Skip to content

Fix and Improve Performance Heatmap - #1622

Merged
Andriy Knysh (aknysh) merged 20 commits into
mainfrom
update-heatmap-3
Oct 13, 2025
Merged

Andriy Knysh (aknysh) merged 20 commits into
mainfrom
update-heatmap-3

Conversation

@aknysh

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

Copy link
Copy Markdown
Member

what

  • Improved the heatmap performance on Docker, fixed critical performance issues with the --heatmap flag in Docker environments
  • Renamed "Total" column to "CPU Time" throughout the performance heatmap display to clarify that it represents sum of self-times, not wall-clock time
  • Added parallelism metric to both console and TUI displays showing CPU Time ÷ Elapsed ratio
  • Improved TUI visualizations (bar chart and sparkline modes) to display average time per call instead of total CPU time for better user comprehension
  • Enhanced TUI legend with live performance metrics (Parallelism, Elapsed time, CPU Time) displayed at the top
  • Split TUI legend into three lines for improved readability
  • Updated comprehensive documentation in website/docs/troubleshoot/profiling.mdx with explanations of all new metrics and display formats

why

Docker performance context

This PR improved the heatmap performance on Docker, fixed critical performance issues with the --heatmap flag in Docker environments.

The Docker Problem:

  • Commands with --heatmap took ~60 seconds to start in Docker containers (vs instantly on macOS)
  • Root cause: runtime.Stack() was called on every tracked function to get goroutine IDs
  • In Docker, this syscall is significantly slower than on native macOS
  • With thousands of tracked function calls during stack processing, overhead accumulated to ~1 minute

The Solution:

  • Introduced "simple tracking mode" using a single global call stack instead of per-goroutine tracking
  • Avoids expensive runtime.Stack() calls for single-goroutine execution (most Atmos commands)
  • Result: ~19x faster (119µs vs 3ms for 1000 calls)

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:

  • Format: Parallelism: ~0.9x (single-threaded) or ~58.2x (highly parallel)
  • Helps users immediately understand execution characteristics
  • Values less than 1.0 indicate single-threaded execution
  • Values greater than 1.0 indicate parallel execution across multiple cores

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:

  • Old format: 2m47.818679s (×447586) - confusing
  • New format: avg: 0.37ms | calls: 447586 - intuitive
  • Bar length still represents total CPU time (overall impact)
  • Average time shows typical function performance

Solution 4: Multi-Line Legend
Split the TUI legend into three informative lines:

  • Line 1: Live metrics (Parallelism, Elapsed, CPU Time)
  • Line 2: Explanation of Count and CPU Time columns
  • Line 3: Explanation of statistical timing columns (Avg, Max, P95)

example

image

testing

All existing tests pass:

  • ✅ 26 tests in pkg/perf package
  • ✅ 36 tests in pkg/ui/heatmap package
  • ✅ 87 tests in cmd package
  • ✅ Total: 149 tests across all modified packages

Manual verification:

  • Compiled binary successfully on macOS
  • Tested in Docker
  • Verified console output shows new format with parallelism
  • Confirmed interactive TUI displays updated legend
  • Website documentation builds without errors
  • Docker performance remains fast (1-2 second startup with --heatmap)

documentation

Updated website/docs/troubleshoot/profiling.mdx with:

  • New "Interactive TUI Legend" section explaining the 3-line legend format
  • Updated Performance Summary section with Parallelism explanation
  • Updated all column descriptions (CPU Time instead of Total)
  • Enhanced Bar Chart and Sparkline mode descriptions with new display format
  • Added concrete examples showing the new avg: Xms | calls: N format

