mirror of
https://github.com/chenhg5/cc-connect.git
synced 2026-07-06 05:37:53 +08:00
ListSessions reads a.cmd and a.workDir without holding a.mu, while SetWorkDir / SetSessionEnv / StartSession all touch those fields under the lock. ProjectMemoryFile likewise reads a.workDir directly. The sibling DeleteSession already uses the canonical "capture under RLock" pattern; ListSessions and ProjectMemoryFile were the inconsistent ones. SetWorkDir mutates a.workDir under a.mu, so /workspace landing on one goroutine while /list or a memory-file lookup runs on another races on the string field. Strings carry a (ptr, len) pair, and a torn read of a different-length string can produce a frankenstring whose pointer doesn't match its length, leading to memory-safety failures or empty/garbled paths. Capture cmd and workDir inside the locked section in ListSessions; capture workDir in ProjectMemoryFile. No public API or behaviour change. Regression: TestOpencodeAgent_WorkDirRaceFreeReaders spawns concurrent SetWorkDir writers and ListSessions / ProjectMemoryFile readers under -race. Without the production fix the test trips "DATA RACE detected"; with the fix the detector stays quiet.
49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
package opencode
|
|
|
|
import (
|
|
"context"
|
|
"path/filepath"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// TestOpencodeAgent_WorkDirRaceFreeReaders pins the bug where
|
|
// ListSessions and ProjectMemoryFile read a.workDir (and a.cmd, in
|
|
// ListSessions' case) without holding a.mu, while SetWorkDir writes
|
|
// a.workDir under the lock. Run with -race to detect the data race;
|
|
// with the production fix the test stays clean.
|
|
func TestOpencodeAgent_WorkDirRaceFreeReaders(t *testing.T) {
|
|
dir := t.TempDir()
|
|
a := &Agent{workDir: dir, cmd: "opencode"}
|
|
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 30; i++ {
|
|
wg.Add(1)
|
|
go func(i int) {
|
|
defer wg.Done()
|
|
if i%2 == 0 {
|
|
a.SetWorkDir(filepath.Join(dir, "a"))
|
|
} else {
|
|
a.SetWorkDir(filepath.Join(dir, "b"))
|
|
}
|
|
}(i)
|
|
}
|
|
for i := 0; i < 30; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
// ListSessions execs `opencode session list`; with a
|
|
// non-existent binary it returns an error immediately.
|
|
// The race detector still observes the unlocked field
|
|
// reads before the exec attempt.
|
|
_, _ = a.ListSessions(context.Background())
|
|
}()
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
_ = a.ProjectMemoryFile()
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
}
|