Skip to content

fix: prevent stack overflow when abstract components have metadata.component - #2214

Merged
Andriy Knysh (aknysh) merged 6 commits into
mainfrom
aknysh/fix-metadata-component-for-abstract
Mar 17, 2026
Merged

Andriy Knysh (aknysh) merged 6 commits into
mainfrom
aknysh/fix-metadata-component-for-abstract

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented Mar 16, 2026 •

Copy link
Copy Markdown
Member

what

  • Fix fatal error: stack overflow crash when abstract components define metadata.component pointing to the same Terraform component directory as a real component that inherits from them
  • Add visited-set cycle detection to processBaseComponentConfigInternal to detect and report circular component references as clear errors instead of Go runtime crashes
  • Skip component chain resolution for abstract components whose promoted top-level component key creates circular references during Phase 2 metadata inheritance processing
  • metadata.component values on abstract components are still properly inherited by real components through metadata inheritance — only the recursive chain traversal is skipped

why

  • Users reported that atmos describe stacks -s <stack> crashes with fatal error: stack overflow on Atmos versions above v1.200.0 when abstract components have metadata.component set
  • The crash is caused by an interaction between two processing phases: Phase 1 promotes metadata.component to a top-level component key via mergeComponentConfigurations, and Phase 2 (metadata inheritance from PR feat: Add metadata inheritance and metadata.name for workspace key prefix #1812) re-processes this enriched data with a different cache key, causing fresh recursion that creates a circular reference between the abstract and real components
  • The simple component == baseComponent guard at the function entry is insufficient because the cycle involves multiple component name pairs alternating through two recursive call sites (component chain and inherits chain)
  • Abstract components can't be deployed, so following their promoted component key for chain resolution is functionally a no-op — but their metadata.component value should still be inherited by child components (which it is, via the metadata merge at the end of the function)

references

  • Fix doc: docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md
  • Root cause: metadata inheritance feature (PR feat: Add metadata inheritance and metadata.name for workspace key prefix #1812, v1.201.0+) added Phase 2 ProcessBaseComponentConfig call in describe_stacks.go that operates on processed maps with promoted component keys
  • New sentinel error: ErrCircularComponentInheritance in errors/errors.go

Tests added (10 test cases across 5 test functions)

  • TestProcessBaseComponentConfig_CycleDetection (4 cases): direct cycle, cycle via inherits, 3-node cycle (A→B→C→A), valid chain (no false positive)
  • TestProcessBaseComponentConfig_AbstractComponentSkip: reproduces the exact user-reported pattern with abstract + real components sharing the same metadata.component
  • TestProcessBaseComponentConfig_DeepChainNoFalsePositive: 3-level inheritance chain works without false cycle detection
  • TestProcessBaseComponentConfig_AbstractMetadataComponentInherited: verifies metadata.component on abstract base is properly inherited by real components through metadata inheritance
  • TestProcessBaseComponentConfig_AbstractMetadataComponentNotInherited_WhenDisabled: confirms metadata.component is NOT inherited when metadata inheritance is disabled

Summary by CodeRabbit

  • Bug Fixes

    • Detects and stops circular component inheritance, surfacing a clear circular-inheritance error.
    • Skips resolving inherited metadata for abstract components to avoid false-positive cycles and infinite recursion.
  • Documentation

    • Added a detailed article on the circular-inheritance scenario, root cause, fixes, workarounds, and compatibility notes.
    • Updated auth-context appendix link.
  • Tests

    • Added extensive tests for cycle detection, abstract-component behavior, metadata inheritance, and deep/diamond inheritance chains.

Andriy Knysh (aknysh) and others added 2 commits March 16, 2026 15:49
…mponent

Add visited-set cycle detection to processBaseComponentConfigInternal to
detect circular component references and return a clear error instead of
crashing with a fatal stack overflow. Skip component chain resolution for
abstract components whose promoted top-level "component" key creates
circular references in Phase 2 metadata inheritance processing.

metadata.component values on abstract components are still properly
inherited by real components through metadata inheritance — only the
recursive chain traversal is skipped.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner March 16, 2026 21:30
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Mar 16, 2026
@github-actions github-actions Bot added the size/m Medium size PR label Mar 16, 2026
@github-actions

github-actions Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@aknysh Andriy Knysh (aknysh) self-assigned this Mar 16, 2026
The aws.github.io/aws-sdk-go-v2 site is no longer available (404).
Replace with the canonical pkg.go.dev reference for the config package.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@coderabbitai

coderabbitai Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds cycle detection to base-component inheritance resolution via a per-call visited set, skips resolving metadata.component for abstract base components to prevent recursion, introduces exported sentinel ErrCircularComponentInheritance, extends unit tests for inheritance/cycle scenarios, and adds a docs article describing the issue and fixes.

Changes

Cohort / File(s) Summary
Error Declarations
errors/errors.go
Added exported sentinel ErrCircularComponentInheritance mapped to existing circular-inheritance error.
Cycle Detection & Logic
internal/exec/stack_processor_utils.go
Threaded a visited map[string]bool through recursive base-component processing; updated ProcessBaseComponentConfig / processBaseComponentConfigInternal signatures; detect and return ErrCircularComponentInheritance on revisit; short-circuit traversal when base component is abstract.
Tests
internal/exec/stack_processor_utils_test.go
Added many tests: direct/indirect cycle detection, abstract-component skip, deep-chain and diamond patterns, metadata.component inheritance toggles; minor path normalization tweak.
Documentation
docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md, docs/prd/auth-context-multi-identity.md
New fix write-up documenting the stack overflow case and fixes; small external link update.
Manifest
go.mod
Module manifest present in diff context.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as CLI/Caller
    participant Processor as StackProcessor
    participant Repo as ComponentRepo
    participant Errors as Errors

    Caller->>Processor: ProcessBaseComponentConfig(component)
    Processor->>Processor: init visited map
    Processor->>Processor: processBaseComponentConfigInternal(component, visited)
    Processor->>Repo: resolve baseComponent reference
    Repo-->>Processor: baseComponent (may be abstract)
    alt base is abstract
        Processor->>Processor: skip resolving metadata.component for abstract base
        Processor-->>Caller: merged config (without traversing abstract metadata.component)
    else base is not abstract
        alt not visited
            Processor->>Processor: mark (component,base) visited
            Processor->>Processor: recurse processBaseComponentConfigInternal(base, visited)
            Processor-->>Caller: resolved merged component config
        else visited
            Processor->>Errors: return ErrCircularComponentInheritance
            Errors-->>Caller: error
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

major

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main fix: preventing stack overflow when abstract components define metadata.component.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch aknysh/fix-metadata-component-for-abstract
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

@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: 2

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

282-282: Use an OS-neutral dummy path here.

These "/dummy/path" literals bake a Unix path into tests that are otherwise pure unit cases. Hoisting a dummyPath := filepath.Join("dummy", "path") keeps the intent and stays aligned with the repo's Windows-compat rule.

♻️ Proposed cleanup
+dummyPath := filepath.Join("dummy", "path")
+
 err := ProcessBaseComponentConfig(
 	atmosConfig,
 	baseComponentConfig,
 	tt.allComponentsMap,
 	tt.component,
 	"test-stack",
 	tt.baseComponent,
-	"/dummy/path",
+	dummyPath,
 	false,
 	&baseComponents,
 )

As per coding guidelines "Ensure Linux/macOS/Windows compatibility - use filepath.Join() instead of hardcoded path separators, never use forward slash concatenation or hardcoded Unix paths in tests".

Also applies to: 350-350, 394-394, 481-481, 566-566

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/exec/stack_processor_utils_test.go` at line 282, Replace the
hardcoded "/dummy/path" string with an OS-neutral variable: add dummyPath :=
filepath.Join("dummy", "path") at the top of the test and use dummyPath wherever
"/dummy/path" appears; also add an import for "path/filepath" if missing. Update
all occurrences of the literal (the ones noted in the review) to reference
dummyPath so the tests are Windows-compatible.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md`:
- Line 260: The summary line claiming "Added 10 test cases across 5 test
functions" for `internal/exec/stack_processor_utils_test.go` doesn't match the
enumerated breakdown (which lists 8 cases); update either the summary or the
breakdown so they match and are auditable—either change the summary to "8 test
cases across X test functions" or add the two missing test-case descriptions to
the breakdown; also make the same correction in the duplicate section referenced
later (the second occurrence of the table/breakdown) so both places are
consistent.
- Around line 65-79: Reword the "Workaround" section to scope it to pre-fix
versions and warn about preserved inheritance: state that removing
metadata.component from abstract component definitions (the metadata.component
key under abstract components) is only necessary for releases before the fix,
and add a sentence that after the fix metadata.component on abstract components
will still participate in metadata merging and be inherited by concrete
components, so users who rely on that inheritance should not delete the key;
ensure the text references "metadata.component", "abstract component
definitions", and "metadata merging" so readers understand the different
behavior pre- and post-fix.

---

Nitpick comments:
In `@internal/exec/stack_processor_utils_test.go`:
- Line 282: Replace the hardcoded "/dummy/path" string with an OS-neutral
variable: add dummyPath := filepath.Join("dummy", "path") at the top of the test
and use dummyPath wherever "/dummy/path" appears; also add an import for
"path/filepath" if missing. Update all occurrences of the literal (the ones
noted in the review) to reference dummyPath so the tests are Windows-compatible.
🪄 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: 38d03f2a-7dd7-400f-8cd0-ae71962f1b6c

📥 Commits

Reviewing files that changed from the base of the PR and between c9f5f50 and 4c9be5c.

📒 Files selected for processing (5)
  • docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md
  • docs/prd/auth-context-multi-identity.md
  • errors/errors.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/stack_processor_utils_test.go

- Use filepath.Join for dummy paths in tests (Windows compatibility)
- Scope workaround section to pre-fix versions only
- Fix test count in fix doc (8 cases, not 10)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh

Copy link
Copy Markdown
Member Author

CodeRabbit (@coderabbitai) full review please

@coderabbitai

coderabbitai Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

@aknysh Sure, triggering a full review now.


🧠 Learnings used
Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

@aknysh Sure, triggering a full review now.


🧠 Learnings used
Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.

Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: toolchain/http_client_test.go:3-10
Timestamp: 2025-09-10T21:17:55.273Z
Learning: In the cloudposse/atmos repository, imports should never be changed as per samtholiya's coding guidelines.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1714
File: NOTICE:0-0
Timestamp: 2025-11-01T20:24:29.557Z
Learning: In the cloudposse/atmos repository, the NOTICE file is programmatically generated and should not be manually edited. Issues with dependency license URLs in NOTICE will be resolved when upstream package metadata is corrected.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: errors/errors.go:184-203
Timestamp: 2025-12-13T06:10:13.688Z
Learning: cloudposse/atmos: For toolchain work, duplicate/unused error sentinels in errors/errors.go should be cleaned up in a separate refactor PR and not block feature PRs; canonical toolchain sentinels live under toolchain/registry with re-exports in toolchain/errors.go.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 1327
File: internal/exec/describe_affected_utils_2.go:248-248
Timestamp: 2025-06-23T18:50:33.614Z
Learning: When aknysh mentions that a suggestion is not related to the current PR and needs separate tests to be reviewed in a separate PR, this indicates their preference for maintaining focused PR scope and proper test coverage for each change.

Learnt from: osterman
Repo: cloudposse/atmos PR: 768
File: internal/exec/vendor_utils.go:496-513
Timestamp: 2024-11-22T12:38:33.132Z
Learning: In the Atmos project, continue to flag path traversal issues in code reviews but acknowledge when they are expected and acceptable in specific cases.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 768
File: internal/exec/vendor_model_component.go:3-20
Timestamp: 2024-11-18T13:59:10.824Z
Learning: When replacing significant dependencies like `go-getter` that require extensive changes, prefer to address them in separate PRs.
✅ Actions performed

Full review triggered.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/exec/stack_processor_utils.go`:
- Around line 1678-1685: The current global visited map (visitKey := component +
":" + baseComponent; visited[visitKey]) incorrectly treats revisits via
different branches as cycles; change the logic to use a recursion-path (stack)
set instead of a persistent global visited set: mark visitKey as present when
descending into the recursive call and unmark it immediately on return (or
replace with an onStack set that you check for true cycle detection), ensuring
siblings can revisit the same pair without error; update the same pattern at the
other occurrence (around the 1780-1792 block) and add a regression test that
builds a diamond inheritance graph to assert no circular-inheritance error is
raised.
🪄 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: b1c42e02-166e-4038-8219-e5b9fc4bec0a

📥 Commits

Reviewing files that changed from the base of the PR and between c9f5f50 and 4b0edf5.

📒 Files selected for processing (5)
  • docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md
  • docs/prd/auth-context-multi-identity.md
  • errors/errors.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/stack_processor_utils_test.go

Comment thread internal/exec/stack_processor_utils.go Resolved
@coderabbitai

coderabbitai Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

@aknysh Sure, triggering a full review now.


🧠 Learnings used
Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.

Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.

Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: toolchain/http_client_test.go:3-10
Timestamp: 2025-09-10T21:17:55.273Z
Learning: In the cloudposse/atmos repository, imports should never be changed as per samtholiya's coding guidelines.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1714
File: NOTICE:0-0
Timestamp: 2025-11-01T20:24:29.557Z
Learning: In the cloudposse/atmos repository, the NOTICE file is programmatically generated and should not be manually edited. Issues with dependency license URLs in NOTICE will be resolved when upstream package metadata is corrected.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: errors/errors.go:184-203
Timestamp: 2025-12-13T06:10:13.688Z
Learning: cloudposse/atmos: For toolchain work, duplicate/unused error sentinels in errors/errors.go should be cleaned up in a separate refactor PR and not block feature PRs; canonical toolchain sentinels live under toolchain/registry with re-exports in toolchain/errors.go.

Learnt from: osterman
Repo: cloudposse/atmos PR: 768
File: internal/exec/vendor_utils.go:496-513
Timestamp: 2024-11-22T12:38:33.132Z
Learning: In the Atmos project, continue to flag path traversal issues in code reviews but acknowledge when they are expected and acceptable in specific cases.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 768
File: internal/exec/vendor_model_component.go:3-20
Timestamp: 2024-11-18T13:59:10.824Z
Learning: When replacing significant dependencies like `go-getter` that require extensive changes, prefer to address them in separate PRs.

Learnt from: osterman
Repo: cloudposse/atmos PR: 740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.
✅ Actions performed

Full review triggered.

@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

♻️ Duplicate comments (1)
internal/exec/stack_processor_utils.go (1)

1678-1685: ⚠️ Potential issue | 🟠 Major

Use recursion-path tracking, not global visited, for cycle detection.

Line 1680 currently treats any repeated (component, baseComponent) as a cycle across the entire traversal. In valid diamond inheritance, sibling branches can legitimately revisit a pair and trigger a false ErrCircularComponentInheritance.

Suggested fix
  visitKey := component + ":" + baseComponent
  if visited[visitKey] {
  	return fmt.Errorf("%w: '%s' -> '%s' in the stack '%s'",
  		errUtils.ErrCircularComponentInheritance, component, baseComponent, stack)
  }
  visited[visitKey] = true
+ defer delete(visited, visitKey)

Also applies to: 1780-1792

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/exec/stack_processor_utils.go` around lines 1678 - 1685, The current
cycle check uses a global visited map keyed by visitKey (component + ":" +
baseComponent), which flags legitimate diamond/revisited pairs as cycles; change
to recursion-path tracking by using a per-recursion (call-path) set that you add
visitKey to at entry and remove at return (or pass a new map copy down the
recursive call) so only nodes on the current stack are considered cycles; update
the visitKey logic where it's used (the block referencing visitKey and visited)
and apply the same change to the similar block around lines 1780-1792 to ensure
correct cycle detection without false positives.
🧹 Nitpick comments (1)
internal/exec/stack_processor_utils_test.go (1)

287-290: Prefer sentinel-only error assertions to avoid brittle tests.

At Line 289, string matching ties the test to wording. assert.ErrorIs(..., errUtils.ErrCircularComponentInheritance) already verifies the behavior.

Optional test hardening diff
 			if tt.expectedError != "" {
 				require.Error(t, err)
-				assert.Contains(t, err.Error(), tt.expectedError)
 				assert.ErrorIs(t, err, errUtils.ErrCircularComponentInheritance)
 			} else {
 				require.NoError(t, err)
 			}

As per coding guidelines, "Test behavior, not implementation; ... use errors.Is() for error checking."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/exec/stack_processor_utils_test.go` around lines 287 - 290, The test
currently asserts both a substring match on err.Error() and a sentinel
comparison; remove the brittle string assertion and rely on the sentinel-only
check: inside the branch that checks tt.expectedError, keep require.Error(t,
err) and replace the assert.Contains(t, err.Error(), tt.expectedError) with
assert.ErrorIs(t, err, errUtils.ErrCircularComponentInheritance) (or if already
present, remove the duplicate string assertion), ensuring the test uses
errUtils.ErrCircularComponentInheritance as the sole behavioral assertion rather
than matching error text from err.Error().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@errors/errors.go`:
- Line 437: Remove the duplicate sentinel ErrCircularComponentInheritance and
consolidate to use the existing ErrStackCircularInheritance instead: delete the
ErrCircularComponentInheritance declaration and replace all references of
ErrCircularComponentInheritance with ErrStackCircularInheritance (or, if
backwards compatibility is required, make ErrCircularComponentInheritance a
simple alias var ErrCircularComponentInheritance = ErrStackCircularInheritance).
Update any tests or callers that compared against the duplicate sentinel so they
use ErrStackCircularInheritance (or rely on the alias) to ensure errors.Is
checks continue to work.

---

Duplicate comments:
In `@internal/exec/stack_processor_utils.go`:
- Around line 1678-1685: The current cycle check uses a global visited map keyed
by visitKey (component + ":" + baseComponent), which flags legitimate
diamond/revisited pairs as cycles; change to recursion-path tracking by using a
per-recursion (call-path) set that you add visitKey to at entry and remove at
return (or pass a new map copy down the recursive call) so only nodes on the
current stack are considered cycles; update the visitKey logic where it's used
(the block referencing visitKey and visited) and apply the same change to the
similar block around lines 1780-1792 to ensure correct cycle detection without
false positives.

---

Nitpick comments:
In `@internal/exec/stack_processor_utils_test.go`:
- Around line 287-290: The test currently asserts both a substring match on
err.Error() and a sentinel comparison; remove the brittle string assertion and
rely on the sentinel-only check: inside the branch that checks tt.expectedError,
keep require.Error(t, err) and replace the assert.Contains(t, err.Error(),
tt.expectedError) with assert.ErrorIs(t, err,
errUtils.ErrCircularComponentInheritance) (or if already present, remove the
duplicate string assertion), ensuring the test uses
errUtils.ErrCircularComponentInheritance as the sole behavioral assertion rather
than matching error text from err.Error().
🪄 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: 8adcddc9-53cf-42a3-876f-00b04eaebcae

📥 Commits

Reviewing files that changed from the base of the PR and between c9f5f50 and 4b0edf5.

📒 Files selected for processing (5)
  • docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md
  • docs/prd/auth-context-multi-identity.md
  • errors/errors.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/stack_processor_utils_test.go

Comment thread errors/errors.go Resolved

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

♻️ Duplicate comments (2)
errors/errors.go (1)

437-437: ⚠️ Potential issue | 🟠 Major

Avoid splitting circular-inheritance checks across two sentinels.

Line 437 introduces a second sentinel for the same condition already represented by ErrStackCircularInheritance. That can cause inconsistent errors.Is checks across call sites.

Suggested fix
-	ErrCircularComponentInheritance     = errors.New("circular component inheritance detected")
+	ErrCircularComponentInheritance     = ErrStackCircularInheritance
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@errors/errors.go` at line 437, Remove the duplicate sentinel
ErrCircularComponentInheritance and consolidate to use the existing
ErrStackCircularInheritance instead: delete the ErrCircularComponentInheritance
declaration and update any references to use ErrStackCircularInheritance so all
callers can rely on a single sentinel for errors.Is checks (search for
ErrCircularComponentInheritance and replace with ErrStackCircularInheritance,
keeping the original ErrStackCircularInheritance declaration intact).
internal/exec/stack_processor_utils.go (1)

1678-1685: ⚠️ Potential issue | 🟠 Major

Visited tracking should be scoped to the active recursion path.

Line 1680 checks a traversal-global map, but entries are never removed after returning (set at Line 1684). That can flag valid non-cyclic graphs (shared ancestors via sibling branches, including metadata.inherits recursion around Line 1781) as circular.

Suggested fix.
  visitKey := component + ":" + baseComponent
  if visited[visitKey] {
  	return fmt.Errorf("%w: '%s' -> '%s' in the stack '%s'",
  		errUtils.ErrCircularComponentInheritance, component, baseComponent, stack)
  }
  visited[visitKey] = true
+ defer delete(visited, visitKey)

Also applies to: 1780-1792

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/exec/stack_processor_utils.go` around lines 1678 - 1685, The visited
map is being used globally across the traversal which causes false positives for
cycles when sibling branches share ancestors; scope visited to the active
recursion path by removing the visitKey when unwinding recursion: after setting
visited[visitKey] = true add a deferred or explicit delete(visited, visitKey) so
the entry is removed on function return (apply the same change to the other
block handling metadata.inherits around the code referencing
visitKey/component/baseComponent) to ensure visited only represents the current
recursion stack.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@errors/errors.go`:
- Line 437: Remove the duplicate sentinel ErrCircularComponentInheritance and
consolidate to use the existing ErrStackCircularInheritance instead: delete the
ErrCircularComponentInheritance declaration and update any references to use
ErrStackCircularInheritance so all callers can rely on a single sentinel for
errors.Is checks (search for ErrCircularComponentInheritance and replace with
ErrStackCircularInheritance, keeping the original ErrStackCircularInheritance
declaration intact).

In `@internal/exec/stack_processor_utils.go`:
- Around line 1678-1685: The visited map is being used globally across the
traversal which causes false positives for cycles when sibling branches share
ancestors; scope visited to the active recursion path by removing the visitKey
when unwinding recursion: after setting visited[visitKey] = true add a deferred
or explicit delete(visited, visitKey) so the entry is removed on function return
(apply the same change to the other block handling metadata.inherits around the
code referencing visitKey/component/baseComponent) to ensure visited only
represents the current recursion stack.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 588c4c05-340b-4164-a258-ba41ebed2dd8

📥 Commits

Reviewing files that changed from the base of the PR and between c9f5f50 and 4b0edf5.

📒 Files selected for processing (5)
  • docs/fixes/2026-03-16-metadata-component-abstract-stack-overflow.md
  • docs/prd/auth-context-multi-identity.md
  • errors/errors.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/stack_processor_utils_test.go

@codecov

codecov Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.88%. Comparing base (fd3e534) to head (26591c7).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/exec/stack_processor_utils.go 90.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2214      +/-   ##
==========================================
+ Coverage   76.84%   76.88%   +0.04%     
==========================================
  Files        1001     1001              
  Lines       95349    95361      +12     
==========================================
+ Hits        73274    73322      +48     
+ Misses      17806    17775      -31     
+ Partials     4269     4264       -5     
Flag Coverage Δ
unittests 76.88% <90.00%> (+0.04%) ⬆️

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

Files with missing lines Coverage Δ
errors/errors.go 100.00% <ø> (ø)
internal/exec/stack_processor_utils.go 81.60% <90.00%> (+0.60%) ⬆️

... and 4 files with indirect coverage changes

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

@mergify

mergify Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Andriy Knysh (@aknysh)? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Mar 16, 2026
Andriy Knysh (aknysh) and others added 2 commits March 16, 2026 19:50
- Add defer delete to visited-set for correct DFS backtracking, preventing
  false cycle detection on diamond inheritance patterns
- Add TestProcessBaseComponentConfig_DiamondInheritance regression test
- Remove brittle string matching from error assertions, use errors.Is only
- Alias ErrCircularComponentInheritance to ErrStackCircularInheritance
  instead of creating a duplicate sentinel

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…omponent-for-abstract

# Conflicts:
#	docs/prd/auth-context-multi-identity.md
@mergify mergify Bot removed the conflict This PR has conflicts label Mar 16, 2026

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

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

404-478: Diamond regression test should run both branches in one traversal.

Right now left and right are evaluated in separate top-level calls, so visited is reinitialized each time. That can miss the sibling-branch revisit case this test description calls out.

Suggested test adjustment
 func TestProcessBaseComponentConfig_DiamondInheritance(t *testing.T) {
 	ClearBaseComponentConfigCache()

 	allComponentsMap := map[string]any{
 		"base": map[string]any{
 			"vars": map[string]any{"from_base": "base-value"},
 		},
 		"left": map[string]any{
 			"metadata": map[string]any{
 				"inherits": []any{"base"},
 			},
 			"vars": map[string]any{"from_left": "left-value"},
 		},
 		"right": map[string]any{
 			"metadata": map[string]any{
 				"inherits": []any{"base"},
 			},
 			"vars": map[string]any{"from_right": "right-value"},
 		},
+		"diamond-root": map[string]any{
+			"metadata": map[string]any{
+				"inherits": []any{"left", "right"},
+			},
+		},
 	}

 	atmosConfig := &schema.AtmosConfiguration{}
 	baseComponentConfig := &schema.BaseComponentConfig{
 		BaseComponentVars:     map[string]any{},
 		BaseComponentSettings: map[string]any{},
 		BaseComponentEnv:      map[string]any{},
 	}

-	// Process "left" first.
 	baseComponents := []string{}
 	err := ProcessBaseComponentConfig(
 		atmosConfig,
 		baseComponentConfig,
 		allComponentsMap,
 		"child",
 		"test-stack",
-		"left",
+		"diamond-root",
 		filepath.Join("dummy", "path"),
 		false,
 		&baseComponents,
 	)
-	require.NoError(t, err, "Left branch of diamond should not error")
-
-	// Process "right" — this reaches "base" again via a sibling branch.
-	// Without defer delete in the visited set, this would falsely trigger cycle detection.
-	ClearBaseComponentConfigCache()
-	baseComponentConfig2 := &schema.BaseComponentConfig{
-		BaseComponentVars:     map[string]any{},
-		BaseComponentSettings: map[string]any{},
-		BaseComponentEnv:      map[string]any{},
-	}
-	baseComponents2 := []string{}
-	err = ProcessBaseComponentConfig(
-		atmosConfig,
-		baseComponentConfig2,
-		allComponentsMap,
-		"child",
-		"test-stack",
-		"right",
-		filepath.Join("dummy", "path"),
-		false,
-		&baseComponents2,
-	)
-	require.NoError(t, err, "Right branch of diamond should not error")
-	assert.Equal(t, "base-value", baseComponentConfig2.BaseComponentVars["from_base"],
-		"Base vars should be inherited through right branch")
+	require.NoError(t, err, "Diamond traversal in one DFS should not error")
+	assert.Equal(t, "base-value", baseComponentConfig.BaseComponentVars["from_base"])
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/exec/stack_processor_utils_test.go` around lines 404 - 478, The test
currently calls ProcessBaseComponentConfig twice (once via "left" and once via
"right") which resets the visited set and misses the true sibling-branch revisit
case; instead define a "child" component in allComponentsMap with
metadata.inherits = []any{"left","right"} and invoke ProcessBaseComponentConfig
a single time for the "child" component (use the same componentName/parentName
so traversal explores both "left" and "right" in one run), remove the separate
ClearBaseComponentConfigCache()/second call, and assert that base vars from
"base" are present after that single traversal; reference
ProcessBaseComponentConfig and the test
TestProcessBaseComponentConfig_DiamondInheritance to make the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@internal/exec/stack_processor_utils_test.go`:
- Around line 404-478: The test currently calls ProcessBaseComponentConfig twice
(once via "left" and once via "right") which resets the visited set and misses
the true sibling-branch revisit case; instead define a "child" component in
allComponentsMap with metadata.inherits = []any{"left","right"} and invoke
ProcessBaseComponentConfig a single time for the "child" component (use the same
componentName/parentName so traversal explores both "left" and "right" in one
run), remove the separate ClearBaseComponentConfigCache()/second call, and
assert that base vars from "base" are present after that single traversal;
reference ProcessBaseComponentConfig and the test
TestProcessBaseComponentConfig_DiamondInheritance to make the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: abc6fcd2-917a-4315-a859-4794441ba91a

📥 Commits

Reviewing files that changed from the base of the PR and between 4b0edf5 and 26591c7.

📒 Files selected for processing (3)
  • errors/errors.go
  • internal/exec/stack_processor_utils.go
  • internal/exec/stack_processor_utils_test.go

@aknysh
Andriy Knysh (aknysh) merged commit e0dc13b into main Mar 17, 2026
63 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the aknysh/fix-metadata-component-for-abstract branch March 17, 2026 01:01
@github-actions

Copy link
Copy Markdown

These changes were released in v1.210.0-rc.1.

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