Skip to content

perf(stacks): dedupe per-identity auth in nested terraform.state resolution - #2656

Merged
Andriy Knysh (aknysh) merged 2 commits into
cloudposse:mainfrom
sgtoj:perf/dedupe-nested-component-auth
Jun 23, 2026
Merged

Andriy Knysh (aknysh) merged 2 commits into
cloudposse:mainfrom
sgtoj:perf/dedupe-nested-component-auth

Conversation

@sgtoj

@sgtoj Brian Ojeda (sgtoj) commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

what

  • Extends the per-component AuthManager memoization introduced in fix(stacks): scope and cache per-component auth in describe stacks #2652 from the top-level describe stacks pass into the nested resolution path that runs while templates and YAML functions are evaluated (!terraform.state, !terraform.output, atmos.Component(...)).
  • Adds a process-scoped nestedAuthManagerCache, consulted by resolveAuthManagerForNestedComponent, keyed by the parent auth chain + a deterministic JSON fingerprint of the component's auth section.
  • Extracts the key logic into a shared buildComponentAuthCacheKey used by both the processor cache (fix(stacks): scope and cache per-component auth in describe stacks #2652) and this nested path, so the two keying strategies cannot drift.
  • Caches only successful, non-nil resolutions; ResetStateCache() also clears the new cache (kept consistent with the terraformStateCache it pairs with). Neither is reset in production.

why

Measured — atmos describe stacks -s <stack> on a large real-world stack (credentials provided via auth exec, 45s cap; only the binary under test varies):

build wall time per-component auth cycles
latest release DNF (>45s) —
main (includes #2652) ~17–19s 44
this PR (#2652 + nested dedup) ~10–11s 5

Output was verified equivalent to main: the remaining run-to-run differences are pre-existing auto_provision_workdir_for_outputs / tofu output provisioning nondeterminism present on both builds (same identity resolved throughout, no new errors). A matched-output pair differed by fewer lines than the main-vs-main noise floor.

The nested path is shared by describe affected, list, and terraform --all/--query. On a large multi-component change, the full per-identity auth cycles during describe affected likewise drop from scaling with the number of resolved components to roughly one-per-identity, with the rest served from the cache.

test plan

  • go build ./... && go test ./internal/exec/... — new unit tests cover key behavior, dedupe-by-identity, parent-chain isolation, errors-not-cached, unserializable-section-not-cached, and the ResetStateCache coupling.
  • custom-gcl run --new-from-rev=main → 0 issues.
  • Real-repo benchmark above.

references

@sgtoj
Brian Ojeda (sgtoj) requested a review from a team as a code owner June 23, 2026 00:05
@atmos-pro

atmos-pro Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions github-actions Bot added the size/m Medium size PR label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 840d3745-e11e-406f-8cb6-2787c260629a

📥 Commits

Reviewing files that changed from the base of the PR and between fac5b1e and 5094cf1.

📒 Files selected for processing (1)
  • internal/exec/describe_stacks_component_processor.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/exec/describe_stacks_component_processor.go

📝 Walkthrough

Walkthrough

Adds a process-scoped nestedAuthManagerCache (sync.Map) to memoize resolved AuthManager instances during nested !terraform.state/!terraform.output evaluation. Shares buildComponentAuthCacheKey between top-level describe-stacks and nested resolution paths. Extends ResetStateCache to also clear the nested auth cache for consistency.

Changes

Nested AuthManager Deduplication

Layer / File(s) Summary
nestedAuthManagerCache: cache data, key builder, and resolver wrapper
internal/exec/terraform_nested_auth_helper.go
Declares nestedAuthManagerCache (sync.Map), ResetNestedAuthManagerCache, buildComponentAuthCacheKey (parent chain + JSON fingerprint of auth section), and resolveCachedComponentAuthManager wrapper that stores only successful non-nil results and bypasses caching for unserializable sections.
Call site wiring and ResetStateCache coupling
internal/exec/terraform_nested_auth_helper.go, internal/exec/terraform_state_utils.go
resolveAuthManagerForNestedComponent now calls resolveCachedComponentAuthManager instead of createComponentAuthManager directly for the default-identity case. ResetStateCache additionally calls ResetNestedAuthManagerCache to keep both caches consistent.
describe_stacks_component_processor delegates to shared cache-key helper
internal/exec/describe_stacks_component_processor.go
componentAuthCacheKey is rewritten to delegate to buildComponentAuthCacheKey, removing the local JSON-fingerprinting logic and the encoding/json import.
Unit tests for cache behavior
internal/exec/terraform_nested_auth_cache_test.go
Tests cover key determinism, deduplication by identity, non-memoization of errors, always-resolving for unserializable sections, and ResetStateCache clearing the nested auth cache.
Fix documentation
docs/fixes/2026-06-22-dedupe-nested-component-auth.md
Documents the auth overcount problem, the nestedAuthManagerCache design, safety invariants for manager reuse, and example log-line reduction.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • cloudposse/atmos#2652: Implements the same parent-chain + auth-section fingerprint cache-key pattern for top-level describe-stacks auth deduplication — this PR extends that pattern to the nested resolution path.

Suggested labels

minor

Suggested reviewers

  • aknysh
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: deduplicating per-identity authentication in nested terraform.state resolution, which is the core performance improvement of this PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/exec/terraform_nested_auth_cache_test.go (1)

23-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a table-driven layout for the multi-scenario keying test.

This test validates several distinct scenarios in one body; converting to table-driven cases will align with repo test conventions and make future additions safer.

As per coding guidelines, "**/*_test.go: Use table-driven tests for testing multiple scenarios in Go."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/exec/terraform_nested_auth_cache_test.go` around lines 23 - 55,
Refactor TestBuildComponentAuthCacheKey to use table-driven testing by creating
a test case struct containing the inputs (parent authentication manager and
section data) and expected validation results, then define a slice of test cases
covering all current scenarios (identical sections, different sections, same
section with different parents, distinct parent chains, and unserializable
sections), and finally replace the current inline assertion logic with a loop
that iterates through the test cases and runs buildComponentAuthCacheKey with
each case's inputs while validating the corresponding outputs.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/fixes/2026-06-22-dedupe-nested-component-auth.md`:
- Around line 17-22: The fenced code block in the markdown file is missing a
language declaration on the opening backticks. To fix this, add a language
identifier (such as `text`) to the opening triple backticks of the code block
that contains the GetTerraformState function call hierarchy. Change the opening
from bare triple backticks to triple backticks followed by the language name.

---

Nitpick comments:
In `@internal/exec/terraform_nested_auth_cache_test.go`:
- Around line 23-55: Refactor TestBuildComponentAuthCacheKey to use table-driven
testing by creating a test case struct containing the inputs (parent
authentication manager and section data) and expected validation results, then
define a slice of test cases covering all current scenarios (identical sections,
different sections, same section with different parents, distinct parent chains,
and unserializable sections), and finally replace the current inline assertion
logic with a loop that iterates through the test cases and runs
buildComponentAuthCacheKey with each case's inputs while validating the
corresponding outputs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: bc412463-661d-4877-88a6-1f4596e69cef

📥 Commits

Reviewing files that changed from the base of the PR and between e56077c and c0eabf0.

📒 Files selected for processing (5)
  • docs/fixes/2026-06-22-dedupe-nested-component-auth.md
  • internal/exec/describe_stacks_component_processor.go
  • internal/exec/terraform_nested_auth_cache_test.go
  • internal/exec/terraform_nested_auth_helper.go
  • internal/exec/terraform_state_utils.go

…lution

Extend the per-component AuthManager memoization beyond the top-level
describe-stacks pass into the nested resolution path that runs while
templates and YAML functions are evaluated.

When a component references another via !terraform.state/!terraform.output,
resolveAuthManagerForNestedComponent ran a full auth cycle (credential
writes, file locks, keyring rebuilds) once per distinct target component,
even when many targets share a single identity. The existing
terraformStateCache only dedupes repeat reads of the same target.

Add a process-scoped nestedAuthManagerCache keyed by parent chain + a
deterministic JSON fingerprint of the auth section, extracted into a shared
buildComponentAuthCacheKey so the processor and the nested path cannot drift.
Only successful, non-nil results are cached; ResetStateCache clears it
alongside the state cache. Reference docs/fixes/2026-06-22-dedupe-nested-component-auth.md.

Related to cloudposse#2639.
@sgtoj
Brian Ojeda (sgtoj) force-pushed the perf/dedupe-nested-component-auth branch from c0eabf0 to fac5b1e Compare June 23, 2026 00:17
@sgtoj

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit review (amended into the single commit):

  • docs/fixes (MD040): added a text language identifier to the fenced call-hierarchy code block.
  • terraform_nested_auth_cache_test.go: refactored TestBuildComponentAuthCacheKey to a table-driven (pairwise) layout covering identical sections, different sections, inherited-vs-auto-detected parent, and distinct parent chains; moved the unserializable-section case into its own TestBuildComponentAuthCacheKey_NonSerializable.

go build ./..., the nested-cache tests, and custom-gcl run --new-from-rev=main are all green.

@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Jun 23, 2026
@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.05%. Comparing base (63033b0) to head (5094cf1).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2656   +/-   ##
=======================================
  Coverage   80.04%   80.05%           
=======================================
  Files        1361     1361           
  Lines      127499   127525   +26     
=======================================
+ Hits       102059   102088   +29     
+ Misses      19774    19771    -3     
  Partials     5666     5666           
Flag Coverage Δ
unittests 80.05% <100.00%> (+<0.01%) ⬆️

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

Files with missing lines Coverage Δ
...ternal/exec/describe_stacks_component_processor.go 95.86% <100.00%> (+0.80%) ⬆️
internal/exec/terraform_nested_auth_helper.go 75.78% <100.00%> (+7.74%) ⬆️
internal/exec/terraform_state_utils.go 80.00% <100.00%> (+0.23%) ⬆️

... and 12 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@aknysh
Andriy Knysh (aknysh) merged commit 12f9e3d into cloudposse:main Jun 23, 2026
57 of 59 checks passed
@atmos-pro

atmos-pro Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.222.0-rc.8.

Andriy Knysh (aknysh) added a commit that referenced this pull request Jul 10, 2026
…entity (#2712)

* fix(auth): atmos.Component() nested lookups could lose or reuse the wrong identity

Two defects in the v1.222.0 per-component/nested auth-caching work
(#2652/#2656) could surface as "no valid credential sources found /
no EC2 IMDS role found" under GitHub OIDC auth with no ambient AWS
credentials:

- authContextWrapper.GetChain() always returns an empty slice, which
  the nested-auth cache used to disambiguate parents. Two different
  real identities reaching a nested lookup via atmos.Component() or
  !terraform.state/!terraform.output could collide on the same cache
  key and silently reuse the wrong identity's AuthManager. Wrapper-
  rooted parents are now never cached.
- atmos.Component() always fetched a target's terraform output using
  the enclosing component's credentials verbatim, unlike
  !terraform.state/!terraform.output, even when the target declared
  its own default-identity auth section. It now resolves the
  target's own auth via resolveAuthManagerForNestedComponent,
  falling back to the enclosing component's context as before.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(auth): !terraform.output never resolved the nested target's own identity

The !terraform.output YAML function fetched a nested component's outputs
using the enclosing component's authContext/authManager verbatim — the
same defect just fixed for atmos.Component(). Only !terraform.state
actually routed through resolveAuthManagerForNestedComponent; the
target-aware resolution was lost when output fetching moved into
pkg/terraform/output (which cannot call back into internal/exec).

- defaultOutputGetter.GetOutput now resolves the target's own auth
  section via resolveNestedOutputAuth (target default identity wins;
  enclosing auth kept when the target has none, on resolver error, or
  when auth is disabled), mirroring GetTerraformState.
- The YAML entry propagates AuthDisabled via authContextWrapper when no
  AuthManager exists, mirroring !terraform.state, so disabled-auth
  contexts never trigger target authentication.
- Corrected the fix doc's false parity claim and recorded two audited
  same-class follow-ups (identity-less result-cache keys; store
  default-identity injection asymmetry).

Tests: TestResolveNestedOutputAuth (8 sub-tests, written failing-first).

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(auth): use generated MockAuthManager and cover AuthDisabled wrapper propagation

Address PR #2712 review feedback and patch coverage:

- Replace the hand-written fakeNestedOutputAuthManager stub with the
  mockgen-generated types.NewMockAuthManager, per the repo's
  mock-generation convention (CodeRabbit review).
- Add TestAuthDisabledPropagatesWrapperToOutputGetter covering both
  branches of the new AuthDisabled wrapper propagation in
  processTagTerraformOutputWithContext — the uncovered lines behind
  the 60% patch coverage on yaml_func_terraform_output.go.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Co-authored-by: Andriy Knysh <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/m Medium size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants