Skip to content

Improve performance heatmap - #1611

Merged
Andriy Knysh (aknysh) merged 26 commits into
mainfrom
add-validate-flag
Oct 11, 2025
Merged

Andriy Knysh (aknysh) merged 26 commits into
mainfrom
add-validate-flag

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented Oct 10, 2025 •

Copy link
Copy Markdown
Member

what

  • Fix --heatmap flag not working with terraform, helmfile, and packer commands
  • Implement advanced performance tracking with self-time vs total-time separation
  • Fix recursive function performance tracking to show accurate counts AND accurate timing
  • Improve heatmap display with consistent metrics and informative legend
  • Add comprehensive tests for heatmap functionality and recursive tracking

atmos describe stacks --heatmap
image
atmos terraform plan vpc -s uw2-prod --heatmap
image

why

Heatmap Flag Fix

The --heatmap flag was not working for terraform, helmfile, and packer commands because:

  • These commands use DisableFlagParsing = true to pass native flags through to underlying tools
  • When flag parsing is disabled, Cobra doesn't parse the --heatmap flag
  • The PersistentPreRun hook couldn't detect the flag via cmd.Flags().GetBool("heatmap")
  • Performance tracking was never enabled, so no data collected

Performance Tracking Enhancement

--heatmap showed inconsistent timing metrics for long-running commands:

  • Elapsed time was correct
  • Individual function totals were massively inflated (- approximately 1,890x inflation)
  • Root cause: Unable to show accurate call counts for recursive functions without timing inflation

Requirement: Show true call volume (e.g., 1,890 calls) with accurate timing (no inflation) and consistent metrics.

changes

Advanced Performance Tracking (Self-Time vs Total-Time)

Implemented professional-grade profiling metrics that separate:

  • Total time (wall-clock): Includes time spent in child function calls
  • Self-time: Actual work done in the function, excluding children
  • Accurate recursive tracking: Shows ALL calls including recursive ones with correct timing

Key Features:

  1. Goroutine-local call stack tracking - Each goroutine maintains its own call stack
  2. Child time accumulation - Each stack frame tracks time spent in children
  3. Self-time calculation - selfTime = totalTime - childTime
  4. HDR Histogram on self-time - P95 based on actual work, not wall-clock
  5. Direct recursive tracking - No wrapper pattern needed, tracks every call accurately

Benefits:

  • Accurate recursive tracking: Shows true call counts (e.g., 1,890 calls) with correct timing
  • No inflation: Self-time excludes child execution, total-time includes it
  • Better insights: Identify where time is spent (total) vs where work is done (self-time)
  • Professional profiling: Same metrics as pprof, but function-level and easier to use

Example Output:

Function                                 Count    Total      Avg        Max        P95
utils.processCustomTags                  1024     4.27ms     4µs        146µs      15µs
  • Count: 1024 - ALL calls including recursive ones
  • Total: 4.27ms - wall-clock time including all children
  • Avg: 4µs - average self-time per call (actual work only)
  • Max: 146µs - maximum self-time for a single call (excludes children)
  • P95: 15µs - 95th percentile of self-time

Metric Consistency Fix

Changed Max to track self-time instead of total-time:

  • All three metrics (Avg, Max, P95) consistently track self-time
  • Rationale: Enables accurate comparison between metrics for identifying performance outliers

TUI Legend

Added informative legend to heatmap TUI:

Count: # calls (incl. recursion) | Total: wall-clock (incl. children & recursion) |
Avg: avg self-time | Max: max self-time | P95: 95th percentile self-time
  • Appears after the header in all visualization modes
  • Explains what each metric means
  • Clarifies that Count and Total include recursion
  • Helps users understand self-time vs total-time

Recursive Function Updates

Benefits:

  • Shows true call volume (e.g., 1,024 calls instead of 1)
  • Timing remains accurate via self-time calculation
  • No wrapper pattern complexity needed

Documentation

Updated profiling documentation:

  • "Understanding Total vs Self-Time" tip reflects that all three metrics now track self-time
  • Updated metric descriptions with accurate explanations
  • Added examples showing self-time context for outlier detection

Heatmap Flag Improvements

  • Added helper function to manually parse --heatmap from os.Args for commands with DisableFlagParsing = true
  • Integrated heatmap flag detection in terraform, helmfile, and packer commands
  • Added test coverage for heatmap flag detection

Enhanced Performance Tracking Coverage

  • Added perf.Track() to UnmarshalYAMLFromFile to track YAML parsing performance
  • Ensures complete visibility into YAML processing call chains during merge operations

testing

Performance Tracking Tests

New self-time tracking tests:

  1. TestSelfTimeVsTotalTime - Verifies self-time excludes child time
  2. TestNestedFunctionSelfTime - Tests multi-level nesting (grandparent → parent → child)
  3. TestDirectRecursionWithSelfTime - Tests direct recursion with accurate counts AND timing

Updated existing tests:

  • All 20 perf tests passing ✅
  • Tests verify self-time calculation accuracy for all three metrics (Avg, Max, P95)

Recursive function tests:

  1. TestRecursiveFunctionTracking - Wrapper pattern verification
  2. TestRecursiveFunctionWrongPattern - Demonstrates inflation with wrong pattern
  3. TestMultipleRecursiveFunctionsIndependent - Independent function tracking
  4. TestYAMLConfigProcessingRecursion - YAML import hierarchy (50 levels deep)
  5. TestYAMLConfigProcessingMultipleImports - Fan-out import pattern
  6. TestProcessBaseComponentConfigRecursion - Component inheritance (15 levels deep)

Heatmap UI Tests

Updated heatmap tests:

  • Updated legend verification tests
  • All 36 heatmap tests passing ✅

Heatmap Flag Tests

✅ TestTerraformHeatmapFlag passes successfully
✅ Manual testing confirms --heatmap works with:

  • atmos terraform plan <component> -s <stack> --heatmap
  • atmos helmfile <subcommand> <component> -s <stack> --heatmap
  • atmos packer <subcommand> <component> -s <stack> --heatmap

Build Verification

✅ All linter checks passing (golangci-lint)
✅ Full project builds successfully
✅ Website documentation builds without errors
✅ All 56 tests passing (20 perf + 36 heatmap)

expected impact

For Recursive Functions

  • Before: Count = 1, accurate timing (using wrapper pattern, recursion hidden)
  • After: Count = 1,890 (shows true call volume), accurate timing (via self-time tracking)

Performance Insights

  • Total time: Identify functions contributing most to overall execution time
  • Self-time: Identify where actual work is being done (optimization targets)
  • Consistent metrics: All three metrics (Avg, Max, P95) track self-time for accurate comparison
  • Accurate P95: Based on self-time, more meaningful for performance analysis

Better User Experience

  • TUI legend: Users immediately understand what each metric means
  • Accurate Max: Identifies performance outliers in function's own work, not including children

Summary by CodeRabbit

  • New Features

    • --heatmap CLI flag available for Terraform, Helmfile, and Packer; heatmap UI adds a legend and wider duration columns.
    • New Terraform "affected" and query execution workflows.
  • Improvements

    • New profiler-related CLI flags and a performance-tracking toggle.
    • Performance metrics now emphasize self-time (Avg, P95, Max) for clearer bottleneck identification.
    • Clearer, more actionable user-facing error messages; telemetry notices suppressed by default.
  • Documentation

    • Profiling guide updated to explain Total vs Self-Time.
  • Chores

    • Go toolchain and example image versions bumped.

@github-actions github-actions Bot added the size/xl Extra large size PR label Oct 10, 2025
@aknysh Andriy Knysh (aknysh) added the no-release Do not create a new release (wait for additional code changes) label Oct 10, 2025
@mergify

mergify Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@mergify

mergify Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@aknysh Andriy Knysh (aknysh) changed the title Improve performance heatmap. Add --validate CLI flag Improve performance heatmap Oct 10, 2025
@aknysh

