Skip to content

refactor(cmd): replace global initializers with lazy PersistentPreRunE - #3994

Merged
meet2mky merged 2 commits into
masterfrom
meet2mky/remove-cobra-global-initializer
Nov 10, 2025
Merged

meet2mky merged 2 commits into
masterfrom
meet2mky/remove-cobra-global-initializer

Conversation

@meet2mky

@meet2mky meet2mky commented Nov 9, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This pull request refactors the command initialization and configuration loading logic to fix a severe performance degradation in our unit tests.

The previous implementation used cobra.OnInitialize to register configuration functions. This is an anti-pattern for testable applications because OnInitialize appends to a global list of initializers, causing repeated test runs to become progressively slower as the list grows.

This change replaces the global initializer pattern with the recommended PersistentPreRunE lifecycle hook. All configuration loading, validation, and rationalization now happens within PersistentPreRunE. This isolates test cases and restores fast, consistent test performance.

Old Behavior

Previously, the newRootCmd function used cobra.OnInitialize to register initialization functions. These functions were responsible for reading the config file, validating flags, and rationalizing the final configuration.

The cobra.OnInitialize function works by appending the provided functions to a global list of initializers within the Cobra library. In our unit tests (e.g., in root_test.go), we call newRootCmd inside a loop for each test case. This led to the following problem:

  1. With each test case, new instances of the initialization functions were appended to the global list.
  2. The list of initializers grew larger with every test that ran.
  3. When cmd.Execute() was called for a given test, Cobra would execute all functions in the global list, including duplicates from all previous tests in the same suite.
  4. This resulted in a significant and compounding increase in the time it took to run each subsequent test, making the overall test suite extremely slow.

New Behavior

To resolve this issue, the configuration logic has been moved out of the global initialization path and into the PersistentPreRunE function of the root command.

PersistentPreRunE is a Cobra lifecycle hook that runs exactly once per command execution, right before the main RunE function. By placing the setup logic here, we achieve the following:

  1. No More Global State: The initialization is now tied to a specific command instance, not a global list.
  2. Test Isolation: Each call to newRootCmd in a test creates a fresh command. When cmd.Execute() is called, only the PersistentPreRunE for that specific instance is run.
  3. Consistent Performance: The initialization logic is executed once per test case, as intended. This eliminates the performance degradation and makes the unit tests consistently fast, regardless of how many test cases are in the suite.

This refactoring makes our command-line handling more robust, easier to reason about, and significantly improves the performance and reliability of our test suite.

Link to the issue in case of a bug fix.

b/459118811

Run time improvement in tests.

Package Run Time (Before) Run Time (After) Reduction
.../gcsfuse/v3/cmd 497.301s 3.123s 494.178s

Perf results

Branch File Size Read BW Write BW RandRead BW RandWrite BW
Master 0.25MiB 563.94MiB/s 1.3MiB/s 77.17MiB/s 1.45MiB/s
PR 0.25MiB 574.18MiB/s 1.33MiB/s 81.34MiB/s 1.13MiB/s
Master 48.828MiB 4679.08MiB/s 82.27MiB/s 1589.89MiB/s 85.75MiB/s
PR 48.828MiB 4679.33MiB/s 84.91MiB/s 1578.92MiB/s 87.16MiB/s
Master 976.562MiB 4684.07MiB/s 38.19MiB/s 1149.11MiB/s 39.66MiB/s
PR 976.562MiB 4702.87MiB/s 38.29MiB/s 1244.02MiB/s 39.19MiB/s

Testing details

  1. Manual - Yes
  2. Unit tests - Yes
  3. Integration tests - Yes (Zonal e2e, Regional e2e)

Any backward incompatible change? If so, please explain.

@meet2mky meet2mky self-assigned this Nov 9, 2025
@meet2mky meet2mky added execute-integration-tests Run only integration tests execute-integration-tests-on-zb To run E2E tests on zonal bucket. labels Nov 9, 2025
@codecov

codecov Bot commented Nov 9, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.09%. Comparing base (3016128) to head (0eff8ab).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
cmd/root.go 84.61% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3994      +/-   ##
==========================================
- Coverage   83.11%   83.09%   -0.03%     
==========================================
  Files         148      148              
  Lines       18187    18181       -6     
==========================================
- Hits        15116    15107       -9     
- Misses       2520     2522       +2     
- Partials      551      552       +1     
Flag Coverage Δ
unittests 83.09% <84.61%> (-0.03%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
@meet2mky meet2mky added execute-perf-test Execute performance test in PR and removed execute-integration-tests Run only integration tests execute-integration-tests-on-zb To run E2E tests on zonal bucket. labels Nov 9, 2025
@meet2mky
meet2mky marked this pull request as ready for review November 9, 2025 12:38
@meet2mky
meet2mky requested a review from a team as a code owner November 9, 2025 12:38
@github-actions

github-actions Bot commented Nov 9, 2025

Copy link
Copy Markdown

/gemini summary

@github-actions github-actions Bot added the remind-reviewers Auto remind reviewers in attention set for review post 24hrs of inactivity on PR. label Nov 9, 2025
@github-actions

github-actions Bot commented Nov 9, 2025

Copy link
Copy Markdown

/gemini review

@meet2mky meet2mky added execute-integration-tests Run only integration tests execute-integration-tests-on-zb To run E2E tests on zonal bucket. labels Nov 9, 2025
@meet2mky

meet2mky commented Nov 9, 2025

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request is an excellent refactoring that addresses a significant performance degradation in unit tests by replacing the global cobra.OnInitialize with the instance-specific PersistentPreRunE hook. The changes are well-implemented, follow Cobra best practices, and make the command initialization logic more robust and easier to reason about. The performance improvements demonstrated in the description are substantial. The code is clean, and the logic has been correctly migrated. I have no further comments; great work!

@kislaykishore

Copy link
Copy Markdown
Collaborator

/gemini review

@gemini-code-assist gemini-code-assist 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.

Code Review

This is an excellent refactoring that addresses a significant performance issue in the test suite by replacing the cobra.OnInitialize anti-pattern with the recommended PersistentPreRunE hook. The change is well-documented in the pull request description, including clear performance metrics that demonstrate the improvement. The new implementation is cleaner, more idiomatic, and correctly isolates command initialization, which is a great improvement for testability and maintainability. I have one minor suggestion to improve error handling consistency, but overall, this is a solid contribution.

Comment thread cmd/root.go Resolved
kislaykishore
kislaykishore previously approved these changes Nov 10, 2025
@meet2mky meet2mky removed execute-perf-test Execute performance test in PR execute-integration-tests Run only integration tests execute-integration-tests-on-zb To run E2E tests on zonal bucket. labels Nov 10, 2025
@meet2mky meet2mky added execute-integration-tests Run only integration tests execute-integration-tests-on-zb To run E2E tests on zonal bucket. labels Nov 10, 2025
@meet2mky meet2mky removed the execute-integration-tests-on-zb To run E2E tests on zonal bucket. label Nov 10, 2025
@kislaykishore
kislaykishore self-requested a review November 10, 2025 08:22
@meet2mky
meet2mky merged commit e557052 into master Nov 10, 2025
@kislaykishore
kislaykishore deleted the meet2mky/remove-cobra-global-initializer branch November 10, 2025 08:23
@ashmeenkaur

Copy link
Copy Markdown
Contributor

Great find!

kislaykishore added a commit that referenced this pull request Aug 26, 2026
#5046)

* build(deps): upgrade Go to 1.26.7 and dependencies for CVE remediation

* upgrade golang to 1.26.7 (CVE fixes)

* test(monitoring): use NewTextParser with LegacyValidation for prometheus/common v0.70.1

* fix(ci): update golangci-lint args in CI workflow

* refactor(cmd): replace global initializers with lazy PersistentPreRunE (#3994)

* fix(test): use 4095 for FUSE max name length (#4810)

On newer Linux kernels, FUSE_NAME_MAX is set to PATH_MAX - 1 (4095). Setting
fuseMaxNameLen to 4095 allows us to test illegal filename lengths with a value
that consistently triggers a kernel-level ENAMETOOLONG error across different
kernel versions.

Use a separate gcsMaxNameLen (1024) for the longest legal name test, matching
the GCS limit.

TAG=agy
CONV=cb2ad2c9-cd41-4085-af5c-0f82aa999dca

* fix(test): exclude unicode.Cn category in interestingNames and interestingLegalNames (#4456)

* test(cache): remove unaligned writer offset test case in CopyUsingMemoryAlignedBuffer

* fix(test): allow EPERM or ENOSYS in DirectoryTest.CreateHardLink for newer kernels (#4354)

* revert: fix(test): use 4095 for FUSE max name length (#4810)

* Revert "revert: fix(test): use 4095 for FUSE max name length (#4810)"

This reverts commit 2b19ee5.

---------

Co-authored-by: Geert Jansen <geertj@google.com>
saisagar1998 pushed a commit that referenced this pull request Nov 16, 2026
#3994)

* remove global initializers from cobra

* review fixes: wrap error based on failures

(cherry picked from commit e557052)
saisagar1998 added a commit that referenced this pull request Nov 16, 2026
…ypto for CVE remediation (#5252)

* fix(deps): upgrade Go to 1.27.4, go-jose/v4 to v4.1.6, x/net and x/crypto for CVE remediation

* refactor(cmd): replace global initializers with lazy PersistentPreRunE (#3994)

* remove global initializers from cobra

* review fixes: wrap error based on failures

(cherry picked from commit e557052)

* updated  otel version to 1.47.0 because of https://osv.dev/GHSA-q7gw-24fr-5p69

---------

Co-authored-by: Mohit Kumar Yadav <mohitkyadav@google.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

execute-integration-tests Run only integration tests remind-reviewers Auto remind reviewers in attention set for review post 24hrs of inactivity on PR.

3 participants