Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

filelock: a lock makes its folder only when the folder is missing

yetone3d55ff473f08
diff --git a/internal/filelock/filelock.go b/internal/filelock/filelock.go
index 42a7b8f6d..38267c044 100644
--- a/internal/filelock/filelock.go
+++ b/internal/filelock/filelock.go
@@ -4,6 +4,8 @@
package filelock
import (
+ "errors"
+ "io/fs"
"log"
"os"
"path/filepath"
@@ -17,6 +19,9 @@ import (
// holds) never hangs every other.
const Wait = 10 * time.Second
+// mkdirAll makes a lock file's folder; a test counts the calls.
+var mkdirAll = os.MkdirAll
+
// Lock takes the lock on the file at path, made if it isn't there, waiting
// up to wait for another process to let it go. The system holds it on the
// file and lets it go when the process holding it ends, however it ends,
@@ -25,8 +30,15 @@ const Wait = 10 * time.Second
// held is false when it went on without the lock: on a file system
// without locks, or after wait.
func Lock(path string, wait time.Duration) (unlock func(), held bool) {
- os.MkdirAll(filepath.Dir(path), 0o700)
+ // the folder is made only when the file can't be opened for want of
+ // it: made first, each lock asked the system for the folder too, on
+ // every take (#1665: ~190 times in a Windows start's first 25s, each
+ // an antivirus filter driver's work)
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
+ if errors.Is(err, fs.ErrNotExist) {
+ mkdirAll(filepath.Dir(path), 0o700)
+ f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
+ }
if err != nil {
return func() {}, false // no lock to be had here: no file to change either
}
diff --git a/internal/filelock/filelock_test.go b/internal/filelock/filelock_test.go
index 065b5ada2..00025426e 100644
--- a/internal/filelock/filelock_test.go
+++ b/internal/filelock/filelock_test.go
@@ -67,3 +67,32 @@ func TestLockAcrossProcesses(t *testing.T) {
}
unlock()
}
+
+// #1665: each take asked the system to make the lock file's folder before
+// it opened the file, ~190 times in a Windows start's first 25s, each one
+// work an antivirus filter driver adds its own to. The folder is made only
+// when it is missing.
+func TestLockMakesFolderOnlyWhenMissing(t *testing.T) {
+ made := 0
+ was := mkdirAll
+ mkdirAll = func(p string, m os.FileMode) error { made++; return was(p, m) }
+ t.Cleanup(func() { mkdirAll = was })
+
+ path := filepath.Join(t.TempDir(), "new", "f.json.lock")
+ unlock, held := Lock(path, time.Second)
+ if !held {
+ t.Fatal("not held in a folder not there yet")
+ }
+ unlock()
+ if made != 1 {
+ t.Fatalf("missing folder made %d times, want 1", made)
+ }
+ m := Mutex{Path: func() string { return path }}
+ for range 20 {
+ m.Lock()
+ m.Unlock()
+ }
+ if made != 1 {
+ t.Fatalf("20 takes in a folder that is there made it %d more times", made-1)
+ }
+}