Copy link
Copy Markdown
Member Author

CodeRabbit (@coderabbitai) full review

@coderabbitai

coderabbitai Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Oct 10, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds raw-CLI heatmap flag handling to enable perf tracking from command entrypoints; reworks perf to record per-goroutine self-time; centralizes sentinel errors; adds Helmfile config validation and Terraform affected/query flows with tests; updates CLI/UI formatting, flags, docs, and dependencies.

Changes

Cohort / File(s) Summary
CLI heatmap plumbing & heatmap UI
cmd/cmd_utils.go, cmd/helmfile.go, cmd/packer.go, cmd/terraform_commands.go, cmd/root.go, pkg/ui/heatmap/heatmap.go, pkg/ui/heatmap/render.go, pkg/ui/heatmap/heatmap_test.go
Add raw-arg scanning helper enableHeatmapIfRequested() to enable perf.EnableTracking(true) when --heatmap is present; widen duration columns; add legend rendering and tests; minor root formatting tweaks.
Performance subsystem (perf)
pkg/perf/perf.go, pkg/perf/perf_test.go, pkg/utils/yaml_utils.go
Replace timing model with per-goroutine CallStack/StackFrame and SelfTime accounting; add EnableTracking(bool); update Metric/Row/snapshot logic; add extensive tests and perf.Track instrumentation in YAML unmarshal.
Terraform affected & query flows
internal/exec/terraform_affected.go, internal/exec/terraform_affected_test.go, internal/exec/terraform_query.go
Implement ExecuteTerraformAffected (get affected components, add dependents, execute in dependency order) with tests/benchmarks; add ExecuteTerraformQuery to init config, list stacks, and process components.
Terraform utils & tests (flag parsing)
internal/exec/terraform_utils.go, internal/exec/terraform_utils_test.go
Add/adjust flag-parsing helpers (e.g., parseUploadStatusFlag), change test skip logic/benchmarks, remove prior perf usage in this file.
Errors centralization
errors/errors.go, internal/exec/terraform.go, tests/snapshots/...
Add sentinel errors for Terraform/Helmfile in errors package; migrate references to errUtils.*; update snapshots and expected error strings.
Helmfile config validation
internal/exec/helmfile_utils.go, internal/exec/helmfile.go, internal/exec/helmfile_utils_test.go
Add checkHelmfileConfig(*AtmosConfiguration) with perf tracking, return specific ErrMissing... sentinel errors; update call sites to pass pointer; add unit tests and benchmark.
CLI flags & stripping
pkg/config/const.go, internal/exec/cli_utils.go
Add identity/profiler/heatmap flag constants and include profiler/heatmap flags in commonFlags for stripping when invoking underlying tools.
Packer component validation
internal/exec/packer.go
Add ValidateComponent step after locked-check and return structured invalid-component errors when validation fails.
Stack processor recursion internals
internal/exec/stack_processor_utils.go
Introduce internal recursive implementations (e.g., processYAMLConfigFileWithContextInternal) and redirect public wrappers to them; external behavior preserved.
Tooling, examples, docs, deps
go.mod, examples/quick-start-advanced/Dockerfile, website/docs/integrations/atlantis.mdx, website/docs/troubleshoot/profiling.mdx
Bump Go directive and multiple module versions; update Atmos version (1.194.0 → 1.195.0) in Dockerfile/docs; expand profiling docs to explain SelfTime vs Total.
Misc tests / telemetry / snapshots
cmd/terraform_test.go, tests/fixtures/..., tests/snapshots/..., tests/test-cases/metadata.yaml
Add TestTerraformHeatmapFlag; disable telemetry in a fixture; update snapshots and locked-component error strings.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant User
  participant CLI as Atmos CLI
  participant Utils as enableHeatmapIfRequested
  participant Perf as pkg/perf

  User->>CLI: atmos <cmd> ... --heatmap ...
  CLI->>Utils: enableHeatmapIfRequested()
  Utils->>Utils: scan os.Args for "--heatmap"
  alt flag present
    Utils->>Perf: EnableTracking(true)
  else absent
    Utils-->>CLI: no-op
  end
  CLI->>CLI: continue command execution
