-
Notifications
You must be signed in to change notification settings - Fork 259
Closed
Labels
automatedIssues created by cagentIssues created by cagentkind/bugSomething isn't workingSomething isn't working
Description
🟠 high - bug
File: cmd/root/run.go (line 161)
Code
if f.cpuProfile != "" {
pf, err := os.Create(f.cpuProfile)
if err != nil {
return fmt.Errorf("failed to create CPU profile: %w", err)
}
if err := pprof.StartCPUProfile(pf); err != nil {
pf.Close()
return fmt.Errorf("failed to start CPU profile: %w", err)
}
defer pprof.StopCPUProfile()
defer pf.Close()
slog.Info("CPU profiling enabled", "file", f.cpuProfile)
}Problem
If pprof.StartCPUProfile(pf) returns an error, pf.Close() is called, but pprof.StopCPUProfile() is not called. This could lead to a partially started CPU profile or other resource issues if StartCPUProfile allocates resources that need to be cleaned up by StopCPUProfile. The deferred call to pprof.StopCPUProfile() will only be executed if pprof.StartCPUProfile is successful.
Suggested Fix
Only defer pprof.StopCPUProfile() if pprof.StartCPUProfile returns no error. One approach is to use a flag to track whether profiling was successfully started:
if f.cpuProfile != "" {
pf, err := os.Create(f.cpuProfile)
if err != nil {
return fmt.Errorf("failed to create CPU profile: %w", err)
}
// Ensure pf is closed even if StartCPUProfile fails.
// If StartCPUProfile succeeds, pf will be closed by the later defer.
closed := false
defer func() {
if !closed {
pf.Close()
}
}()
if err := pprof.StartCPUProfile(pf); err != nil {
return fmt.Errorf("failed to start CPU profile: %w", err)
}
defer pprof.StopCPUProfile()
// Mark as closed by defer
closed = true
defer pf.Close()
slog.Info("CPU profiling enabled", "file", f.cpuProfile)
}Found by nightly codebase scan
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
automatedIssues created by cagentIssues created by cagentkind/bugSomething isn't workingSomething isn't working