benefits

  1. Clearer Metrics: "CPU Time" is unambiguous compared to "Total"
  2. Execution Context: Parallelism metric immediately shows if execution was single-threaded or parallel
  3. Intuitive Display: Average times per call are much easier to understand than large totals
  4. Better UX: Multi-line legend is more readable and informative
  5. Complete Documentation: Users have clear explanations of all metrics
  6. Backward Compatible: All existing tests pass without changes
  7. Docker Ready: Works fast in Docker environments (builds on PR Improve performance heatmap #1611 improvements)

Summary by CodeRabbit

  • New Features

    • Heatmap and summaries now show CPU Time and Parallelism; charts and sparklines show average time per call with counts; interactive UI supports cancellation and a new toggle to control tracking mode.
  • Bug Fixes

    • More accurate CPU Time and parallelism calculations; per-function CPU Time shown; durations truncated to microseconds; headers and columns reorganized for clarity.
  • Tests

    • Added tests for tracking modes, performance comparisons, and legend/render output; Windows skips and more robust environment/IO handling.
  • Documentation

    • Profiling docs updated to explain CPU Time vs Self‑Time with revised examples.
  • Chores

    • CI tool version bumped and test cleanup/synchronization improvements.

@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Oct 13, 2025
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner October 13, 2025 03:17
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Oct 13, 2025
@github-actions github-actions Bot added the size/l Large size PR label Oct 13, 2025
@aknysh Andriy Knysh (aknysh) self-assigned this Oct 13, 2025
@coderabbitai

coderabbitai Bot commented Oct 13, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a global "simple" perf tracking mode with ownership logic and goroutine-local fallback, exposes IsTrackingEnabled()/UseSimpleTracking(), switches heatmap enablement to perf.IsTrackingEnabled(), changes heatmap metrics from wall‑clock Total to CPU self‑time, computes parallelism, updates UI/rendering/tests/docs, and includes test/CI hygiene fixes.

Changes

Cohort / File(s) Summary
CLI root
cmd/root.go
Use perf.IsTrackingEnabled() for heatmap enablement; default empty heatmap-mode to "bar"; compute/display Elapsed / CPU Time / Parallelism; adjust performance table headers/formatting and truncate durations.
Perf core
pkg/perf/perf.go
Add global simple-tracking mode with atomic ownership and per-goroutine fallback; add IsTrackingEnabled() and UseSimpleTracking(bool); EnableTracking enables simple tracking by default; Track branches to simple or goroutine-local paths; compute/record total and self CPU times; use SelfTime for display to avoid double-counting.
Perf tests
pkg/perf/perf_test.go
Add TestSimpleTrackingMode, TestGoroutineLocalTracking, and TestSimpleVsGoroutineLocalPerformance to validate tracking modes and compare performance.
Heatmap UI & rendering
pkg/ui/heatmap/heatmap.go, pkg/ui/heatmap/render.go, pkg/ui/heatmap/heatmap_test.go
Rename "Total" to "CPU Time"; capture unbounded initial snapshot and display top‑N; compute total CPU time (sum of self-time) and parallelism; show Avg and Calls in bars/sparklines; pass context into Bubble Tea program; update legend and tests.
Docs
website/docs/troubleshoot/profiling.mdx
Replace "Total" with "CPU Time" across prose/examples; update outputs and explanations to show Elapsed / CPU Time / Parallelism and clarify Self-Time vs wall-clock.
CLI tests
cmd/terraform_generate_backend_test.go, cmd/terraform_generate_varfile_test.go
Add Windows skip guard; use t.Setenv; improve stderr capture with os.Pipe error handling, proper close/read sequencing, and deferred cleanup; ensure flag reset in defer.
CI workflow
.github/workflows/test.yml
Bump PACKER_VERSION from 1.14.1 to 1.14.2 in CI env.

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
Loading
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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

minor

Suggested reviewers

  • osterman

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title Check ❓ Inconclusive The title “Fix and Improve Performance Heatmap” is related to the changes but is overly generic and doesn’t convey the specific enhancements such as CPU Time metrics, parallelism display, and the new simple tracking mode added to the heatmap feature. Consider revising the title to more specifically highlight the primary changes, for example “Add CPU Time and Parallelism Metrics with Simple Tracking to Performance Heatmap” so that the main enhancements are immediately clear.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% 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 update-heatmap-3

📜 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 d17ea69 and 3f91dd3.

📒 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 (4)
📓 Common learnings
Learnt from: aknysh
PR: cloudposse/atmos#1622
File: pkg/perf/perf.go:140-184
Timestamp: 2025-10-13T18:13:53.992Z
Learning: In pkg/perf/perf.go, the `trackWithSimpleStack` function intentionally skips ownership checks at call stack depth > 1 to avoid expensive `getGoroutineID()` calls on every nested function. This is a performance optimization for the common single-goroutine execution case (most Atmos commands), accepting the rare edge case of potential metric corruption if multi-goroutine execution occurs at depth > 1. The ~19× performance improvement justifies this trade-off.
📚 Learning: 2025-10-13T18:13:53.992Z
Learnt from: aknysh
PR: cloudposse/atmos#1622
File: pkg/perf/perf.go:140-184
Timestamp: 2025-10-13T18:13:53.992Z
Learning: In pkg/perf/perf.go, the `trackWithSimpleStack` function intentionally skips ownership checks at call stack depth > 1 to avoid expensive `getGoroutineID()` calls on every nested function. This is a performance optimization for the common single-goroutine execution case (most Atmos commands), accepting the rare edge case of potential metric corruption if multi-goroutine execution occurs at depth > 1. The ~19× performance improvement justifies this trade-off.

Applied to files:

  • pkg/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
📚 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). (6)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (10)
pkg/perf/perf.go (10)