Loading
sequenceDiagram
  autonumber
  participant Cmd as atmos terraform affected
  participant Exec as ExecuteTerraformAffected
  participant GA as getAffectedComponents
  participant Desc as ExecuteDescribeAffectedWith...
  participant Dep as addDependentsToAffected
  participant Run as executeAffectedComponents
  participant Comp as executeTerraformAffectedComponentInDepOrder

  Cmd->>Exec: ExecuteTerraformAffected(args, info)
  Exec->>GA: getAffectedComponents(args)
  GA->>Desc: choose repo/clone/default path -> call DescribeAffected
  GA-->>Exec: affectedList
  Exec->>Dep: addDependentsToAffected(affectedList)
  Dep-->>Exec: augmentedList
  Exec->>Run: executeAffectedComponents(augmentedList,...)
  loop per component in dep order
    Run->>Comp: executeTerraformAffectedComponentInDepOrder(...)
  end
  Run-->>Exec: result
  Exec-->>Cmd: return
Loading
sequenceDiagram
  autonumber
  participant Cmd as atmos terraform query
  participant Query as ExecuteTerraformQuery
  participant Cfg as cfg.InitCliConfig
  participant Stacks as ExecuteDescribeStacks
  participant Walk as walkTerraformComponents
  participant Proc as processTerraformComponent

  Cmd->>Query: ExecuteTerraformQuery(info)
  Query->>Cfg: InitCliConfig(...)
  Cfg-->>Query: atmosConfig
  Query->>Stacks: ExecuteDescribeStacks(...)
  Stacks-->>Query: stacks
  Query->>Walk: walkTerraformComponents(stacks)
  loop per component
    Walk->>Proc: processTerraformComponent(atmosConfig, info,...)
  end
  Query-->>Cmd: return
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested reviewers

  • osterman

Pre-merge checks and finishing touches

✅ 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 “Improve performance heatmap” succinctly captures the primary focus of the changeset by indicating enhancements to the performance heatmap feature, which aligns with the PR’s objectives around flag detection, self-time metrics, and TUI legend updates. It is clear, concise, and directly related to the main improvements without extraneous detail.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-validate-flag

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f13d968 and efb8095.

