Skip to content

feat: performance improvement on -version execution #4288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 21, 2025
Merged

feat: performance improvement on -version execution #4288

merged 10 commits into from
May 21, 2025

Conversation

denis256
Copy link
Member

@denis256 denis256 commented May 15, 2025

Description

  • added caching of -version execution
  • added integration test to track that -version is invoked only once

Test results on running 10 times a stack of 20 units on different versions vs current branch

hyperfine-v2

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Added / Removed / Updated [X].

Migration Guide

Summary by CodeRabbit

  • New Features
    • Improved performance by adding caching for Terraform version detection, reducing redundant version checks.
  • Tests
    • Added tests to verify that the Terraform version command is invoked only once and correctly across different directories.
  • Bug Fixes
    • Corrected the working directory used in a dependency validation test.

Copy link

vercel bot commented May 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 20, 2025 9:38pm

Copy link
Contributor

coderabbitai bot commented May 15, 2025

📝 Walkthrough

"""

Walkthrough

A version cache mechanism was introduced to optimize the retrieval of the Terraform version in the Terragrunt CLI. Context management utilities for the cache were added, and the version check logic was updated to use this cache. Integration tests verify the number of Terraform version command invocations. New Terraform and Terragrunt configuration fixtures support these tests.

Changes

File(s) Change Summary
cli/app.go Imports the new run version cache utilities and wraps the context with run.WithRunVersionCache(ctx) in the application's RunContext method.
cli/commands/run/context.go New file introducing context key types and two functions: WithRunVersionCache for storing a version cache in context, and GetRunVersionCache for retrieving it.
cli/commands/run/version_check.go Updates PopulateTerraformVersion to use a cache keyed by the hash of version file contents, avoiding redundant Terraform version command executions. Adds computeVersionFilesCacheKey function.
test/integration_test.go Fixes an import, adjusts a test directory argument, and adds TestVersionIsInvokedOnlyOnce and TestVersionIsInvokedInDifferentDirectory to verify Terraform version command invocation counts.
test/fixtures/version-invocation/app/main.tf Adds Terraform configuration declaring an input variable and output referencing it.
test/fixtures/version-invocation/app/terragrunt.hcl Adds Terragrunt configuration with two dependencies and input mapping from a dependency output.
test/fixtures/version-invocation/dependency/main.tf Adds Terraform output returning a static string "42".
test/fixtures/version-invocation/dependency-with-custom-version/.tool-versions Adds a .tool-versions file specifying the tofu tool version 1.9.4.
test/fixtures/version-invocation/dependency-with-custom-version/main.tf Adds Terraform output returning a static string "42".

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant RunContext
    participant RunVersionCache
    participant VersionCheck
    participant Terraform

    App->>RunContext: Start application
    RunContext->>RunVersionCache: WithRunVersionCache(ctx)
    RunContext->>VersionCheck: PopulateTerraformVersion(ctx, options)
    VersionCheck->>RunVersionCache: GetRunVersionCache(ctx)
    alt Cache hit
        RunVersionCache-->>VersionCheck: Return cached version output
        VersionCheck-->>RunContext: Use cached version info
    else Cache miss
        VersionCheck->>Terraform: Run terraform --version
        Terraform-->>VersionCheck: Return version output
        VersionCheck->>RunVersionCache: Store version output in cache
        VersionCheck-->>RunContext: Use new version info
    end
Loading

Suggested reviewers

  • yhakbar
    """

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c2aab7e and ee0c28b.

📒 Files selected for processing (6)
  • test/fixtures/version-invocation/app/main.tf (1 hunks)
  • test/fixtures/version-invocation/app/terragrunt.hcl (1 hunks)
  • test/fixtures/version-invocation/dependency-with-custom-version/.tool-versions (1 hunks)
  • test/fixtures/version-invocation/dependency-with-custom-version/main.tf (1 hunks)
  • test/fixtures/version-invocation/dependency/main.tf (1 hunks)
  • test/integration_test.go (4 hunks)
✅ Files skipped from review due to trivial changes (5)
  • test/fixtures/version-invocation/app/terragrunt.hcl
  • test/fixtures/version-invocation/dependency-with-custom-version/.tool-versions
  • test/fixtures/version-invocation/dependency/main.tf
  • test/fixtures/version-invocation/app/main.tf
  • test/fixtures/version-invocation/dependency-with-custom-version/main.tf
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • test/integration_test.go
🧬 Code Graph Analysis (1)
test/integration_test.go (2)
test/helpers/package.go (4)
  • RunTerragruntCommand (785-789)
  • CopyEnvironment (83-96)
  • CleanupTerraformFolder (719-726)
  • RunTerragruntCommandWithOutput (827-831)
util/file.go (1)
  • JoinPath (472-474)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Pull Request has non-contributor approval
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (3)
test/integration_test.go (3)

19-19: Import statement cleanup looks good.

Removing the unnecessary alias for the print package makes the code cleaner and more readable.


116-116: New test fixture constant added correctly.

This constant will be used by the new test cases to reference the version-invocation test fixtures.


4141-4156: Good test implementation for version caching.

This test verifies the core functionality of the PR - ensuring that the terraform version command is invoked only once when running multiple modules, confirming the caching mechanism works as expected.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@denis256 denis256 marked this pull request as ready for review May 20, 2025 21:14
@denis256 denis256 requested a review from yhakbar as a code owner May 20, 2025 21:14
func computeVersionFilesCacheKey(workingDir string) string {
var hashes []string

files := []string{".terraform-version", ".tool-versions"}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This could be many more files including mise.toml or .mise.toml.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (2)
cli/app.go (1)

111-111: Approve caching of Terraform version & suggest documenting it
Wrapping the context with run.WithRunVersionCache(ctx) ensures that the -version command is invoked only once per run, delivering the intended performance improvement. Its placement—after engine context setup and before command execution—is appropriate.
Consider adding a brief comment above this line to explain the purpose of the version cache.

cli/commands/run/version_check.go (1)

240-263: Consider some enhancements to the cache key computation.

The function is well-implemented, but has a few areas for improvement:

  1. It silently ignores errors from FileSHA256 without logging
  2. The version file names are hard-coded within the function

Consider these improvements:

+// Version files that are checked to compute the cache key
+var VersionFiles = []string{".terraform-version", ".tool-versions"}

 // Helper to compute a cache key from the checksums of .terraform-version and .tool-versions
 func computeVersionFilesCacheKey(workingDir string) string {
 	var hashes []string

-	files := []string{".terraform-version", ".tool-versions"}
+	files := VersionFiles

 	for _, file := range files {
 		path := filepath.Join(workingDir, file)
 		if util.FileExists(path) {
 			hash, err := util.FileSHA256(path)
 			if err == nil {
 				hashes = append(hashes, file+":"+hex.EncodeToString(hash))
+			} else {
+				// Log error for debugging but continue
+				// terragruntOptions.Logger.Debugf("Error hashing file %s: %v", path, err)
 			}
 		}
 	}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 594134b and 12394e0.

📒 Files selected for processing (4)
  • cli/app.go (2 hunks)
  • cli/commands/run/context.go (1 hunks)
  • cli/commands/run/version_check.go (4 hunks)
  • test/integration_test.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • cli/app.go
  • cli/commands/run/version_check.go
  • test/integration_test.go
  • cli/commands/run/context.go
🧬 Code Graph Analysis (4)
cli/app.go (1)
cli/commands/run/context.go (1)
  • WithRunVersionCache (17-20)
cli/commands/run/version_check.go (3)
cli/commands/run/context.go (1)
  • GetRunVersionCache (23-25)
util/file.go (2)
  • FileExists (57-60)
  • FileSHA256 (805-831)
util/hash.go (1)
  • EncodeBase64Sha1 (16-19)
test/integration_test.go (2)
test/helpers/package.go (4)
  • RunTerragruntCommand (785-789)
  • CopyEnvironment (83-96)
  • CleanupTerraformFolder (719-726)
  • RunTerragruntCommandWithOutput (827-831)
util/file.go (1)
  • JoinPath (472-474)
cli/commands/run/context.go (1)
internal/cache/cache.go (3)
  • NewCache (24-30)
  • Cache (17-21)
  • ContextCache (119-126)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test (macos)
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (8)
cli/app.go (1)

10-10: Approve import of run package
The new import "github.com/gruntwork-io/terragrunt/cli/commands/run" is necessary to enable the version cache in the CLI and is correctly added.

test/integration_test.go (3)

19-19: Import statement corrected

Removed erroneous alias from the import of the print package, making the code cleaner and more maintainable.


1961-1961: Fixed test working directory path

Changed the working directory argument in TestDependencyMockOutputRestricted from dependent2Path to rootPath. This properly sets the validation test to run from the root directory rather than from a subdirectory.


4140-4155: Good test for version caching mechanism

This new test validates that the -version command is invoked only once during a multi-module run, confirming that the caching mechanism is working correctly. The test effectively:

  1. Sets up a test environment with multiple modules
  2. Runs a terragrunt command with tracing enabled
  3. Verifies via regex that the version command appears exactly once in the logs

This directly tests the feature described in the PR objectives.

cli/commands/run/context.go (1)

1-26: Clean implementation of context-based version caching.

The context management is well-structured, using a typed key and constants for the cache. The function names are clear and follow Go conventions. The use of generics for the cache implementation is appropriate for type safety.

cli/commands/run/version_check.go (3)

92-112: Well-implemented caching mechanism.

The caching implementation effectively checks for cached version output before running the Terraform command, which should provide the intended performance improvement for the -version command execution.


133-134: Good cache update approach.

Storing the command output in the cache after execution ensures it will be available for subsequent calls.


7-8: Good import organization and hex encoding usage.

The addition of the hex encoding import and path/filepath packages correctly supports the new caching functionality.

Also applies to: 11-12

@@ -4136,3 +4136,20 @@ func TestTfPath(t *testing.T) {

assert.Regexp(t, "(?i)(terraform|opentofu)", stdout+stderr)
}

func TestVersionIsInvokedOnlyOnce(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

We should include a version where at least two fire from .tool-version files, etc.

cacheKey = strings.Join(hashes, "|")
}

return util.EncodeBase64Sha1(cacheKey)
Copy link
Collaborator

Choose a reason for hiding this comment

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

NIT: Should we be SHA-ing this? It's going to get hashed by the standard library when used for the key of the map, right? I don't think it's super important, just trying to confirm my understanding right.

Copy link
Member Author

Choose a reason for hiding this comment

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

util.FileSHA256(path) - returns 8kb byte array, encoded in hex it is quite large key.

sha1.Sum([]byte(str)) - return 20 bytes

Copy link
Collaborator

Choose a reason for hiding this comment

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

I was just saying that I don't know that we need to hash this, as it's used as the key for the hashmap, which is going to get hashed by the standard library, right?

@@ -27,6 +31,8 @@ var TerraformVersionRegex = regexp.MustCompile(`^(\S+)\s(v?\d+\.\d+\.\d+)`)

const versionParts = 3

var versionFiles = []string{".terraform-version", ".tool-versions", "mise.toml", ".mise.toml"}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do you think we should make a ticket to backlog making this configurable? Maybe a user can just feed Terragrunt the files that might be used to control TF versions outside these defaults?

Copy link
Member Author

Choose a reason for hiding this comment

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

Will raise another ticket for this

yhakbar
yhakbar previously approved these changes May 20, 2025
Copy link
Collaborator

@yhakbar yhakbar left a comment

Choose a reason for hiding this comment

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

We can do the bonus test for checking that version files trigger multiple -version calls later, IMO. It doesn't have to block you.

@denis256 denis256 merged commit 958f0c9 into main May 21, 2025
40 of 42 checks passed
@denis256 denis256 deleted the tg-916 branch May 21, 2025 13:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants