Skip to content

perf: speed up EncodeSourceVersion by multiple optimizations #4533

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

healthy-pod
Copy link

@healthy-pod healthy-pod commented Jul 11, 2025

Description

  1. Use WalkDir to only call os.Stat when needed (i.e. when access to file modification time is needed). Previously, it was called on all entries. This cut EncodeSourceVersion time in one of our private workspaces from 43s to 34s.

  2. Skip walking cache directories completely by returning filepath.SkipDir when hitting one. Previously, we just returned nil which meant we still had to walk everything in the file tree.
    This cut EncodeSourceVersion time in one of our private workspaces from 34s to ~nil.

TODOs

Read the Gruntwork contribution guidelines.

  • I authored this code entirely myself
  • I am submitting code based on open source software (e.g. MIT, MPL-2.0, Apache)]
  • I am adding or upgrading a dependency or adapted code and confirm it has a compatible open source license
  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Updated EncodeSourceVersion to make less stat calls and skip walking cache dirs.

Migration Guide

Summary by CodeRabbit

  • Bug Fixes

    • Improved directory traversal to more reliably skip .terragrunt-cache and .terraform directories when processing local sources.
  • Chores

    • Updated internal handling of file permissions and directory entry checks for better compatibility and maintainability.

Copy link
Contributor

coderabbitai bot commented Jul 11, 2025

📝 Walkthrough

Walkthrough

The code updates the source directory traversal in the EncodeSourceVersion method by switching from filepath.Walk to filepath.WalkDir, updating directory and file handling logic accordingly. It also adjusts file permission syntax for writing the version file and imports the io/fs package to support the new traversal method.

Changes

File(s) Change Summary
tf/source.go Replaced filepath.Walk with filepath.WalkDir in source traversal; updated callback logic, directory skipping, file info retrieval, and file permission syntax; imported io/fs.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Source
    participant OS

    Caller->>Source: EncodeSourceVersion()
    Source->>OS: WalkDir(sourceDir, callback)
    loop For each entry
        OS-->>Source: path, DirEntry, err
        alt Entry is directory and name is .terragrunt-cache or .terraform
            Source->>OS: SkipDir
        else Entry is file
            Source->>OS: Stat(path)
            OS-->>Source: FileInfo
            Source->>Source: Update hash with file mod time
        end
    end
    Source-->>Caller: hash value
    Caller->>Source: WriteVersionFile()
    Source->>OS: Write file with 0o640 permissions
    OS-->>Source: Success/Failure
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

vercel bot commented Jul 11, 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 Jul 11, 2025 8:33pm

1. Use `WalkDir` to only call `os.Stat` when needed (i.e. when access to file modification
time is needed). Previously, it was called on all entries.
This cut `EncodeSourceVersion` time in one of our private workspaces from 43s to 34s.

2. Skip walking cache directories completely by returning `filepath.SkipDir` when hitting
one. Previously, we just returned nil which meant we still had to walk everything in the
file tree.
This cut `EncodeSourceVersion` time in one of our private workspaces from 34s to ~nil.
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2de4b8c and 6801ed6.

📒 Files selected for processing (1)
  • tf/source.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧠 Learnings (1)
tf/source.go (3)
Learnt from: yhakbar
PR: gruntwork-io/terragrunt#4169
File: cli/commands/hcl/validate/cli.go:29-60
Timestamp: 2025-04-17T13:02:28.098Z
Learning: Avoid shadowing imported packages with local variables in Go code, such as using a variable named `flags` when the `github.com/gruntwork-io/terragrunt/cli/flags` package is imported. Use more specific variable names like `flagSet` instead.
Learnt from: wakeful
PR: gruntwork-io/terragrunt#4491
File: test/integration_test.go:4265-4265
Timestamp: 2025-07-03T22:05:07.356Z
Learning: Constants defined in one Go file are accessible from other files in the same package without explicit imports. When reviewing Go code, consider the package-level scope rather than just the individual file scope.
Learnt from: levkohimins
PR: gruntwork-io/terragrunt#3723
File: cli/commands/stack/action.go:160-160
Timestamp: 2025-02-10T13:36:19.542Z
Learning: The project uses a custom error package `github.com/gruntwork-io/terragrunt/internal/errors` which provides similar functionality to `fmt.Errorf` but includes stack traces. Prefer using this package's error functions (e.g., `errors.Errorf`, `errors.New`) over the standard library's error handling.
🧬 Code Graph Analysis (1)
tf/source.go (1)
util/file.go (2)
  • IsDir (184-187)
  • TerragruntCacheDir (27-27)