📒 Files selected for processing (1)
  • internal/exec/helmfile.go (9 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All comments must end with periods; comments should be complete sentences (golangci-lint godot).
Organize imports into three groups separated by blank lines: standard library, third-party, and github.com/cloudposse/atmos packages; sort alphabetically within each group and preserve existing aliases.
Wrap all errors using static errors from errors/errors.go; prefer errors.Join for multiple errors; use fmt.Errorf with %w for context; check with errors.Is; never use dynamic errors directly.
Distinguish structured logging from UI output: use stderr for prompts/status/errors needing user action, stdout only for data; never use logging for UI elements.
Most text UI must go to stderr; only data/results go to stdout; prefer utils.PrintfMessageToTUI for UI messages.
Ensure cross-platform compatibility: prefer SDKs over external binaries; use filepath.Join, os.PathSeparator, and runtime.GOOS for OS-specific logic; add build constraints if needed.

Files:

  • internal/exec/helmfile.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • internal/exec/helmfile.go
@(cmd|internal|pkg)/**/!(*_test).go

📄 CodeRabbit inference engine (CLAUDE.md)

@(cmd|internal|pkg)/**/!(*_test).go: Add defer perf.Track() to all public and critical private functions with a blank line after the call; use package-qualified names like "packagename.FunctionName"; pass atmosConfig if present, else nil.
Ensure 80% minimum coverage on new/changed lines; exclude mock files from coverage (mock_.go, **/mock_.go, **/mock/*.go); include comprehensive unit and required integration tests.

Files:

  • internal/exec/helmfile.go
@(cmd|internal|pkg)/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for every env var.

Files:

  • internal/exec/helmfile.go
internal/exec/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

All new configs must support Go templating using FuncMap() from internal/exec/template_funcs.go; test template rendering with various contexts.

Files:

  • internal/exec/helmfile.go
🧠 Learnings (4)
📚 Learning: 2024-12-07T16:16:13.038Z
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/helmfile.go
📚 Learning: 2024-12-12T15:17:45.245Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: examples/demo-atmos.d/atmos.d/tools/helmfile.yml:10-10
Timestamp: 2024-12-12T15:17:45.245Z
Learning: In `examples/demo-atmos.d/atmos.d/tools/helmfile.yml`, when suggesting changes to `kubeconfig_path`, ensure that the values use valid Go template syntax.

Applied to files:

  • internal/exec/helmfile.go
📚 Learning: 2025-09-13T18:06:07.674Z
Learnt from: samtholiya
PR: cloudposse/atmos#1466
File: toolchain/list.go:39-42
Timestamp: 2025-09-13T18:06:07.674Z
Learning: In the cloudposse/atmos repository, for UI messages in the toolchain package, use utils.PrintfMessageToTUI instead of log.Error or fmt.Fprintln(os.Stderr, ...). Import pkg/utils with alias "u" to follow the established pattern.

Applied to files:

  • internal/exec/helmfile.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#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.

Applied to files:

  • internal/exec/helmfile.go
🧬 Code graph analysis (1)
internal/exec/helmfile.go (5)
pkg/utils/component_path_utils.go (1)
  • GetComponentPath (223-259)
pkg/utils/file_utils.go (1)
  • IsDirectory (20-28)
errors/errors.go (1)
  • ErrInvalidComponent (104-104)
pkg/config/utils.go (1)
  • ReplaceContextTokens (736-751)
pkg/schema/schema.go (2)
  • Components (357-361)
  • Helmfile (343-350)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (7)
internal/exec/helmfile.go (7)

12-12: Error utilities alias added correctly.

The import alias follows the coding guideline to use static errors from errors/errors.go. This is used properly at line 126.


70-73: Configuration validation updated to use pointer.

Passing &atmosConfig is appropriate here, especially if the validation function needs to access the full configuration or if AtmosConfiguration is a large struct.


92-106: Abstract and locked component checks look good.

The logic correctly prevents provisioning of abstract components and blocks modification commands on locked components. Comments now properly end with periods.


125-129: Validation error wrapping follows coding guidelines.

Good use of errUtils.ErrInvalidComponent from errors/errors.go. This follows the coding guideline to wrap errors using static errors with proper context.

Based on coding guidelines.


131-142: Variable file write added correctly.

Writing component variables to a YAML file before execution is well-implemented with proper error handling and DryRun support. The cleanup at line 286 ensures the temporary file is removed.


154-188: EKS configuration handling looks good.

The AWS profile preparation and kubeconfig download logic is correct. Comments have been updated to end with periods, following coding guidelines.


190-291: Command execution and cleanup properly implemented.

The command preparation, environment variable setup, and execution logic are all correct. The cleanup at line 286 with a warning on error is good practice. All comments now properly end with periods.


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[bot]
coderabbitai Bot previously approved these changes Oct 11, 2025

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

🧹 Nitpick comments (1)
pkg/perf/perf.go (1)

157-160: Consider logging RecordValue errors.

Ignoring the error from Hist.RecordValue is likely safe given the generous histogram bounds, but unexpected errors could be helpful for debugging. Consider logging if the error occurs.

Apply this diff to log unexpected errors:

 	// Record self-time in histogram for percentiles.
 	if m.Hist != nil {
-		_ = m.Hist.RecordValue(selfTime.Microseconds())
+		if err := m.Hist.RecordValue(selfTime.Microseconds()); err != nil {
+			// Log unexpected histogram error for debugging (rare).
+			// Don't fail since this is non-critical.
+		}
 	}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 84996f4 and f13d968.

📒 Files selected for processing (1)
  • pkg/perf/perf.go (7 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
pkg/**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Place business logic in pkg rather than in cmd

Files:

  • pkg/perf/perf.go
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All comments must end with periods; comments should be complete sentences (golangci-lint godot).
Organize imports into three groups separated by blank lines: standard library, third-party, and github.com/cloudposse/atmos packages; sort alphabetically within each group and preserve existing aliases.
Wrap all errors using static errors from errors/errors.go; prefer errors.Join for multiple errors; use fmt.Errorf with %w for context; check with errors.Is; never use dynamic errors directly.
Distinguish structured logging from UI output: use stderr for prompts/status/errors needing user action, stdout only for data; never use logging for UI elements.
Most text UI must go to stderr; only data/results go to stdout; prefer utils.PrintfMessageToTUI for UI messages.
Ensure cross-platform compatibility: prefer SDKs over external binaries; use filepath.Join, os.PathSeparator, and runtime.GOOS for OS-specific logic; add build constraints if needed.

Files:

  • pkg/perf/perf.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • pkg/perf/perf.go
@(cmd|internal|pkg)/**/!(*_test).go

📄 CodeRabbit inference engine (CLAUDE.md)

@(cmd|internal|pkg)/**/!(*_test).go: Add defer perf.Track() to all public and critical private functions with a blank line after the call; use package-qualified names like "packagename.FunctionName"; pass atmosConfig if present, else nil.
Ensure 80% minimum coverage on new/changed lines; exclude mock files from coverage (mock_.go, **/mock_.go, **/mock/*.go); include comprehensive unit and required integration tests.

Files:

  • pkg/perf/perf.go
@(cmd|internal|pkg)/**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Bind environment variables with viper.BindEnv() and provide ATMOS_ alternatives for every env var.

Files:

  • pkg/perf/perf.go
🧠 Learnings (1)
📚 Learning: 2025-10-07T14:35:22.186Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-07T14:35:22.186Z
Learning: Applies to **/*.go : All comments must end with periods; comments should be complete sentences (golangci-lint godot).

Applied to files:

  • pkg/perf/perf.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Run pre-commit hooks
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (7)
pkg/perf/perf.go (7)

4-29: LGTM!

The new imports and constants are well-organized and properly documented for the goroutine ID parsing functionality.


31-54: Solid design for nested timing.

The StackFrame and CallStack types provide a clean foundation for goroutine-local call tracking. The childTime accumulator on each frame enables accurate self-time calculation.


62-82: LGTM!

Using sync.Map for goroutine-local call stacks and atomic.Bool for the tracking flag ensures thread-safe access with minimal overhead.


114-124: Verify lock-free parent mutation is safe.

Line 123 modifies parent.childTime without holding the CallStack mutex, after peek() has released it. This should be safe since only the current goroutine accesses its own CallStack, but please confirm this reasoning is correct and intentional.


163-203: LGTM!

The CallStack helper methods correctly use locking to protect concurrent access, and handle empty-stack cases appropriately.


205-221: LGTM!

The bounds checking and error handling prevent panics. The fallback to ID 0 should be rare since runtime.Stack reliably produces the expected format.


223-326: LGTM!

The Row struct, filtering, and sorting logic correctly implement the self-time semantics. Avg is appropriately calculated from SelfTime, and the default sort prioritizes self-time for meaningful performance analysis.

Comment thread internal/exec/helmfile.go Resolved
@aknysh
Andriy Knysh (aknysh) merged commit 9b5598a into main Oct 11, 2025
@aknysh
Andriy Knysh (aknysh) deleted the add-validate-flag branch October 11, 2025 23:23
@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Oct 11, 2025
@aknysh Andriy Knysh (aknysh) self-assigned this Oct 13, 2025
@github-actions

Copy link
Copy Markdown

These changes were released in v1.194.1-rc.0.

This branch was successfully deployed

No deployments
preview — efb80959 Deployed Oct 11, 2025 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no-release Do not create a new release (wait for additional code changes) size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants