Files
magpie/internal/library/treememo.go
T
yetone 3a80ce7fa0 library: reading the Library page no longer reads every byte of the agents' skills each time; a folder unchanged since the last read isn't opened again (#541)
0day404 (#541, Windows): the Library page spins for minutes each time it
is opened. The page waits on GET /api/library, and library.Read, under
the library lock, compared every skill an agent has of its own with the
same name in each other agent byte by byte (foundSkills -> sameTree ->
sameFile) and hashed every library skill given as a copy (behind ->
libHash -> hashDir). Skills with node_modules or templates, given to
several agents, are hundreds of MB per read; on Windows each file opened
is scanned.

What sameTree and hashFiles found is now kept against a stamp of the
folders: each file's and link's path, type, size and mtime (stamper in
treememo.go). The walk that compares or hashes a folder stamps it as it
goes, before opening a file, so a folder seen for the first time is
walked once, as before; a later read walks it without opening a file, and
while the stamps match, the answer is reused. In foundSkills a skill held
by several agents is walked once per read, not once per pair.

What is never taken as unchanged:
- a folder that can't be walked, or a file in it that can't be read
  (compareTrees and sameFile now say whether they read everything): it is
  unknown, not the same, and compared again next time;
- a folder with a file written in the last 3s (a rewrite within a file
  system's time granularity can keep size and mtime);
- any change of a file's size or mtime, or a file added or removed.
A rewrite that keeps both size and mtime (cp -p of a same-size file) is
not seen, as with rsync's quick check. .git, .DS_Store and magpie's mark
aren't part of a stamp, as they aren't part of the compare. hashFiles'
hashes are byte-for-byte what they were (they are kept in library.json
and each copy's mark).

Measured on the Windows box (Windows 11 x64, test binary, 20 library
skills given as copies to 4 agents and 40 own skills in 3 agents, each
300 files of 8KB under node_modules), library.Read:
  before:  5.5-6.3s every read
  after:   5.0s the first read after start, then 2.0s
(Glance, the next commit, is 80ms.) The Mac was under load average ~118
from other work, so its timings weren't comparable.

Tests:
- TestPageReadDoesntReadUnchangedSkillsAgain: aged folders, the second
  read finds codex's copy the same with its files made unreadable; an
  edit afterwards is read again and found to differ.
- TestJustWrittenSkillIsReadAgain: a folder written a moment ago isn't
  taken from the memo.
- TestUnreadableSkillIsntRememberedAsDifferent (scripts/run.sh made
  unreadable; SKILL.md unreadable leaves the skill unlisted).
- TestEditedLibrarySkillIsHashedAgain: a library skill edited to the same
  size and aged an hour after a read: its copies are behind.
- TestHashUnchangedByTheMemo: hashFiles' value for files, a link,
  .DS_Store and .git; passes on the old code too.
Broken by hand, each goes red: stamp without mtime (PageRead,
EditedLibrarySkill), memo never hit (PageRead), unsure compares kept
(Unreadable), unsettled folders kept (JustWritten).

Run: go test -tags nogui ./internal/library ./internal/gui (macOS); the
library package's tests on the Windows box; gofmt; vet on darwin, linux
and windows.
2026-10-10 19:53:02 +08:00

118 lines
3.7 KiB
Go

package library
// Reading the Library page compares skill folders whole: an agent's own
// skill against the same name in another agent (foundSkills), and each
// agent's copy against the library's skill (behind). Each compare read
// every byte of both folders on every read of the page, so a few dozen
// skills with node_modules or templates in them, given to several agents,
// read hundreds of megabytes each time the page opened; on Windows, with
// every file read scanned, that is minutes (0day404, #541). What a compare
// or a hash found is kept here against what a walk of the folders sees
// without opening a file: each entry's place, size and time. While those
// are the same, the answer is too. A folder that couldn't be walked or
// read whole is unknown: it is read again next time, never taken as
// unchanged.
import (
"crypto/sha256"
"encoding/hex"
"fmt"
stdhash "hash"
"io/fs"
"path/filepath"
"sync"
"time"
)
// settleFor is how long ago the newest file of a folder must have been
// written for what was found of it to be kept: a file written again within
// the time a file system can tell apart could keep its time and size.
const settleFor = 3 * time.Second
// stamper sums what a walk sees of a folder's files and links without
// opening one: each one's place, type, size and time. The walk that reads
// a folder stamps it as it goes, before opening a file, so a file written
// while it is read has a stamp that says so next time.
type stamper struct {
h stdhash.Hash
newest time.Time
}
func newStamper() *stamper { return &stamper{h: sha256.New()} }
func (s *stamper) add(rel string, fi fs.FileInfo) {
fmt.Fprintf(s.h, "%s\x00%d\x00%d\x00%d\n", filepath.ToSlash(rel), fi.Mode().Type(), fi.Size(), fi.ModTime().UnixNano())
if fi.ModTime().After(s.newest) {
s.newest = fi.ModTime()
}
}
// done is the stamp, and whether nothing stamped was written in the last
// settleFor.
func (s *stamper) done() (stamp string, settled bool) {
return hex.EncodeToString(s.h.Sum(nil)), time.Since(s.newest) > settleFor
}
type hashMemo struct{ stamp, hash string }
type treeMemo struct {
a, b string
same bool
}
var memo = struct {
sync.Mutex
hashes map[string]hashMemo // dir and noFinder: the folder's hash
trees map[[2]string]treeMemo // two folders: whether they hold the same
}{hashes: map[string]hashMemo{}, trees: map[[2]string]treeMemo{}}
// rememberedHash is hashFiles(dir, noFinder): the hash found before, while
// a walk finds dir as it was then, else read. A folder hashed for the
// first time is walked once, as before the memo.
func rememberedHash(dir string, noFinder bool) string {
key := fmt.Sprintf("%t\x00%s", noFinder, dir)
memo.Lock()
m, hit := memo.hashes[key]
memo.Unlock()
if hit {
if _, stamp, _, ok := hashWalk(dir, noFinder, false); ok && stamp == m.stamp {
return m.hash
}
memo.Lock()
delete(memo.hashes, key)
memo.Unlock()
}
h, stamp, settled, ok := hashWalk(dir, noFinder, true)
if !ok {
return ""
}
if settled {
memo.Lock()
memo.hashes[key] = hashMemo{stamp: stamp, hash: h}
memo.Unlock()
}
return h
}
// rememberedSame is whether trees a and b hold the same, as found before
// while both are as they were then, else compare. Only an answer from
// reading both whole (sure) is kept.
func rememberedSame(a, b string, ta, tb tree, compare func() (same, sure bool)) bool {
key := [2]string{a, b}
memo.Lock()
m, hit := memo.trees[key]
memo.Unlock()
if hit && m.a == ta.stamp && m.b == tb.stamp {
return m.same
}
same, sure := compare()
memo.Lock()
if sure && ta.settled && tb.settled {
memo.trees[key] = treeMemo{a: ta.stamp, b: tb.stamp, same: same}
} else {
delete(memo.trees, key)
}
memo.Unlock()
return same
}