usage: Append keeps the log open between calls, not an open and a close for each request (#3725)

Every request the gateway serves appends a line to usage.jsonl, and
Append opened and closed the file each time. In a CPU profile of the
request path (BenchmarkZZIO, a local benchmark not committed) Append was
0.51s of the handler's 1.36s, 0.35s of it in os.OpenFile and 0.07s in
Close.

Now the handle is held, under the same mu. Before each write the held
file's identity is checked against what Path names now (fstat and stat,
os.SameFile), so a log another program moves, removes or replaces, or a
Path that changes with HOME, is opened again. A failed write drops the
handle. Windows still closes after each write, since a file held open
there can't be removed or renamed.

Measured (local microbenchmark, open+fstat+write+fstat+close against a
held file with stat+fstat+write+fstat, 600-byte lines, 20000 runs, load
~80): 55 to 116µs per call before, 11 to 24µs held. On the whole
request (BenchmarkZZIO) the difference is inside the noise at this load,
so no request-time figure is claimed.

TestAppendHeldLogFollowsThePath appends twice and checks the second call
used the same handle (and that Windows holds none), then replaces the log
by rename, removes it, and moves HOME, checking each time that the next
call is counted in the file Path names. Broken by hand (identity check
skipped) it is red: after a replacement the call went to the old file and
Summarize counted 0 calls.

Windows box (test binary run outside the source tree): internal/usage,
mine and origin/main 92cf0b68d, both fail the same three tests:
TestDesktopSessionAccountMetadata (#1356), and TestKimiCodeCost and
TestRequestDiskNamesItsSource, which read testdata and source files that
aren't beside the binary there. TestUsageReadAfterAppendHashesNothingOnAFineClock
was red once in my first full run (#3511, the whole-second case); it
passed 30 of 30 alone with this change and in the next full run.

Run at this tree (fcbf618eb plus this change): gofmt -l internal/usage
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
ok; go test -count=1 -timeout 45m ./internal/usage ./internal/usageapi
./internal/gateway ok (16.161s, 6.655s, 448.476s).
This commit is contained in:
yetone
2026-10-27 02:25:45 +08:00
parent fcbf618ebb
commit 39526c0690
2 changed files with 118 additions and 12 deletions
+59
View File
@@ -0,0 +1,59 @@
package usage
import (
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
// Append keeps the log open between calls (#3725), and still writes to
// the file Path names after another program replaces or removes it.
func TestAppendHeldLogFollowsThePath(t *testing.T) {
pageHome(t)
holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
t.Cleanup(func() {
mu.Lock()
defer mu.Unlock()
if heldLog.f != nil {
heldLog.f.Close()
heldLog.f = nil
}
})
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 2, Status: 200})
first := heldLog.f
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 3, Status: 200})
if runtime.GOOS != "windows" && (first == nil || heldLog.f != first) {
t.Fatalf("the log was opened again for the second call: %p then %p", first, heldLog.f)
}
if runtime.GOOS == "windows" && heldLog.f != nil {
t.Fatal("Windows kept the log open")
}
f := filepath.Join(filepath.Dir(Path()), "replacement.jsonl")
if err := os.WriteFile(f, nil, 0o600); err != nil {
t.Fatal(err)
}
if err := os.Rename(f, Path()); err != nil {
t.Fatal(err)
}
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 7, Status: 200})
if s := Summarize(Today); s.Input != 7 || s.Calls != 1 {
t.Fatalf("after a replacement: %+v", s.Totals)
}
if err := os.Remove(Path()); err != nil {
t.Fatal(err)
}
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 11, Status: 200})
if s := Summarize(Today); s.Input != 11 || s.Calls != 1 {
t.Fatalf("after a removal: %+v", s.Totals)
}
pageHome(t) // another HOME: the log is another file
Append(Record{Agent: "codex", Provider: "relay", Model: "m", Input: 13, Status: 200})
if s := Summarize(Today); s.Input != 13 || s.Calls != 1 {
t.Fatalf("in another HOME: %+v", s.Totals)
}
}
+59 -12
View File
@@ -13,6 +13,7 @@ import (
"math"
"os"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
@@ -245,21 +246,67 @@ func Append(r Record) {
}
mu.Lock()
defer mu.Unlock()
// the folder is made only when it is missing: every request appends,
// and MkdirAll stat'ed it each time (#3725)
f, err := os.OpenFile(Path(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if errors.Is(err, fs.ErrNotExist) && os.MkdirAll(filepath.Dir(Path()), 0o755) == nil {
f, err = os.OpenFile(Path(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
}
if err != nil {
path := Path()
f, before := openLog(path)
if f == nil {
return
}
defer f.Close()
before, _ := statLogHandle(f)
if _, err := f.Write(append(b, '\n')); err == nil {
after, _ := statLogHandle(f)
noteLogAppend(Path(), before, after)
if !holdLog {
defer f.Close()
}
if _, err := f.Write(append(b, '\n')); err != nil {
if holdLog {
f.Close()
heldLog.f = nil
}
return
}
after, _ := statLogHandle(f)
noteLogAppend(path, before, after)
}
// heldLog is the log Append keeps open between calls, under mu: every
// request appends, and an open and a close of usage.jsonl each time was
// most of Append's time (#3725). It is written to only while Path still
// names that same file, so a log moved, removed or replaced is opened
// again. Windows closes it after each write, since a file open there
// can't be removed or renamed.
var heldLog struct {
path string
f *os.File
}
const holdLog = runtime.GOOS != "windows"
// openLog returns the log to append to and its state before the write,
// or nil when it can't be opened.
func openLog(path string) (*os.File, os.FileInfo) {
if f := heldLog.f; f != nil {
heldLog.f = nil
if heldLog.path == path {
before, err := statLogHandle(f)
now, nerr := statLogFile(path)
if err == nil && nerr == nil && sameLogFile(before, now) {
heldLog.f = f
return f, before
}
}
f.Close()
}
// the folder is made only when it is missing: every request appends,
// and MkdirAll stat'ed it each time (#3725)
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if errors.Is(err, fs.ErrNotExist) && os.MkdirAll(filepath.Dir(path), 0o755) == nil {
f, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
}
if err != nil {
return nil, nil
}
before, _ := statLogHandle(f)
if holdLog {
heldLog.path, heldLog.f = path, f
}
return f, before
}
// IsRejected also recognizes local rejections written before the explicit flag.