🔇 Additional comments (4)
tf/source.go (4)

7-7: LGTM: Import addition necessary for fs.DirEntry

The io/fs import is required for the fs.DirEntry type used in the filepath.WalkDir callback function.


91-91: LGTM: Excellent performance optimization

Switching from filepath.Walk to filepath.WalkDir is a great optimization that avoids unnecessary os.Stat calls on every directory entry. This aligns perfectly with the PR objective of reducing stat calls.


110-114: LGTM: Proper file info handling with error checking

The code correctly calls os.Stat(path) only when file information is actually needed (for files, not directories) and properly handles any errors that might occur. This maintains the same functionality while improving performance.


152-152: LGTM: Modernized octal literal syntax

Good modernization to use Go 1.13+ octal literal syntax 0o640 instead of the older 0640 format.

Comment on lines +97 to 108
if entry.IsDir() {
// avoid checking files in .terragrunt-cache directory since contents is auto-generated
if strings.Contains(path, util.TerragruntCacheDir) {
return filepath.SkipDir
}
// avoid checking files in .terraform directory since contents is auto-generated
if entry.Name() == util.TerraformLockFile {
return filepath.SkipDir
}
// We don't use any info from directories to calculate our hash
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the .terraform directory check logic

The directory skipping logic correctly uses filepath.SkipDir for better performance, but there's an issue with the .terraform directory check.

The code checks entry.Name() == util.TerraformLockFile, but based on the comment "avoid checking files in .terraform directory", this should be checking for the directory name ".terraform" instead of the lock file name.

Apply this diff to fix the directory check:

-				// avoid checking files in .terraform directory since contents is auto-generated
-				if entry.Name() == util.TerraformLockFile {
-					return filepath.SkipDir
-				}
+				// avoid checking files in .terraform directory since contents is auto-generated
+				if entry.Name() == ".terraform" {
+					return filepath.SkipDir
+				}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if entry.IsDir() {
// avoid checking files in .terragrunt-cache directory since contents is auto-generated
if strings.Contains(path, util.TerragruntCacheDir) {
return filepath.SkipDir
}
// avoid checking files in .terraform directory since contents is auto-generated
if entry.Name() == util.TerraformLockFile {
return filepath.SkipDir
}
// We don't use any info from directories to calculate our hash
return nil
}
if entry.IsDir() {
// avoid checking files in .terragrunt-cache directory since contents is auto-generated
if strings.Contains(path, util.TerragruntCacheDir) {
return filepath.SkipDir
}
// avoid checking files in .terraform directory since contents is auto-generated
if entry.Name() == ".terraform" {
return filepath.SkipDir
}
// We don't use any info from directories to calculate our hash
return nil
}
🤖 Prompt for AI Agents
In tf/source.go around lines 97 to 108, the code incorrectly checks for the
.terraform directory by comparing entry.Name() to util.TerraformLockFile, which
is a file name, not a directory. To fix this, change the condition to check if
entry.Name() equals the string ".terraform" to properly skip the .terraform
directory using filepath.SkipDir.

@denis256
Copy link
Member

Hi,
Consider running make run-lint to run lint checks locally:

level=info msg="File cache stats: 1 entries of total size 14.2KiB"
level=info msg="Memory: 857 samples, avg is 111.6MB, max is 1052.8MB"
level=info msg="Execution took 1m25.991943112s"
tf/source.go:114:5: assignments should only be cuddled with other assignments (wsl)
				fileModified := fileInfo.ModTime().UnixMicro()
				^
1 issues:
* wsl: 1
make: *** [Makefile:[42](https://github.com/gruntwork-io/terragrunt/actions/runs/16296496947/job/46019409624?pr=4533#step:8:43): run-lint] Error 1

Looks like TestInitSkipCache is failing

2025-07-15T14:49:42.0137091Z --- FAIL: TestInitSkipCache (23.88s)

FAILTestInitSkipCache.txt

@yhakbar yhakbar marked this pull request as draft July 24, 2025 16:24
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