32-43: LGTM: Clear distinction between Total and SelfTime.

The updated comments properly document that Total is for internal tracking (wall-clock, includes children) while SelfTime is used for display (excludes children). This aligns with the PR objective of switching to CPU self-time metrics.


86-93: LGTM: Default simple mode enables the performance optimization.

Enabling simple tracking mode by default when tracking is enabled aligns with the PR objective of improving Docker performance by avoiding expensive goroutine ID lookups.


95-106: LGTM: Clean public API additions.

The new IsTrackingEnabled() and UseSimpleTracking() functions provide necessary public access to the tracking state. These are straightforward getters/setters that don't require performance tracking overhead.


130-138: LGTM: Clean mode selection.

The conditional routing between simple and goroutine-local tracking modes is straightforward and efficient.


140-187: LGTM: Ownership checks implement the accepted performance optimization.

The depth-based ownership verification (checking at depths 0 and 1, trusting at depth > 1) implements the agreed-upon trade-off that achieves ~19× performance improvement for the common single-goroutine case. The documented limitation at lines 171-174 properly explains the design decision for future maintainers.

Based on learnings


189-205: LGTM: Correct atomic ownership claim.

The CompareAndSwap logic properly handles the ownership claim, and the CAS failure path correctly returns the caller's goroutine ID (line 200) for proper cross-goroutine detection.


207-230: LGTM: Correct completion logic with ownership cleanup.

The finish function properly calculates times, propagates child durations to parents, and clears ownership when the stack empties (lines 223-226), allowing the fast path to be re-established later.


232-275: LGTM: Goroutine-local tracking with proper cleanup.

The goroutine-local implementation correctly handles per-goroutine stacks and prevents memory leaks by deleting empty stacks (lines 268-271).


348-353: LGTM: Thread-safe depth accessor.

The depth() method properly locks while reading the stack depth.


439-458: LGTM: Display metrics use self-time to avoid double-counting.

The buildRows() function correctly assigns m.SelfTime to Row.Total (line 445) to represent the sum of self-times for display purposes, avoiding double-counting in nested calls. This aligns with the PR objective of switching from wall-clock Total to CPU self-time.


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 13, 2025
@codecov

codecov Bot commented Oct 13, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.42424% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.56%. Comparing base (d72c802) to head (3f91dd3).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/perf/perf.go 87.00% 10 Missing and 3 partials ⚠️
pkg/ui/heatmap/heatmap.go 70.58% 8 Missing and 2 partials ⚠️
cmd/root.go 77.77% 4 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Flag Coverage Δ
unittests 64.56% <82.42%> (+0.08%) ⬆️

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

Files with missing lines Coverage Δ
pkg/ui/heatmap/render.go 84.30% <100.00%> (+0.18%) ⬆️
cmd/root.go 46.72% <77.77%> (+1.65%) ⬆️
pkg/ui/heatmap/heatmap.go 84.01% <70.58%> (-1.61%) ⬇️
pkg/perf/perf.go 88.71% <87.00%> (-1.88%) ⬇️

... and 3 files with indirect coverage changes

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

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]>

@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/ui/heatmap/heatmap_test.go (1)

541-605: Strengthen parallelism assertions using the unused expectParallel field.

The test defines expectParallel but 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 0fca37d and 9f35c03.

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

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 13, 2025
@mergify

mergify Bot commented Oct 13, 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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 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 0012396 and 34d0982.

📒 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.go
  • cmd/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.go
  • cmd/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.go
  • cmd/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.go
  • cmd/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.go
  • cmd/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 with cmd/terraform_generate_backend_test.go.

Comment thread cmd/terraform_generate_backend_test.go Resolved
Comment thread cmd/terraform_generate_varfile_test.go Resolved
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]>
@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

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

350-355: Consider consolidating Total and SelfTime fields in Row struct.

Both Total and SelfTime now 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 3411ac8 and 716fe18.

📒 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() and UseSimpleTracking() are well-documented and provide necessary control over the tracking behavior.


130-138: LGTM! Clean routing between tracking modes.

The conditional routing based on useSimpleStack flag 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.Total to m.SelfTime correctly 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]>
@aknysh

Copy link
Copy Markdown
Member Author

CodeRabbit (@coderabbitai) full review

@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

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

101-106: Clear simple owner when disabling simple tracking

Avoid 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 churn

finish* 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 handling

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

📥 Commits

Reviewing files that changed from the base of the PR and between d72c802 and 716fe18.

⛔ Files ignored due to path filters (1)
  • website/static/img/cli/perf/atmos-describe-stacks-heatmap-bar-chart.png is 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.go
  • pkg/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 in terraform_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 with DisableFlagParsing. 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 in terraform_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 consistent

Terminology, 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

Comment thread pkg/perf/perf.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

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

101-106: Document the timing constraint for UseSimpleTracking.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 716fe18 and bfb1448.

📒 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 simpleOwnerGID and auto-enabling simple mode in EnableTracking aligns with the PR's performance goals. The comments clearly explain the rationale (faster Docker performance by avoiding per-call runtime.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:

  1. Empty stack: claim via CAS and fall back on mismatch.
  2. 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:

  1. Clamps negative selfTime (line 198).
  2. Pops the frame before checking for parent (thread-safe via internal locks).
  3. Clears ownership only when the stack becomes empty (line 210), allowing future single-goroutine fast path.
  4. 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 finishSimpleStackTracking and finishGoroutineLocalTracking makes 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.Total assignment at line 424 uses m.SelfTime with 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]>

@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 (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 = &registry{
     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 subtest
pkg/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.

📥 Commits

Reviewing files that changed from the base of the PR and between d72c802 and bfb1448.

⛔ Files ignored due to path filters (1)
  • website/static/img/cli/perf/atmos-describe-stacks-heatmap-bar-chart.png is 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.

Comment thread pkg/perf/perf.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between bfb1448 and d17ea69.

📒 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

Comment thread pkg/perf/perf.go Resolved
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 13, 2025
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]>
@aknysh
Andriy Knysh (aknysh) merged commit 8464ef4 into main Oct 13, 2025
@aknysh
Andriy Knysh (aknysh) deleted the update-heatmap-3 branch October 13, 2025 19:26
@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Oct 13, 2025
@github-actions

Copy link
Copy Markdown

These changes were released in v1.194.1.

This branch was successfully deployed

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

Labels

patch A minor, backward compatible change size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants