Repository navigation
Fix and Improve Performance Heatmap - #1622
Conversation
📝 WalkthroughWalkthroughAdds a global "simple" perf tracking mode with ownership logic and goroutine-local fallback, exposes Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant perf as pkg/perf
participant metrics as MetricsStore
participant simple as simpleStack
participant gor as goroutineStack
Note over Caller,perf: Instrumentation: perf.Track("fn") { ... }
Caller->>perf: Track start("fn")
alt simple tracking enabled
perf->>simple: push frame (global stack)
Note right of simple #B6E0C2: global stack\natomic owner
perf->>simple: pop frame
perf->>metrics: recordMetrics(name, totalTime, selfTime)
else goroutine-local tracking
perf->>gor: push frame (goroutine-local)
Note right of gor #FDE2B6: per-goroutine stacks
perf->>gor: pop frame
perf->>metrics: recordMetrics(name, totalTime, selfTime)
end
perf-->>Caller: Track end
sequenceDiagram
participant CLI as cmd/root
participant perf as pkg/perf
participant ui as heatmap UI
CLI->>perf: request snapshot
perf-->>CLI: snapshot(rows, elapsed)
CLI->>ui: render with snapshot
ui->>ui: totalCPU = sum(row.SelfTime)
ui->>ui: parallelism = (elapsed > 0) ? totalCPU/elapsed : 0
ui-->>CLI: legend(Parallelism / Elapsed / CPU Time / Count / Avg / Max / P95)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 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 (3)pkg/**/*.go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
**/*.go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
**/!(*_test).go📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
Files:
🧠 Learnings (4)📓 Common learnings📚 Learning: 2025-10-13T18:13:53.992ZApplied to files:
📚 Learning: 2025-10-11T19:06:16.109ZApplied to files:
📚 Learning: 2025-10-11T23:25:09.201ZApplied to files:
⏰ 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 (10)
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 |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1622 +/- ##
==========================================
+ Coverage 64.47% 64.56% +0.08%
==========================================
Files 333 333
Lines 37331 37469 +138
==========================================
+ Hits 24068 24190 +122
- Misses 11318 11325 +7
- Partials 1945 1954 +9
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Add comprehensive tests for renderLegend() method to ensure full coverage of the parallelism calculation logic introduced in this PR. Changes: - Add assertion for "Parallelism:" text in TestModel_View - Add new TestModel_RenderLegend with table-driven tests covering: - Single-threaded execution (parallelism ~0.5x) - Parallel execution with multiple functions (parallelism ~3.0x) - Verification of all legend text elements - Validation of CPU time summation across multiple rows This improves pkg/ui/heatmap coverage from 77.77% to 87.2%. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
pkg/ui/heatmap/heatmap_test.go (1)
541-605: Strengthen parallelism assertions using the unusedexpectParallelfield.The test defines
expectParallelbut doesn't use it to validate behavior. The current assertion (line 602) only checks for "~" presence but doesn't verify that:
- Single-threaded execution (0.5 parallelism) vs parallel execution (3.0 parallelism) display correctly
- The parallelism value itself is accurate
Consider adding assertions that use
expectParallel:// Verify all expected strings are present. for _, expected := range tt.expectedStrings { assert.Contains(t, result, expected) } - // Verify parallelism is calculated (value greater than 0). - assert.Contains(t, result, "~") + // Verify parallelism value is displayed. + assert.Contains(t, result, "~") + + // Verify parallelism indicator matches expected execution type. + if tt.expectParallel { + // For parallel execution (parallelism > 1), value should be > 1. + // You may want to parse and validate the actual value here. + assert.Contains(t, result, "Parallelism: ~3") + } else { + // For single-threaded (parallelism < 1), value should be < 1. + assert.Contains(t, result, "Parallelism: ~0.5") + }Note: Adjust the exact string format based on how
renderLegend()formats the parallelism value.
📜 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/ui/heatmap/heatmap_test.go(2 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/ui/heatmap/heatmap_test.go
**/*_test.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios
**/*_test.go: Write unit tests as table-driven tests focused on behavior; prefer high coverage for pkg/ and internal/exec/; comments must end with periods.
Use t.Skipf with a reason instead of t.Skip; never skip without a reason.
Test files must mirror implementation file names (e.g., aws_ssm_store_test.go pairs with aws_ssm_store.go).
Files:
pkg/ui/heatmap/heatmap_test.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 across all Go code (godot linter enforced).
Organize imports into three groups (stdlib, 3rd-party, Atmos) separated by blank lines and sorted alphabetically within groups; preserve existing aliases.
Add defer perf.Track(<atmosConfig|nil>, ".")() at the start of all public and critical private functions, followed by a blank line.
All errors must be wrapped using static errors from errors/errors.go; prefer errors.Join for multiple errors, fmt.Errorf with %w for context, and check with errors.Is; never use dynamic errors directly.
Use utils.PrintfMarkdown() to render embedded markdown examples for CLI help output.
Co-locate unit tests with implementation files; integration tests reside under tests/.
Distinguish UI output from logging: UI prompts/status/errors to stderr; data/results to stdout; logging for system/debug info only with structured fields.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
Bind all environment variables with viper.BindEnv(); every env var must have an ATMOS_ alternative binding.
Favor cross-platform code: prefer SDKs over external binaries, use filepath/os/runtime, and handle OS-specific differences or use build tags.
For non-standard execution paths, capture telemetry using telemetry.CaptureCmd or telemetry.CaptureCmdString without collecting user data.
Search for existing methods and utilities (internal/exec, pkg/) before implementing new functionality; prefer reuse/refactoring over duplication.
Files:
pkg/ui/heatmap/heatmap_test.go
pkg/**/*_test.go
📄 CodeRabbit inference engine (CLAUDE.md)
Place unit tests for packages under pkg/ as *_test.go files.
Files:
pkg/ui/heatmap/heatmap_test.go
{pkg/ui/**,internal/tui/**}/*.go
📄 CodeRabbit inference engine (CLAUDE.md)
Use theme.Styles and theme.Colors for consistent UI formatting.
Files:
pkg/ui/heatmap/heatmap_test.go
🧬 Code graph analysis (1)
pkg/ui/heatmap/heatmap_test.go (2)
pkg/ui/heatmap/heatmap.go (1)
NewHeatModel(79-89)pkg/perf/perf.go (2)
Snapshot(293-298)Row(283-291)
⏰ 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 (macos-latest, macos)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Analyze (go)
- GitHub Check: website-deploy-preview
- GitHub Check: Lint (golangci)
- GitHub Check: Summary
🔇 Additional comments (1)
pkg/ui/heatmap/heatmap_test.go (1)
415-417: LGTM!The assertion updates correctly validate the new legend labels (Parallelism and CPU Time) in the view output.
|
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 |
The TestTerraformGenerateBackendCmd test was timing out on Windows after 30 minutes when run with other cmd package tests, though it worked fine when run in isolation. Root causes: 1. Missing environment variable cleanup - ENV vars set in the test persisted and polluted subsequent tests 2. Missing stderr cleanup on error paths - if test failed before restoring stderr, it remained broken for other tests 3. Missing defer statements - cleanup code only ran on happy path 4. Flag cleanup happened too early - flags reset before command ran instead of after Solutions: - Use t.Setenv() for automatic cleanup by Go test framework - Add defer statements to ensure stderr is ALWAYS restored - Move flag cleanup to defer to run AFTER command execution - Explicitly close pipe reader to prevent potential hangs - Add error checking for pipe creation Also fixed identical issues in TestTerraformGenerateVarfileCmd. These changes prevent test pollution and ensure proper resource cleanup even when tests fail, fixing the Windows timeout issue. Testing: - Tests pass individually: ✅ (0.16s, 0.08s) - Tests pass together: ✅ (4.3s for entire cmd package) - No ENV var pollution between tests - Proper cleanup on both success and failure paths 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
34d0982
There was a problem hiding this comment.
Actionable comments posted: 2
📜 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 (2)
cmd/terraform_generate_backend_test.go(1 hunks)cmd/terraform_generate_varfile_test.go(1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
cmd/**/*.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
cmd/**/*.go: Use Cobra's recommended command structure with a root command and subcommands
Implement each CLI command in a separate file under cmd/
Use Viper for managing configuration, environment variables, and flags in the CLI
Keep separation of concerns between CLI interface (cmd) and business logic
Use kebab-case for command-line flags
Provide comprehensive help text for all commands and flags
Include examples in Cobra command help
Use Viper for configuration management; support files, env vars, and flags with precedence flags > env > config > defaults
Follow single responsibility; separate command interface from business logic
Provide meaningful user feedback and include progress indicators for long-running operations
Provide clear error messages to users and troubleshooting hints where appropriate
cmd/**/*.go: Define one Cobra command per file under cmd/ and follow example pattern with embedded markdown examples.
New commands should rely on automatic telemetry capture; add explicit CaptureCmd/CaptureCmdString only for non-standard paths.
Files:
cmd/terraform_generate_varfile_test.gocmd/terraform_generate_backend_test.go
**/*_test.go
📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)
**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for multiple scenarios
**/*_test.go: Write unit tests as table-driven tests focused on behavior; prefer high coverage for pkg/ and internal/exec/; comments must end with periods.
Use t.Skipf with a reason instead of t.Skip; never skip without a reason.
Test files must mirror implementation file names (e.g., aws_ssm_store_test.go pairs with aws_ssm_store.go).
Files:
cmd/terraform_generate_varfile_test.gocmd/terraform_generate_backend_test.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 across all Go code (godot linter enforced).
Organize imports into three groups (stdlib, 3rd-party, Atmos) separated by blank lines and sorted alphabetically within groups; preserve existing aliases.
Add defer perf.Track(<atmosConfig|nil>, ".")() at the start of all public and critical private functions, followed by a blank line.
All errors must be wrapped using static errors from errors/errors.go; prefer errors.Join for multiple errors, fmt.Errorf with %w for context, and check with errors.Is; never use dynamic errors directly.
Use utils.PrintfMarkdown() to render embedded markdown examples for CLI help output.
Co-locate unit tests with implementation files; integration tests reside under tests/.
Distinguish UI output from logging: UI prompts/status/errors to stderr; data/results to stdout; logging for system/debug info only with structured fields.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
Bind all environment variables with viper.BindEnv(); every env var must have an ATMOS_ alternative binding.
Favor cross-platform code: prefer SDKs over external binaries, use filepath/os/runtime, and handle OS-specific differences or use build tags.
For non-standard execution paths, capture telemetry using telemetry.CaptureCmd or telemetry.CaptureCmdString without collecting user data.
Search for existing methods and utilities (internal/exec, pkg/) before implementing new functionality; prefer reuse/refactoring over duplication.
Files:
cmd/terraform_generate_varfile_test.gocmd/terraform_generate_backend_test.go
cmd/*.go
📄 CodeRabbit inference engine (CLAUDE.md)
Place each CLI command in its own file (one command per file) under cmd/.
Files:
cmd/terraform_generate_varfile_test.gocmd/terraform_generate_backend_test.go
cmd/**/*_test.go
📄 CodeRabbit inference engine (CLAUDE.md)
Place command tests under cmd/ as *_test.go files.
Files:
cmd/terraform_generate_varfile_test.gocmd/terraform_generate_backend_test.go
🧠 Learnings (1)
📚 Learning: 2025-10-10T23:51:36.588Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: internal/exec/terraform.go:394-402
Timestamp: 2025-10-10T23:51:36.588Z
Learning: In Atmos (internal/exec/terraform.go), when adding OpenTofu-specific flags like `--var-file` for `init`, do not gate them based on command name (e.g., checking if `info.Command == "tofu"` or `info.Command == "opentofu"`) because command names don't reliably indicate the actual binary being executed (symlinks, aliases). Instead, document the OpenTofu requirement in code comments and documentation, trusting users who enable the feature (e.g., `PassVars`) to ensure their terraform command points to an OpenTofu binary.
Applied to files:
cmd/terraform_generate_varfile_test.go
🧬 Code graph analysis (2)
cmd/terraform_generate_varfile_test.go (1)
cmd/root.go (1)
RootCmd(54-163)
cmd/terraform_generate_backend_test.go (1)
cmd/root.go (2)
RootCmd(54-163)Execute(437-484)
⏰ 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 (macos-latest, macos)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: website-deploy-preview
- GitHub Check: Lint (golangci)
- GitHub Check: Analyze (go)
- GitHub Check: Summary
🔇 Additional comments (3)
cmd/terraform_generate_backend_test.go (2)
20-23: Clean environment variable setup!Using
t.Setenv()ensures automatic cleanup by the test framework, preventing env var pollution across tests.
34-61: Solid I/O capture pattern with comprehensive error handling.The pipe-based stderr capture is well-implemented with proper error checks and defer ordering. Minor: the reader close error at line 61 is ignored (
_ = r.Close()), though this is acceptable at test end.cmd/terraform_generate_varfile_test.go (1)
19-22: Clean environment variable setup!Using
t.Setenv()ensures automatic cleanup, consistent withcmd/terraform_generate_backend_test.go.
Add missing persistent flag cleanup to TestTerraformGenerateVarfileCmd for consistency with TestTerraformGenerateBackendCmd. Both tests call RootCmd.SetArgs() and Execute(), so they need the same cleanup pattern to prevent flag pollution between tests. The test was already using t.Setenv() and proper stderr cleanup, but lacked the flag reset defer block that could cause order-dependent test failures when flags from this test pollute subsequent tests. Changes: - Add defer block to reset RootCmd.PersistentFlags() state - Add pflag import for flag cleanup code Testing: - Test passes individually: ✅ (0.20s) - Matches cleanup pattern in terraform_generate_backend_test.go - Prevents flag pollution in test suite 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/perf/perf.go (1)
350-355: Consider consolidating Total and SelfTime fields in Row struct.Both
TotalandSelfTimenow hold the same value (sum of self-time). Having two fields with identical values can be confusing and increases maintenance burden. Consider removing one of them or clarifying their distinct purposes if they're meant to diverge in the future.If you decide to keep both fields for backward compatibility or future extension, update the comment to explicitly state why both exist.
📜 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(6 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
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 across all Go code (godot linter enforced).
Organize imports into three groups (stdlib, 3rd-party, Atmos) separated by blank lines and sorted alphabetically within groups; preserve existing aliases.
Add defer perf.Track(<atmosConfig|nil>, ".")() at the start of all public and critical private functions, followed by a blank line.
All errors must be wrapped using static errors from errors/errors.go; prefer errors.Join for multiple errors, fmt.Errorf with %w for context, and check with errors.Is; never use dynamic errors directly.
Use utils.PrintfMarkdown() to render embedded markdown examples for CLI help output.
Co-locate unit tests with implementation files; integration tests reside under tests/.
Distinguish UI output from logging: UI prompts/status/errors to stderr; data/results to stdout; logging for system/debug info only with structured fields.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
Bind all environment variables with viper.BindEnv(); every env var must have an ATMOS_ alternative binding.
Favor cross-platform code: prefer SDKs over external binaries, use filepath/os/runtime, and handle OS-specific differences or use build tags.
For non-standard execution paths, capture telemetry using telemetry.CaptureCmd or telemetry.CaptureCmdString without collecting user data.
Search for existing methods and utilities (internal/exec, pkg/) before implementing new functionality; prefer reuse/refactoring over duplication.
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
⏰ 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). (5)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Analyze (go)
- GitHub Check: Lint (golangci)
- GitHub Check: website-deploy-preview
- GitHub Check: Summary
🔇 Additional comments (9)
pkg/perf/perf.go (9)
73-77: LGTM! Ownership tracking properly added.The simple stack globals with atomic ownership tracking are well-designed for detecting cross-goroutine access.
84-92: LGTM! Smart default for Docker performance.Enabling simple tracking mode by default when tracking is enabled is a good choice for the common single-goroutine case.
95-106: LGTM! Clean public APIs for tracking control.Both
IsTrackingEnabled()andUseSimpleTracking()are well-documented and provide necessary control over the tracking behavior.
130-138: LGTM! Clean routing between tracking modes.The conditional routing based on
useSimpleStackflag is straightforward and maintains good separation between the two tracking paths.
169-185: LGTM! CAS failure path correctly returns caller's GID.Line 180 now returns the caller's goroutine ID on CAS failure, enabling the caller to detect ownership mismatch. This addresses the past review concern.
187-210: LGTM! Clean completion logic with ownership cleanup.The negative self-time guard and ownership clearing when the stack empties are well-thought-out details that ensure correctness and reusability.
212-230: LGTM! Goroutine-local tracking is solid.The goroutine-local tracking path correctly isolates each goroutine's call stack, preventing cross-goroutine corruption.
232-255: LGTM! Proper cleanup prevents memory leaks.Deleting empty goroutine-local stacks from the map (line 250) is essential for preventing memory leaks in long-running processes.
418-418: LGTM! Aligns display metrics with self-time semantics.Setting
Row.Totaltom.SelfTimecorrectly reflects the PR's goal of using self-time for display to avoid double-counting in nested calls.
…mpty **Problem**: The ownership check only ran when simpleStack was empty. When goroutine A pushes a frame and goroutine B calls Track() before A's deferred cleanup runs, B sees a non-empty stack, skips the ownership check, and pushes onto the simple stack—corrupting child/self-time calculations. **Race Scenario**: 1. Goroutine A calls Track() → stack empty → claims ownership (GID=100) → pushes frame 2. Goroutine B calls Track() → stack NOT empty → skips ownership check → pushes frame 3. Both goroutines now use simple stack → metrics corruption **Solution**: - Always load owner GID before checking stack state - If stack is empty: claim ownership using CAS (existing logic) - If stack is non-empty AND owner != 0: verify current goroutine is the owner - If ownership mismatch: fall back to goroutine-local tracking This ensures that any goroutine attempting to use the simple stack when it doesn't own it will automatically fall back to goroutine-local tracking, preventing metric corruption. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
|
CodeRabbit (@coderabbitai) full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
pkg/perf/perf.go (3)
101-106: Clear simple owner when disabling simple trackingAvoid stale ownership if toggling modes during long runs.
func UseSimpleTracking(enabled bool) { - useSimpleStack.Store(enabled) + useSimpleStack.Store(enabled) + if !enabled { + simpleOwnerGID.Store(0) + } }
195-206: Unify pop/peek/child accumulation under one lock to reduce lock churnfinish* methods call pop(), then peek(), then isEmpty() — each locks independently. While intended to be single-goroutine, a single critical section is cleaner and cheaper.
Consider adding an internal helper:
// In CallStack: func (cs *CallStack) finishFrame(total time.Duration) (stackEmpty bool, parent *StackFrame) { cs.mu.Lock() defer cs.mu.Unlock() if n := len(cs.frames); n > 0 { cs.frames = cs.frames[:n-1] if n-1 > 0 { parent = cs.frames[n-2] parent.childTime += total } } return len(cs.frames) == 0, parent }Then use it:
- simpleStack.pop() - if parent := simpleStack.peek(); parent != nil { parent.childTime += totalTime } - if simpleStack.isEmpty() { simpleOwnerGID.Store(0) } + empty, _ := simpleStack.finishFrame(totalTime) + if empty { simpleOwnerGID.Store(0) }And similarly in finishGoroutineLocalTracking:
- stack.pop() - if parent := stack.peek(); parent != nil { parent.childTime += totalTime } - if stack.isEmpty() { callStacks.Delete(gid) } + empty, _ := stack.finishFrame(totalTime) + if empty { callStacks.Delete(gid) }Also applies to: 240-251, 292-326
286-291: GID fallback handlingIf getGoroutineID() returns 0 (unexpected format), goroutine-local stacks will key on 0 and share a stack. Add a safe fallback to a dedicated per-callstack key to avoid cross-contamination.
Option: when gid == 0, use the address of a new stack as the key via a unique counter.
// Package-scope: var anonKey atomic.Uint64 func getOrCreateCallStackKey(gid uint64) uint64 { if gid != 0 { return gid } // Generate a unique anonymous key when gid is unavailable. return anonKey.Add(1) }Then:
- gid := getGoroutineID() + gid := getOrCreateCallStackKey(getGoroutineID())Also applies to: 328-345
📜 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 ignored due to path filters (1)
website/static/img/cli/perf/atmos-describe-stacks-heatmap-bar-chart.pngis excluded by!**/*.png
📒 Files selected for processing (10)
.github/workflows/test.yml(1 hunks)cmd/root.go(3 hunks)cmd/terraform_generate_backend_test.go(2 hunks)cmd/terraform_generate_varfile_test.go(2 hunks)pkg/perf/perf.go(6 hunks)pkg/perf/perf_test.go(1 hunks)pkg/ui/heatmap/heatmap.go(5 hunks)pkg/ui/heatmap/heatmap_test.go(2 hunks)pkg/ui/heatmap/render.go(2 hunks)website/docs/troubleshoot/profiling.mdx(7 hunks)
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-10-10T23:51:36.588Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: internal/exec/terraform.go:394-402
Timestamp: 2025-10-10T23:51:36.588Z
Learning: In Atmos (internal/exec/terraform.go), when adding OpenTofu-specific flags like `--var-file` for `init`, do not gate them based on command name (e.g., checking if `info.Command == "tofu"` or `info.Command == "opentofu"`) because command names don't reliably indicate the actual binary being executed (symlinks, aliases). Instead, document the OpenTofu requirement in code comments and documentation, trusting users who enable the feature (e.g., `PassVars`) to ensure their terraform command points to an OpenTofu binary.
Applied to files:
cmd/terraform_generate_varfile_test.go
📚 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:
cmd/terraform_generate_varfile_test.go
📚 Learning: 2025-10-11T23:25:09.201Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-11T23:25:09.201Z
Learning: Applies to **/*.go : Add defer perf.Track(<atmosConfig|nil>, "<pkg>.<Func>")() at the start of all public and critical private functions, followed by a blank line.
Applied to files:
pkg/perf/perf_test.gopkg/perf/perf.go
📚 Learning: 2025-10-11T19:06:16.109Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: pkg/ui/markdown/renderer.go:247-259
Timestamp: 2025-10-11T19:06:16.109Z
Learning: Performance tracking with `defer perf.Track()` should be reserved for functions that perform actual computational work, I/O operations, or have measurable performance impact. Simple wrapper methods that immediately delegate to other functions do not require performance tracking, as it adds unnecessary overhead without providing meaningful insights.
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). (3)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Lint (golangci)
- GitHub Check: Summary
🔇 Additional comments (23)
.github/workflows/test.yml (1)
24-24: LGTM! Packer version bump looks good.The update from 1.14.1 to 1.14.2 is a standard patch version increment that should maintain compatibility.
pkg/ui/heatmap/render.go (2)
108-111: LGTM! Bar chart now displays per-call metrics.The shift from total duration to average per call with explicit call counts makes the visualization more intuitive. The new format "avg: ... | calls: ..." provides clearer information at a glance.
214-217: LGTM! Sparkline metrics align with bar chart.Consistent use of average per call and call counts across both visualization modes improves the user experience.
pkg/ui/heatmap/heatmap_test.go (2)
415-418: LGTM! Test expectations updated for new metrics.The assertions now correctly verify the presence of "Parallelism:" and "CPU Time: sum of self-time" in the view output, aligning with the updated legend format.
542-605: LGTM! Comprehensive legend rendering tests.The new test function covers both single-threaded and parallel execution scenarios, ensuring the legend displays correctly with proper parallelism calculations and metric labels.
pkg/ui/heatmap/heatmap.go (5)
223-223: LGTM! Table header renamed to CPU Time.The new "CPU Time" header clearly communicates that the column represents self-time (excluding children), aligning with the updated terminology throughout the heatmap display.
266-269: LGTM! Unbounded snapshot for accurate metrics.Capturing all tracked functions (topN=0) at TUI start ensures CPU time calculations and parallelism metrics reflect the complete execution profile, not just the top-N subset.
394-397: LGTM! Display limit applied correctly.The table shows the top 50 functions for readability while the summary metrics use the full unbounded snapshot captured at initialization.
421-441: LGTM! Parallelism calculation properly guarded.The zero elapsed guard prevents Inf/NaN values, and the legend clearly explains the CPU Time and parallelism metrics with updated terminology.
493-496: LGTM! Context propagation enables cancellation.Passing the context via
tea.WithContext(ctx)allows the TUI to respond to cancellation signals properly.cmd/terraform_generate_varfile_test.go (3)
19-21: LGTM! Windows skip prevents test hangs.The skip on Windows addresses pipe/stderr interaction issues with background goroutines, maintaining test reliability across platforms.
25-37: LGTM! Test isolation improvements.Using
t.Setenv()provides automatic cleanup, and the deferred flag reset prevents test pollution. This matches the pattern interraform_generate_backend_test.go.
39-65: LGTM! Robust stderr capture implementation.The pipe-based capture properly handles errors at each step: pipe creation, writer close, reading, and reader close. Restoring stderr immediately after command execution prevents goroutine blocking.
pkg/perf/perf_test.go (3)
1138-1263: LGTM! Comprehensive simple tracking mode tests.The test covers default enablement, nested calls, and direct recursion scenarios. The assertions validate both count and timing metrics, ensuring simple mode works correctly in various execution patterns.
1265-1356: LGTM! Goroutine-local tracking tests.The tests verify concurrent execution with simple mode disabled and nested calls in goroutine-local mode, ensuring the tracking system works correctly when explicitly using goroutine IDs.
1358-1404: LGTM! Performance comparison test.The test provides visibility into the performance difference between simple mode and goroutine-local mode, logging durations for both paths. Skipping in short mode is appropriate for performance tests.
cmd/root.go (3)
137-143: LGTM! Tracking detection improved.Using
perf.IsTrackingEnabled()instead of checking the heatmap flag directly supports commands withDisableFlagParsing. Defaulting to "bar" mode when empty handles the flag parsing edge case.
533-549: LGTM! Summary metrics computed from full snapshot.Using an unbounded snapshot (
topN=0) for CPU time and parallelism calculations ensures accurate totals, while the limited snapshot keeps the table output manageable. The parallelism guard prevents Inf/NaN.
552-557: LGTM! Output format updated with new metrics.The header now displays Elapsed, CPU Time, and Parallelism, and the column header uses "CPU Time" instead of "Total", aligning with the PR's terminology changes.
cmd/terraform_generate_backend_test.go (3)
19-21: LGTM! Windows skip prevents test hangs.Consistent with
terraform_generate_varfile_test.go, this skip addresses pipe/stderr interaction issues on Windows.
25-37: LGTM! Test isolation improvements.Using
t.Setenv()and deferred flag reset prevents test pollution, matching the pattern established interraform_generate_varfile_test.go.
39-65: LGTM! Robust stderr capture implementation.The pipe-based capture with proper error handling at each step mirrors the implementation in
terraform_generate_varfile_test.go, ensuring consistent test hygiene across the suite.website/docs/troubleshoot/profiling.mdx (1)
62-90: Docs align with new CPU Time/self-time model and TUI; examples look consistentTerminology, legend, and examples reflect Self-Time-based metrics, parallelism, and per-call averages. P95 ≤ Max in samples. LGTM.
Also applies to: 96-109, 119-130, 133-144, 153-155, 161-171, 181-206, 210-214, 221-224, 269-270
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
pkg/perf/perf.go (1)
101-106: Document the timing constraint forUseSimpleTracking.The function allows toggling simple tracking mode at any time via an atomic store, but the behavior when called mid-tracking is undefined (e.g., frames already on one type of stack won't migrate). Add a note that callers should only change this setting before
EnableTracking(true)or after tracking completes.Apply this diff to clarify usage:
// UseSimpleTracking enables or disables simple tracking mode. // Simple mode uses a single global call stack (faster, no goroutine ID lookups). // Use false for multi-goroutine scenarios to ensure accurate per-goroutine tracking. +// Note: This should be called before EnableTracking(true) or after tracking completes. +// Toggling mid-tracking may produce inconsistent results as existing frames won't migrate. func UseSimpleTracking(enabled bool) { useSimpleStack.Store(enabled) }
📜 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(6 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
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 across all Go code (godot linter enforced).
Organize imports into three groups (stdlib, 3rd-party, Atmos) separated by blank lines and sorted alphabetically within groups; preserve existing aliases.
Add defer perf.Track(<atmosConfig|nil>, ".")() at the start of all public and critical private functions, followed by a blank line.
All errors must be wrapped using static errors from errors/errors.go; prefer errors.Join for multiple errors, fmt.Errorf with %w for context, and check with errors.Is; never use dynamic errors directly.
Use utils.PrintfMarkdown() to render embedded markdown examples for CLI help output.
Co-locate unit tests with implementation files; integration tests reside under tests/.
Distinguish UI output from logging: UI prompts/status/errors to stderr; data/results to stdout; logging for system/debug info only with structured fields.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
Bind all environment variables with viper.BindEnv(); every env var must have an ATMOS_ alternative binding.
Favor cross-platform code: prefer SDKs over external binaries, use filepath/os/runtime, and handle OS-specific differences or use build tags.
For non-standard execution paths, capture telemetry using telemetry.CaptureCmd or telemetry.CaptureCmdString without collecting user data.
Search for existing methods and utilities (internal/exec, pkg/) before implementing new functionality; prefer reuse/refactoring over duplication.
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
⏰ 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). (5)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Lint (golangci)
- GitHub Check: Analyze (go)
- GitHub Check: website-deploy-preview
- GitHub Check: Summary
🔇 Additional comments (7)
pkg/perf/perf.go (7)
33-43: LGTM! Clear documentation of Total vs SelfTime semantics.The updated comments effectively distinguish between internal tracking (Total as wall-clock time) and display metrics (SelfTime as actual work). This clarity helps maintainers understand why SelfTime is used for display to avoid double-counting nested calls.
73-93: LGTM! Sensible defaults with clear ownership tracking.The addition of
simpleOwnerGIDand auto-enabling simple mode inEnableTrackingaligns with the PR's performance goals. The comments clearly explain the rationale (faster Docker performance by avoiding per-callruntime.Stack()lookups).
140-173: LGTM! Concurrency protection is sound; nested-call overhead is an acceptable trade-off.The ownership checks correctly prevent the race condition where a second goroutine could corrupt the simple stack. The logic is:
- Empty stack: claim via CAS and fall back on mismatch.
- Non-empty stack: verify current goroutine is the owner (line 156), fall back otherwise.
The
getGoroutineID()call at line 156 adds overhead to nested calls (acknowledged in past reviews), but this is necessary for correctness in multi-goroutine edge cases.Based on past review resolutions.
175-191: LGTM! CAS failure path correctly returns caller's GID.Line 186 correctly returns the current goroutine's ID (not the owner) after CAS failure, enabling the caller to detect cross-goroutine access. This aligns with the past review guidance and ensures proper fallback to goroutine-local tracking.
Based on past review resolutions.
193-216: LGTM! Frame lifecycle and ownership cleanup are correct.The function properly:
- Clamps negative selfTime (line 198).
- Pops the frame before checking for parent (thread-safe via internal locks).
- Clears ownership only when the stack becomes empty (line 210), allowing future single-goroutine fast path.
- Records metrics with both total and self-time.
218-261: LGTM! Goroutine-local tracking mirrors simple-stack logic with proper cleanup.The parallel structure between
finishSimpleStackTrackingandfinishGoroutineLocalTrackingmakes the code easy to understand. Cleanup at line 256 correctly prevents memory leaks by removing empty per-goroutine stacks.
356-357: LGTM! Display metrics correctly use SelfTime to avoid double-counting.The
Row.Totalassignment at line 424 usesm.SelfTimewith a clear comment explaining it represents the sum of self-times (excludes children). This prevents nested/recursive calls from inflating totals and aligns with the PR's shift to CPU time metrics.Also applies to: 424-424
…depth <= 1) **Problem**: The previous fix checked goroutine ownership on EVERY call when the stack was non-empty, causing expensive runtime.Stack() calls on every nested function. This made Docker container runs very slow. **Root Cause**: In single-goroutine execution with deep call stacks (e.g., 1000+ nested calls), we were calling getGoroutineID() thousands of times, each requiring an expensive runtime.Stack() operation. **Solution - Depth-Based Checking**: - **Depth == 0** (empty): Claim ownership (1 getGoroutineID call) - **Depth == 1** (shallow): Verify ownership once to catch early cross-goroutine access - **Depth > 1** (deep): Trust ownership, skip expensive check **Performance Impact**: - Single-goroutine with deep nesting: Only 2 checks total (depth 0 and 1) - Previously: O(N) checks where N = number of nested calls - Now: O(1) checks after depth > 1 **Safety**: - Cross-goroutine access is still detected early (at depth 0 or 1) - When detected, simple mode is disabled globally - All future calls use goroutine-local tracking automatically This restores fast Docker performance while maintaining correctness for multi-goroutine scenarios. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (14)
.github/workflows/test.yml (1)
145-149: Pin setup-packer action to a tagged release (avoid Vlad Vannov (@main)).Using Vlad Vannov (@main) is brittle and a security smell. Prefer a stable tag (e.g., v3) or a pinned SHA.
Apply:
- - name: Install Packer - uses: hashicorp/setup-packer@main + - name: Install Packer + uses: hashicorp/setup-packer@v3 with: version: ${{ env.PACKER_VERSION }}Repeat for all occurrences in this workflow.
Also applies to: 303-307, 449-453
cmd/terraform_generate_backend_test.go (1)
39-46: Restore os.Stderr via t.Cleanup to harden against early failures.Guarantees restoration on panics/subtest failures.
Apply:
- // Capture stderr. - oldStderr := os.Stderr + // Capture stderr. + oldStderr := os.Stderr r, w, err := os.Pipe() assert.NoError(t, err, "Creating pipe should not error") - os.Stderr = w + os.Stderr = w + t.Cleanup(func() { + // Best-effort cleanup + os.Stderr = oldStderr + _ = w.Close() + _ = r.Close() + })Also applies to: 51-66
pkg/perf/perf_test.go (3)
1141-1152: Stabilize default-mode assertion by saving/restoring simple-mode.Global state can leak across tests; restore it via t.Cleanup, and set it explicitly before asserting.
Apply:
t.Run("Simple mode enabled by default", func(t *testing.T) { // Reset and enable tracking. reg = ®istry{ data: make(map[string]*Metric), start: time.Now(), } EnableTracking(true) - - // Simple mode should be enabled by default. - if !useSimpleStack.Load() { - t.Error("expected simple mode to be enabled by default") - } + // Preserve and assert default mode deterministically. + prev := useSimpleStack.Load() + t.Cleanup(func() { UseSimpleTracking(prev) }) + UseSimpleTracking(true) + if !useSimpleStack.Load() { + t.Error("expected simple mode to be enabled by default") + } })
1267-1275: Restore tracking mode in concurrent test.Wrap UseSimpleTracking(false) with cleanup to avoid leaking state.
Apply:
EnableTracking(true) - UseSimpleTracking(false) // Explicitly disable simple mode for concurrent test. + prev := useSimpleStack.Load() + t.Cleanup(func() { UseSimpleTracking(prev) }) + UseSimpleTracking(false) // Explicitly disable simple mode for concurrent test.
1359-1404: Perf comparison: keep as log-only, but guard global mode as well.Same cleanup pattern avoids cross-test flakiness.
Example:
prev := useSimpleStack.Load() t.Cleanup(func(){ UseSimpleTracking(prev) }) UseSimpleTracking(true) // or false in the second subtestpkg/ui/heatmap/heatmap.go (2)
388-414: Minor: avoid redundant update gating or remove lastUpdate.lastUpdate is initialized in newModel, so the IsZero check never fires. Either remove the check and rely on Init’s one-time load, or init lastUpdate to zero to let tick update once.
Option A (remove gating in handleTick):
- if m.lastUpdate.IsZero() { - m.updatePerformanceData() - m.lastUpdate = time.Time(msg) - }Option B (init lastUpdate zero in newModel):
- lastUpdate: time.Now(), + lastUpdate: time.Time{},
492-497: Optional: WithAltScreen + EnterAltScreen duplication.Either WithAltScreen or tea.EnterAltScreen is sufficient.
You can drop tea.EnterAltScreen from Init or WithAltScreen here to simplify.
pkg/perf/perf.go (5)
86-93: Align Elapsed with the tracking window (reset start on enable).Elapsed currently starts at package init. Reset reg.start when enabling to avoid underreporting parallelism and misleading summaries.
func EnableTracking(enabled bool) { trackingEnabled.Store(enabled) if enabled { + // Reset elapsed baseline to align with when tracking actually starts. + reg.mu.Lock() + reg.start = time.Now() + reg.mu.Unlock() // Enable simple stack mode by default for better Docker performance. // This avoids expensive runtime.Stack() calls on every tracked function. useSimpleStack.Store(true) } }
101-106: Prevent stale simple-stack ownership across toggles.If simple tracking was previously in use, simpleOwnerGID may remain set and force immediate fallback. Clear it when enabling simple mode.
func UseSimpleTracking(enabled bool) { useSimpleStack.Store(enabled) + if enabled { + // Ensure fresh ownership claim on next use. + simpleOwnerGID.Store(0) + } }
145-160: Nested-call GID checks add overhead; consider sampling.The non-empty stack path calls getGoroutineID per push. Correctness is good; to trim overhead, sample (e.g., every Nth push) or gate by time since last check. Keep safety fallback on mismatch.
263-291: Avoid histogram out-of-range errors and log noise for 0µs.Recording 0 microseconds causes RecordValue errors and trace logs. Skip zeros.
// Record self-time in histogram for percentiles. if m.Hist != nil { - if err := m.Hist.RecordValue(selfTime.Microseconds()); err != nil { + if selfTime > 0 { + if err := m.Hist.RecordValue(selfTime.Microseconds()); err != nil { log.Trace("Failed to record histogram value", "error", err, "metric", name) + } } }
337-350: Harden goroutine ID extraction.Increase buffer size to reduce chance of truncated headers returning gid==0 (which would collapse stacks).
func getGoroutineID() uint64 { - var buf [64]byte + var buf [128]byte n := runtime.Stack(buf[:], false) // Stack trace format: "goroutine 123 [running]:\n...".cmd/root.go (1)
533-557: Use full snapshot for counts to match CPU Time/Elapsed.You compute CPU Time and Elapsed from fullSnap but print Functions/Calls from limited snap. Use fullSnap for those too.
- utils.PrintfMessageToTUI("Functions: %d | Total Calls: %d\n\n", snap.TotalFuncs, snap.TotalCalls) + utils.PrintfMessageToTUI("Functions: %d | Total Calls: %d\n\n", fullSnap.TotalFuncs, fullSnap.TotalCalls)cmd/terraform_generate_varfile_test.go (1)
39-66: Minor: ensure stderr restore on early failures.Use t.Cleanup to restore os.Stderr even if the test aborts before the manual restore.
- oldStderr := os.Stderr + oldStderr := os.Stderr + t.Cleanup(func() { os.Stderr = oldStderr }) r, w, err := os.Pipe() ... os.Stderr = w
📜 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 ignored due to path filters (1)
website/static/img/cli/perf/atmos-describe-stacks-heatmap-bar-chart.pngis excluded by!**/*.png
📒 Files selected for processing (10)
.github/workflows/test.yml(1 hunks)cmd/root.go(3 hunks)cmd/terraform_generate_backend_test.go(2 hunks)cmd/terraform_generate_varfile_test.go(2 hunks)pkg/perf/perf.go(6 hunks)pkg/perf/perf_test.go(1 hunks)pkg/ui/heatmap/heatmap.go(5 hunks)pkg/ui/heatmap/heatmap_test.go(2 hunks)pkg/ui/heatmap/render.go(2 hunks)website/docs/troubleshoot/profiling.mdx(7 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-10-11T23:25:09.201Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-11T23:25:09.201Z
Learning: Applies to **/*.go : Add defer perf.Track(<atmosConfig|nil>, "<pkg>.<Func>")() at the start of all public and critical private functions, followed by a blank line.
Applied to files:
pkg/perf/perf_test.go
📚 Learning: 2025-10-10T23:51:36.588Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: internal/exec/terraform.go:394-402
Timestamp: 2025-10-10T23:51:36.588Z
Learning: In Atmos (internal/exec/terraform.go), when adding OpenTofu-specific flags like `--var-file` for `init`, do not gate them based on command name (e.g., checking if `info.Command == "tofu"` or `info.Command == "opentofu"`) because command names don't reliably indicate the actual binary being executed (symlinks, aliases). Instead, document the OpenTofu requirement in code comments and documentation, trusting users who enable the feature (e.g., `PassVars`) to ensure their terraform command points to an OpenTofu binary.
Applied to files:
cmd/terraform_generate_varfile_test.go
📚 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:
cmd/terraform_generate_varfile_test.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). (5)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Lint (golangci)
- GitHub Check: Analyze (go)
- GitHub Check: website-deploy-preview
- GitHub Check: Summary
🔇 Additional comments (15)
.github/workflows/test.yml (1)
24-24: LGTM: bump Packer to 1.14.2.Version var aligns with setup steps below.
cmd/terraform_generate_backend_test.go (2)
19-21: Good: skip on Windows to avoid pipe hang.Prevents intermittent hangs in CI.
23-29: Nice: t.Setenv and deferred flag reset.Reduces test pollution and improves reliability.
Also applies to: 32-37
pkg/ui/heatmap/heatmap.go (2)
266-270: Good: capture unbounded, filtered snapshot at TUI start.Enables accurate totals/elapsed without top-N bias.
421-433: Legend computation is correct and guarded.Totals from full snapshot; zero-elapsed guard prevents Inf/NaN.
Also applies to: 435-441
website/docs/troubleshoot/profiling.mdx (1)
62-86: Docs align well with CPU Time/self-time semantics and new legend.Examples and terminology are clear and consistent.
Also applies to: 96-110, 157-171, 181-199
pkg/perf/perf_test.go (1)
1-1404: No parallel tests detected
All tests in pkg/perf avoid t.Parallel, so the shared registry and simple-stack global state won’t race.pkg/perf/perf.go (1)
352-361: Public Row fields duplication (Total vs SelfTime).Using Total as sum of SelfTime is clear and consistent. LGTM.
Also applies to: 424-435
cmd/root.go (1)
136-143: Good: robust heatmap gating and default mode.Using IsTrackingEnabled() and defaulting mode to "bar" covers DisableFlagParsing and empty flag cases cleanly.
cmd/terraform_generate_varfile_test.go (2)
19-21: Good: Windows skip prevents flaky hangs.Pragmatic guard for pipe/stderr behavior on Windows.
30-37: Nice: flag state cleanup.Prevents cross-test pollution. LGTM.
pkg/ui/heatmap/heatmap_test.go (2)
415-419: Updated legend expectations look correct.Checks for Parallelism and CPU Time semantics align with new display.
542-605: Solid coverage for legend rendering.Good cases and string checks; validates semantics without overfitting.
pkg/ui/heatmap/render.go (2)
108-112: Good UX: show avg per call + count.Keeps bar length proportional to CPU time; label communicates per-call cost.
214-218: Consistent sparkline stats.Avg + calls mirrors the bar view. LGTM.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 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 (3)
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 across all Go code (godot linter enforced).
Organize imports into three groups (stdlib, 3rd-party, Atmos) separated by blank lines and sorted alphabetically within groups; preserve existing aliases.
Add defer perf.Track(<atmosConfig|nil>, ".")() at the start of all public and critical private functions, followed by a blank line.
All errors must be wrapped using static errors from errors/errors.go; prefer errors.Join for multiple errors, fmt.Errorf with %w for context, and check with errors.Is; never use dynamic errors directly.
Use utils.PrintfMarkdown() to render embedded markdown examples for CLI help output.
Co-locate unit tests with implementation files; integration tests reside under tests/.
Distinguish UI output from logging: UI prompts/status/errors to stderr; data/results to stdout; logging for system/debug info only with structured fields.
Most text UI must go to stderr; only data/results to stdout. Prefer utils.PrintfMessageToTUI for UI messages.
Bind all environment variables with viper.BindEnv(); every env var must have an ATMOS_ alternative binding.
Favor cross-platform code: prefer SDKs over external binaries, use filepath/os/runtime, and handle OS-specific differences or use build tags.
For non-standard execution paths, capture telemetry using telemetry.CaptureCmd or telemetry.CaptureCmdString without collecting user data.
Search for existing methods and utilities (internal/exec, pkg/) before implementing new functionality; prefer reuse/refactoring over duplication.
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
🧠 Learnings (2)
📚 Learning: 2025-10-11T19:06:16.109Z
Learnt from: osterman
PR: cloudposse/atmos#1599
File: pkg/ui/markdown/renderer.go:247-259
Timestamp: 2025-10-11T19:06:16.109Z
Learning: Performance tracking with `defer perf.Track()` should be reserved for functions that perform actual computational work, I/O operations, or have measurable performance impact. Simple wrapper methods that immediately delegate to other functions do not require performance tracking, as it adds unnecessary overhead without providing meaningful insights.
Applied to files:
pkg/perf/perf.go
📚 Learning: 2025-10-11T23:25:09.201Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-11T23:25:09.201Z
Learning: Applies to **/*.go : Add defer perf.Track(<atmosConfig|nil>, "<pkg>.<Func>")() at the start of all public and critical private functions, followed by a blank line.
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). (3)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Lint (golangci)
- GitHub Check: Summary
Per CodeRabbit's recommendation, add detailed comments documenting the performance vs correctness trade-off for the depth-based ownership checking optimization. **Known Limitation**: When stack depth > 1, ownership checking is skipped for performance. If a goroutine spawns another goroutine while at depth > 1, metric corruption is theoretically possible. **Why This Trade-off is Acceptable**: 1. Favors performance for 99% of Atmos commands (single-goroutine) 2. Edge case is extremely rare in practice (multi-goroutine spawn at depth > 1) 3. Impact limited to incorrect metrics for one run (no crashes or data loss) 4. Early detection at depth 0-1 catches most multi-goroutine scenarios 5. Simple mode disabled globally when detected, preventing future issues This documentation helps future maintainers understand the design decision and why fast Docker performance was prioritized over handling this rare edge case. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
|
These changes were released in v1.194.1. |
what
--heatmapflag in Docker environmentswebsite/docs/troubleshoot/profiling.mdxwith explanations of all new metrics and display formatswhy
Docker performance context
This PR improved the heatmap performance on Docker, fixed critical performance issues with the
--heatmapflag in Docker environments.The Docker Problem:
--heatmaptook ~60 seconds to start in Docker containers (vs instantly on macOS)runtime.Stack()was called on every tracked function to get goroutine IDsThe Solution:
runtime.Stack()calls for single-goroutine execution (most Atmos commands)TUI improvements
Problem 1: Confusing Column Name
The "Total" column name was ambiguous - users couldn't tell if it meant wall-clock time or CPU time. This caused confusion when trying to interpret performance data.
Problem 2: Missing Parallelism Context
Users had no way to understand the relationship between CPU time and elapsed time. When CPU time exceeded elapsed time (e.g., 5 minutes of CPU time in 22 seconds), it looked wrong but was actually correct for parallel execution.
Problem 3: TUI Display Showed Confusing Values
The bar chart displayed large total times (e.g., "2m47s") for functions called hundreds of thousands of times, making it appear slow when the average time per call was actually fast (e.g., 0.37ms). This was mathematically correct but user-unfriendly.
Problem 4: Cramped Legend
The single-line legend was too wide and difficult to read in the TUI.
Solutions
Solution 1: Clear Terminology
Renamed "Total" to "CPU Time" everywhere with consistent explanations that it represents "sum of self-time (excludes children)" to avoid confusion with wall-clock time.
Solution 2: Parallelism Metric
Added parallelism calculation and display in both console output and TUI legend:
Parallelism: ~0.9x(single-threaded) or~58.2x(highly parallel)Solution 3: User-Friendly TUI Visualizations
Changed bar chart and sparkline displays from showing total CPU time to showing average time per call with call counts:
2m47.818679s (×447586)- confusingavg: 0.37ms | calls: 447586- intuitiveSolution 4: Multi-Line Legend
Split the TUI legend into three informative lines:
example
testing
All existing tests pass:
pkg/perfpackagepkg/ui/heatmappackagecmdpackageManual verification:
--heatmap)documentation
Updated
website/docs/troubleshoot/profiling.mdxwith:avg: Xms | calls: Nformatbenefits
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Documentation
Chores