Repository navigation
Improve performance heatmap - #1611
Conversation
|
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. |
|
Important Cloud Posse Engineering Team Review RequiredThis 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 |
--validate CLI flag|
CodeRabbit (@coderabbitai) full review |
✅ Actions performedFull review triggered. |
…to handle CI overhead
📝 WalkthroughWalkthroughAdds 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
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
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (5)**/*.go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
**/!(*_test).go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
@(cmd|internal|pkg)/**/!(*_test).go📄 CodeRabbit inference engine (CLAUDE.md)
Files:
@(cmd|internal|pkg)/**/*.go📄 CodeRabbit inference engine (CLAUDE.md)
Files:
internal/exec/**/*.go📄 CodeRabbit inference engine (CLAUDE.md)
Files:
🧠 Learnings (4)📚 Learning: 2024-12-07T16:16:13.038ZApplied to files:
📚 Learning: 2024-12-12T15:17:45.245ZApplied to files:
📚 Learning: 2025-09-13T18:06:07.674ZApplied to files:
📚 Learning: 2024-10-23T21:36:40.262ZApplied to files:
🧬 Code graph analysis (1)internal/exec/helmfile.go (5)
⏰ 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)
🔇 Additional comments (7)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
pkg/perf/perf.go (1)
157-160: Consider logging RecordValue errors.Ignoring the error from
Hist.RecordValueis 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.
📒 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: Adddefer 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.Mapfor goroutine-local call stacks andatomic.Boolfor the tracking flag ensures thread-safe access with minimal overhead.
114-124: Verify lock-free parent mutation is safe.Line 123 modifies
parent.childTimewithout holding the CallStack mutex, afterpeek()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.Stackreliably 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.
efb8095
|
These changes were released in v1.194.1-rc.0. |
what
--heatmapflag not working withterraform,helmfile, andpackercommandswhy
Heatmap Flag Fix
The
--heatmapflag was not working forterraform,helmfile, andpackercommands because:DisableFlagParsing = trueto pass native flags through to underlying tools--heatmapflagPersistentPreRunhook couldn't detect the flag viacmd.Flags().GetBool("heatmap")Performance Tracking Enhancement
--heatmapshowed inconsistent timing metrics for long-running commands: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:
Key Features:
selfTime = totalTime - childTimeBenefits:
Example Output:
Metric Consistency Fix
Changed Max to track self-time instead of total-time:
Avg,Max,P95) consistently track self-timeTUI Legend
Added informative legend to heatmap TUI:
Recursive Function Updates
Benefits:
Documentation
Updated profiling documentation:
Heatmap Flag Improvements
--heatmapfromos.Argsfor commands withDisableFlagParsing = trueterraform,helmfile, andpackercommandsEnhanced Performance Tracking Coverage
perf.Track()toUnmarshalYAMLFromFileto track YAML parsing performancetesting
Performance Tracking Tests
New self-time tracking tests:
TestSelfTimeVsTotalTime- Verifies self-time excludes child timeTestNestedFunctionSelfTime- Tests multi-level nesting (grandparent → parent → child)TestDirectRecursionWithSelfTime- Tests direct recursion with accurate counts AND timingUpdated existing tests:
Recursive function tests:
TestRecursiveFunctionTracking- Wrapper pattern verificationTestRecursiveFunctionWrongPattern- Demonstrates inflation with wrong patternTestMultipleRecursiveFunctionsIndependent- Independent function trackingTestYAMLConfigProcessingRecursion- YAML import hierarchy (50 levels deep)TestYAMLConfigProcessingMultipleImports- Fan-out import patternTestProcessBaseComponentConfigRecursion- Component inheritance (15 levels deep)Heatmap UI Tests
Updated heatmap tests:
Heatmap Flag Tests
✅
TestTerraformHeatmapFlagpasses successfully✅ Manual testing confirms
--heatmapworks with:atmos terraform plan <component> -s <stack> --heatmapatmos helmfile <subcommand> <component> -s <stack> --heatmapatmos packer <subcommand> <component> -s <stack> --heatmapBuild 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
Performance Insights
Better User Experience
Summary by CodeRabbit
New Features
Improvements
Documentation
Chores