sessions: a session resumed into copies isn't read whole again after a start (shangyuan0818 on X)

shangyuan0818 on X, on the latest Windows build: after using an agent,
Sessions took 18 s to load. They had ~100 Claude Code sessions of 30 to
100 MB and read Claude Code only, and guessed it was dedup, since
ccusage is slow on the same files.

Cause: older `claude --resume` wrote each resume as a whole copy of the
session under a new sessionId. ccFamily judges such a group by every
file's message uuids (ccUUIDsOf), and ccRest reads each copy for what
its keeper doesn't hold. Both were kept in memory only. cc-rest.json
kept the rests, but without the uuids they were read from (ids nil).
After a start, the first turn of the session the copies are kept in
changed the group's signature and its size, so every file of the chain
was read whole twice: gigabytes before Sessions showed. Codex is not
read with Claude-only reads (the cold load is the same with its folder
empty).

Fix: the uuids of each file of a group are kept on disk, one file each
in cc-uuids/ (named by a hash of the path), with the size, mtime, the
offset read to and a prefixHash of the bytes up to it. A start reads
them back and goes on from the offset only while the hash still
matches the file's start; otherwise the file is read from its start.
The rest ids are kept in cc-rest-ids.bin under the rest's key, so a
keeper that only grew leaves its copies unread after a start too.
Entries whose session file is gone are pruned once a start. Trash
drops an entry. Reset forgets the in-memory uuids, like a real start.
Not changed: a first start (no cache) still reads each copy three
times (parse, ccUUIDsOf, ccRest), filed as #7143.

Windows (xiaomi-gpu, Windows 11, CGO_ENABLED=0 builds, Claude-only
reads, sandbox HOME). The fixture is 5 resume chains of 20 files, 30 to
107 MB each, 6.9 GB. Time is for the page's three requests together.
                                     origin/main   this change
  cold, no cache                         20.2 s        17.6 s
  warm restart                            0.30 s        0.30 s
  restart after 1 keeper's turn       3.29/3.14 s   0.38/0.25 s
  1 keeper's turn while running           1.60 s        0.11 s
  restart after 5 keepers' turns          7.25 s        0.92 s
  5 keepers' turns while running          3.32 s        0.78 s
The profile of a restart after a turn on origin/main was ccFamily →
ccUUIDsOf (1.23 s) and ccCopyStates → ccRest (1.14 s) in scanThin.
The kept uuids take 2.4 MB for the fixture's 100 files.

Tests (internal/sessions/cc_copies_test.go):
- TestClaudeKeeperTurnAfterAStartReadsNoCopy: a turn, then Reset, reads
  no file from its start, and the turn is counted.
- TestClaudeKeeperTurnTheBranchHeldAfterAStart: a keeper that grows,
  after a start, with a message the branch held on its own counts it
  once.
- TestClaudeKeptUUIDsOfAFileWrittenOver: an entry whose file was
  written over doesn't stand.
- TestClaudeKeptUUIDsRoundTrip.

Run at this tree:
- go test ./... -count=1 -timeout 45m on mote: 102 packages ok, 2
  red, both filed: internal/cli's TestHealthcheckFindsTheRunningGateway
  WithoutMagpieAddr, TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr
  and TestUpdateFindsAMagpieThatWroteNoRecord (#6471, #6223: they ask
  whatever serves 127.0.0.1:3425 on mote), and internal/gateway's
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117, red on main).
- go test ./internal/sessions -race -count=1 -run TestClaude -timeout
  25m on mica: every new test passes; 2 reds, both data races filed and
  outside this change: TestClaudeCdKeptParseReadAgain (#6213, red the
  same at 0e3d09361 on mica) and the claude-desktop-3p subtest of
  TestClaudeTraceSubagentsShareSessionWithoutIDCollisions, failed by
  testenv.Zone's cleanup against provider's sweepStale timer (#4360).
  A first try at -count=3 hit go test's default 10m timeout mid-run
  (3 x ~240s under -race), not a hang.
- go vet ./internal/sessions on darwin, GOOS=linux and GOOS=windows
  (mote): clean. gofmt -l: clean.
- win-run go test ./internal/sessions: 4 reds, TestAgySessions,
  TestAgyRowOnly, TestAntigravityAppFolder and
  TestCCListingKeepsItsNames. The same 4 are red at origin/main
  0e3d09361 on the same box, filed as #6071.
- No GUI test reaches this: the GUI tests fake the API, and no asset
  changed.
Broken by hand:
- kept uuids not read back (ccUUIDKept ignored):
  TestClaudeKeeperTurnAfterAStartReadsNoCopy red, all three files read
  whole on each turn.
- rest ids not read back: that test red, the two copies read whole.
- rest ids read back as empty: TestClaudeKeeperTurnTheBranchHeldAfterAStart
  red, 90 tokens in where 80 are wanted.
Not tried: the reporter's own files, or a real Claude Code --resume
chain (the fixture is generated in that shape). Not tried on a slow
disk or with Defender scanning, which the reporter's 18 s may include.
This commit is contained in:
yetone
2026-11-19 09:10:33 +08:00
parent 0e3d093611
commit 14b6b95556
6 changed files with 548 additions and 10 deletions
+19 -7
View File
@@ -216,6 +216,8 @@ func ccFamily(files []file) (copies, branches map[string]string) {
}
}
ccFamiliesSave()
ccUUIDSave()
ccUUIDPrune()
// a file judged here that no longer starts like another lets its
// uuids go; another caller's files are left as they are
for _, o := range all {
@@ -255,6 +257,7 @@ var ccUUIDMemo = map[string]*ccUUIDs{}
type ccUUIDs struct {
size, mod, off int64
set uuidSet
hash digest // prefixHash of the file up to off
// forked is the session its messages say they were copied from
// (forkedFrom, which /branch writes on each), "" for none
forked string
@@ -276,6 +279,12 @@ var ccForked = []byte(`"forkedFrom":{`)
// read stopped while the file only grew.
func ccUUIDsOf(f file) uuidSet {
m := ccUUIDMemo[f.path]
if m == nil {
// what an earlier start read of it, read on from there
if m = ccUUIDKept(f); m != nil {
ccUUIDMemo[f.path] = m
}
}
if m == nil || f.size < m.size || f.size == m.size && f.mod.UnixNano() != m.mod {
m = &ccUUIDs{set: uuidSet{}}
ccUUIDMemo[f.path] = m
@@ -298,6 +307,8 @@ func ccUUIDsOf(f file) uuidSet {
})
if err == nil {
m.off = off
m.hash = prefixHash(f.path, off)
ccUUIDDirty[f.path] = true
}
m.size, m.mod = f.size, f.mod.UnixNano()
return m.set
@@ -341,10 +352,11 @@ type ccRestOf struct {
keeper string
ksize, kmod int64
st *state
// ids is the uuids of the messages st was read from, nil when not
// known (kept on disk): while the copy stays as it is and the keeper
// only grows, st stands as long as the keeper holds none of them
ids []string
// ids is the uuids of the messages st was read from (uuidKey), nil
// when not known: while the copy stays as it is and the keeper only
// grows, st stands as long as the keeper holds none of them. Kept on
// disk with st (cc-rest-ids.bin).
ids [][16]byte
}
// ccRest is the copy's file read for its messages the keeper's file
@@ -366,14 +378,14 @@ func ccRest(copyFile, keeper file) *state {
// session, is not read again on each turn
if m != nil && m.ids != nil && m.size == copyFile.size && m.mod == copyFile.mod.UnixNano() &&
m.keeper == keeper.path && keeper.size > m.ksize &&
!slices.ContainsFunc(m.ids, held.has) {
!slices.ContainsFunc(m.ids, func(k [16]byte) bool { _, ok := held[k]; return ok }) {
m.ksize, m.kmod = keeper.size, keeper.mod.UnixNano()
ccRestKept.dirty = true
return m.st
}
line := parserFor(copyFile.agent).line
s := &state{}
ids := []string{}
ids := [][16]byte{}
_, err := scanThin(copyFile.path, 0, nil, thinClaude, func(b []byte, _, _ int64) bool {
if !bytes.Contains(b, ccUser) && !bytes.Contains(b, ccAssistant) {
return true
@@ -382,7 +394,7 @@ func ccRest(copyFile, keeper file) *state {
if t := r[0].String(); t != "user" && t != "assistant" || r[1].Type != gjson.String || held.has(r[1].Str) {
return true
}
ids = append(ids, r[1].Str)
ids = append(ids, uuidKey(r[1].Str))
line(s, b, copyFile.main)
return true
})
+183
View File
@@ -2,6 +2,7 @@ package sessions
import (
"fmt"
"maps"
"os"
"path/filepath"
"slices"
@@ -741,3 +742,185 @@ func TestClaudeKeeperTurnTheBranchHeldIsCountedOnce(t *testing.T) {
t.Errorf("tokens in = %d (days), %d (sessions); want 80, the branch's reply counted once", days.Input, sessions.Input)
}
}
// A turn of the session the copies are kept in, made while magpie was
// not running, reads none of the copies again on the next start: the
// uuids of each file and what each copy holds on its own are kept on
// disk, and the keeper is read on from where it was read to. In memory
// only, each start after a turn read every file of the group whole: for
// a session resumed into ~100 copies of 30 to 100 MB (shangyuan0818, on
// X) gigabytes, and seconds before Sessions showed.
func TestClaudeKeeperTurnAfterAStartReadsNoCopy(t *testing.T) {
claude, _ := setup(t)
ccForkFixture(t, claude,
[2]string{"original.jsonl", ccOriginal},
[2]string{"original.jsonl", ccCopyIDs[0]},
[2]string{"fork-on.jsonl", ccForkOn})
if got := ccRows("claude"); !slices.Equal(got, []string{ccForkOn}) {
t.Fatalf("rows = %v, want the fork only", got)
}
before, _ := ccStatTokens(t)
proj := filepath.Join(claude, "projects", "-w-proj")
keeper := filepath.Join(proj, ccForkOn+".jsonl")
var hmu sync.Mutex
var whole []string // files read from their start
scanHook = func(p string, off int64) {
if off == 0 && strings.HasPrefix(p, proj) {
hmu.Lock()
whole = append(whole, filepath.Base(p))
hmu.Unlock()
}
}
t.Cleanup(func() { scanHook = nil })
for n := 1; n <= 2; n++ {
ccKeeperTurn(t, keeper, ccForkOn, n)
Reset() // a start: nothing read is in memory
hmu.Lock()
whole = nil
hmu.Unlock()
if got := ccRows("claude"); !slices.Equal(got, []string{ccForkOn}) {
t.Fatalf("turn %d: rows = %v, want the fork only", n, got)
}
days, _ := ccStatTokens(t)
if want := before.Input + n*1000; days.Input != want {
t.Errorf("turn %d: tokens in = %d, want %d", n, days.Input, want)
}
hmu.Lock()
got := slices.Clone(whole)
hmu.Unlock()
// the keeper's own parse reads its turn on; nothing reads a copy,
// or the keeper, from its start
if len(got) > 0 {
t.Errorf("turn %d, after a start, read files whole again: %v", n, got)
}
}
}
// ccKeeperTurn appends the nth turn, of 1000 tokens in, to the session
// file at p.
func ccKeeperTurn(t *testing.T, p, session string, n int) {
t.Helper()
id := fmt.Sprintf("0c0c0c0c-0000-4000-8000-%012d", n)
line := `{"parentUuid":null,"isSidechain":false,"message":{"id":"msg_turn_` + id + `","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"more"}],"stop_reason":"end_turn","usage":{"input_tokens":1000,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":5}},"type":"assistant","uuid":"` + id + `","timestamp":"` + time.Now().Add(-time.Duration(10-n)*time.Minute).UTC().Format(time.RFC3339Nano) + `","sessionId":"` + session + `","cwd":"/w/proj"}` + "\n"
f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteString(line); err != nil {
t.Fatal(err)
}
f.Close()
at := time.Now().Add(-time.Duration(10-n) * time.Minute)
if err := os.Chtimes(p, at, at); err != nil {
t.Fatal(err)
}
}
// The uuids kept of a file stand only while what they were read from is
// still its start: a file written over, longer than before, is read
// again from its start.
func TestClaudeKeptUUIDsOfAFileWrittenOver(t *testing.T) {
claude, _ := setup(t)
ccForkFixture(t, claude,
[2]string{"original.jsonl", ccOriginal},
[2]string{"original.jsonl", ccCopyIDs[0]},
[2]string{"fork-on.jsonl", ccForkOn})
ccRows("claude")
Reset()
p := filepath.Join(claude, "projects", "-w-proj", ccForkOn+".jsonl")
fi, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
f := file{path: p, size: fi.Size(), mod: modOf(fi.ModTime())}
mu.Lock()
kept := ccUUIDKept(f)
mu.Unlock()
if kept == nil || len(kept.set) == 0 {
t.Fatal("no uuids kept of the fork after a start")
}
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
// its first uuid changed, and a line more
i := strings.Index(string(b), `"uuid":"`) + len(`"uuid":"`)
b[i] ^= 1
if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil {
t.Fatal(err)
}
fi, err = os.Stat(p)
if err != nil {
t.Fatal(err)
}
f = file{path: p, size: fi.Size(), mod: modOf(fi.ModTime())}
mu.Lock()
kept = ccUUIDKept(f)
mu.Unlock()
if kept != nil {
t.Error("the uuids kept of a file written over still stand")
}
}
// When the file a branch is kept in grows, after a start, with a message
// the branch held on its own, that message is counted once still: what
// the branch held is kept with the uuids it was read from, and read
// again when the keeper holds one of them.
func TestClaudeKeeperTurnTheBranchHeldAfterAStart(t *testing.T) {
ccCompactedBranchFixture(t)
if days, _ := ccStatTokens(t); days.Input != 80 {
t.Fatalf("tokens in = %d, want 80", days.Input)
}
Reset()
claude := os.Getenv("CLAUDE_CONFIG_DIR")
proj := filepath.Join(claude, "projects", "-w-proj")
b, err := os.ReadFile(filepath.Join(proj, ccBranch+".jsonl"))
if err != nil {
t.Fatal(err)
}
var own string
for _, l := range strings.SplitAfter(string(b), "\n") {
if strings.Contains(l, `"type":"assistant"`) && strings.Contains(l, `"input_tokens"`) {
own = l
}
}
if own == "" {
t.Fatal("the branch has no reply")
}
p := filepath.Join(proj, ccCompacted+".jsonl")
fi, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
f.WriteString(strings.ReplaceAll(own, ccBranch, ccCompacted))
f.Close()
at := fi.ModTime().Add(time.Minute)
if err := os.Chtimes(p, at, at); err != nil {
t.Fatal(err)
}
Reset()
if days, sessions := ccStatTokens(t); days.Input != 80 || sessions.Input != 80 {
t.Errorf("tokens in = %d (days), %d (sessions); want 80, the branch's reply counted once", days.Input, sessions.Input)
}
}
// The kept uuids and rest ids read back as they were written.
func TestClaudeKeptUUIDsRoundTrip(t *testing.T) {
m := &ccUUIDs{size: 1 << 33, mod: -5, off: 77, forked: "s", set: uuidSet{}, hash: digest{1, 2}}
m.set.add("0c0c0c0c-0000-4000-8000-000000000001")
m.set.add("not-a-uuid")
path, got, err := decodeUUIDs(encodeUUIDs(`C:\x\y.jsonl`, m))
if err != nil || path != `C:\x\y.jsonl` || got.size != m.size || got.mod != m.mod || got.off != m.off ||
got.forked != m.forked || got.hash != m.hash || !maps.Equal(got.set, m.set) {
t.Fatalf("decoded %q %+v, %v; want %+v", path, got, err, m)
}
ids := map[string][][16]byte{"a\x00b": {uuidKey("x"), uuidKey("y")}, "c": {}}
back := decodeRestIDs(encodeRestIDs(ids))
if len(back) != 2 || len(back["c"]) != 0 || back["c"] == nil || !slices.Equal(back["a\x00b"], ids["a\x00b"]) {
t.Fatalf("rest ids = %v, want %v", back, ids)
}
}
+19 -2
View File
@@ -188,6 +188,11 @@ func ccFamiliesForget() {
ccFamilies.path, ccFamilies.groups, ccFamilies.dirty = "", nil, false
ccRestKept.path, ccRestKept.dirty = "", false
clear(ccRestMemo)
ccUUIDWait()
ccRestIDWrites.Wait()
clear(ccUUIDMemo)
clear(ccUUIDDirty)
ccUUIDPruned = ""
}
// What a copy or branch holds that the file it is kept in doesn't (ccRest)
@@ -225,6 +230,10 @@ func ccRestLoad() {
if !ok {
return
}
ids := map[string][][16]byte{}
if b, err := os.ReadFile(ccRestIDsPath()); err == nil {
ids = decodeRestIDs(b)
}
for k, st := range files {
f := strings.Split(k, "\x00")
if len(f) != 6 || st == nil {
@@ -240,7 +249,8 @@ func ccRestLoad() {
continue
}
if _, ok := ccRestMemo[f[0]]; !ok {
ccRestMemo[f[0]] = &ccRestOf{size: n[0], mod: n[1], keeper: f[1], ksize: n[2], kmod: n[3], st: st}
// ids known only when kept by the same key: nil is not known
ccRestMemo[f[0]] = &ccRestOf{size: n[0], mod: n[1], keeper: f[1], ksize: n[2], kmod: n[3], st: st, ids: ids[k]}
}
}
}
@@ -248,14 +258,21 @@ func ccRestLoad() {
// ccRestSave writes the rests when they changed. Encoded under mu, written
// behind it.
func ccRestSave() {
ccUUIDSave()
if !ccRestKept.dirty || ccRestKept.path == "" {
return
}
ccRestKept.dirty = false
files := make(map[string]*state, len(ccRestMemo))
ids := map[string][][16]byte{}
for p, m := range ccRestMemo {
files[ccRestKey(p, m)] = m.st
k := ccRestKey(p, m)
files[k] = m.st
if m.ids != nil {
ids[k] = m.ids
}
}
ccRestIDWrites.write(ccRestIDsPath(), encodeRestIDs(ids))
var b bytes.Buffer
if encodeCache(&b, cacheFile{Version: cacheVersion, Zone: zone(), Parsers: parseVersions, Files: files}) != nil {
return
+324
View File
@@ -0,0 +1,324 @@
package sessions
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"io"
"os"
"path/filepath"
"slices"
"strings"
"sync"
)
// The uuids read of each file of a group that starts alike (ccUUIDsOf),
// and of what a copy holds that its keeper doesn't (ccRestOf.ids), are
// kept on disk as well. In memory only, a start had none of them, so the
// first turn after it of a session resumed into copies read every file of
// the group whole: for a long session resumed many times (Claude Code's
// older --resume wrote each a whole copy, ~100 MB a file for the reporter
// on X) that was gigabytes and many seconds on each start after a turn.
// Kept, a file that grew is read on from where it was read to, as it is
// while magpie runs, as long as what was read is still the file's start
// (prefixHash).
// ccUUIDDir holds one file for each file whose uuids are kept, named by a
// hash of its path, so a turn writes the uuids of the file it grew only.
func ccUUIDDir() string { return filepath.Join(filepath.Dir(CachePath()), "cc-uuids") }
func ccUUIDFile(dir, path string) string {
h := sha256.Sum256([]byte(path))
return filepath.Join(dir, hex.EncodeToString(h[:12])+".bin")
}
const ccUUIDMagic = "ccu1"
// ccUUIDDirty is the files whose uuids changed since they were written.
// Under mu.
var ccUUIDDirty = map[string]bool{}
// ccUUIDWrites orders the writes of each kept file, by its path. Saved
// waits for them with or without mu, so the map has a lock of its own.
var ccUUIDWrites = struct {
sync.Mutex
m map[string]*keptWriter
}{m: map[string]*keptWriter{}}
func ccUUIDWriter(fp string) *keptWriter {
ccUUIDWrites.Lock()
defer ccUUIDWrites.Unlock()
w := ccUUIDWrites.m[fp]
if w == nil {
w = &keptWriter{}
ccUUIDWrites.m[fp] = w
}
return w
}
// ccUUIDWait waits for the uuid files being written.
func ccUUIDWait() {
ccUUIDWrites.Lock()
ws := make([]*keptWriter, 0, len(ccUUIDWrites.m))
for _, w := range ccUUIDWrites.m {
ws = append(ws, w)
}
ccUUIDWrites.Unlock()
for _, w := range ws {
w.Wait()
}
}
func encodeUUIDs(path string, m *ccUUIDs) []byte {
var b bytes.Buffer
b.WriteString(ccUUIDMagic)
var n [binary.MaxVarintLen64]byte
str := func(s string) {
b.Write(n[:binary.PutUvarint(n[:], uint64(len(s)))])
b.WriteString(s)
}
num := func(v int64) { b.Write(n[:binary.PutVarint(n[:], v)]) }
str(path)
num(m.size)
num(m.mod)
num(m.off)
b.Write(m.hash[:])
str(m.forked)
b.Write(n[:binary.PutUvarint(n[:], uint64(len(m.set)))])
keys := make([][16]byte, 0, len(m.set))
for k := range m.set {
keys = append(keys, k)
}
// in order, so the same set writes the same bytes
slices.SortFunc(keys, func(a, c [16]byte) int { return bytes.Compare(a[:], c[:]) })
for _, k := range keys {
b.Write(k[:])
}
return b.Bytes()
}
var errUUIDFile = errors.New("not a kept uuid file")
func decodeUUIDs(b []byte) (string, *ccUUIDs, error) {
if !bytes.HasPrefix(b, []byte(ccUUIDMagic)) {
return "", nil, errUUIDFile
}
b = b[len(ccUUIDMagic):]
bad := false
uv := func() uint64 {
v, k := binary.Uvarint(b)
if k <= 0 {
bad = true
return 0
}
b = b[k:]
return v
}
num := func() int64 {
v, k := binary.Varint(b)
if k <= 0 {
bad = true
return 0
}
b = b[k:]
return v
}
str := func() string {
l := uv()
if bad || l > uint64(len(b)) {
bad = true
return ""
}
s := string(b[:l])
b = b[l:]
return s
}
path := str()
m := &ccUUIDs{}
m.size, m.mod, m.off = num(), num(), num()
if bad || len(b) < len(m.hash) {
return "", nil, errUUIDFile
}
copy(m.hash[:], b)
b = b[len(m.hash):]
m.forked = str()
count := uv()
if bad || count*16 != uint64(len(b)) {
return "", nil, errUUIDFile
}
m.set = make(uuidSet, count)
for i := uint64(0); i < count; i++ {
var k [16]byte
copy(k[:], b[i*16:])
m.set[k] = struct{}{}
}
return path, m, nil
}
// ccUUIDKept is f's uuids as kept on disk, when what they were read from
// is still f's start; nil otherwise, and f is read from its start. Under
// mu.
func ccUUIDKept(f file) *ccUUIDs {
b, err := os.ReadFile(ccUUIDFile(ccUUIDDir(), f.path))
if err != nil {
return nil
}
path, m, err := decodeUUIDs(b)
if err != nil || path != f.path || f.size < m.size || f.size == m.size && f.mod.UnixNano() != m.mod ||
m.off > f.size || m.hash == (digest{}) || prefixHash(f.path, m.off) != m.hash {
return nil
}
return m
}
// ccUUIDSave writes the uuids that changed. Encoded under mu, written
// behind it.
func ccUUIDSave() {
if len(ccUUIDDirty) == 0 {
return
}
dir := ccUUIDDir()
for p := range ccUUIDDirty {
m := ccUUIDMemo[p]
if m == nil || m.hash == (digest{}) {
continue
}
fp := ccUUIDFile(dir, p)
ccUUIDWriter(fp).write(fp, encodeUUIDs(p, m))
}
clear(ccUUIDDirty)
}
// ccUUIDDrop lets the kept uuids of the file at path go, as when it is
// moved to the trash. Under mu.
func ccUUIDDrop(path string) {
delete(ccUUIDMemo, path)
delete(ccUUIDDirty, path)
fp := ccUUIDFile(ccUUIDDir(), path)
ccUUIDWriter(fp).Wait()
os.Remove(fp)
}
// ccUUIDPruned is the folder of kept uuids last pruned: once a start.
// Under mu.
var ccUUIDPruned string
// ccUUIDPrune removes, once a start, the kept uuids of files that are
// gone. Of the files still there, those in no group that starts alike
// any more stay: a caller judges some of the files only (ccFamily), so
// what it left out says nothing of them.
func ccUUIDPrune() {
dir := ccUUIDDir()
if ccUUIDPruned == dir {
return
}
ccUUIDPruned = dir
ents, err := os.ReadDir(dir)
if err != nil {
return
}
for _, e := range ents {
n := e.Name()
if !strings.HasSuffix(n, ".bin") {
continue
}
fp := filepath.Join(dir, n)
path, ok := ccUUIDPathOf(fp)
if ok {
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
continue
}
} else if path == "?" {
continue // not read: unknown, not gone
}
ccUUIDWriter(fp).Wait()
os.Remove(fp)
}
}
// ccUUIDPathOf is the path of the file whose uuids fp keeps, read from
// its head; ok false with "?" when fp can't be read, with "" when it is
// not a kept uuid file.
func ccUUIDPathOf(fp string) (string, bool) {
f, err := os.Open(fp)
if err != nil {
return "?", false
}
defer f.Close()
b := make([]byte, 4096+len(ccUUIDMagic)+binary.MaxVarintLen64)
k, _ := io.ReadFull(f, b)
b = b[:k]
if !bytes.HasPrefix(b, []byte(ccUUIDMagic)) {
return "", false
}
b = b[len(ccUUIDMagic):]
l, n := binary.Uvarint(b)
if n <= 0 {
return "", false
}
if l > uint64(len(b)-n) {
return "?", false // a path longer than the head read
}
return string(b[n : n+int(l)]), true
}
// What a copy holds that its keeper doesn't is kept with the uuids of the
// messages it was read from (ccRestOf.ids) in cc-rest-ids.bin, beside the
// rests (cc-rest.json), by the same key: without them, a keeper that grew
// after a start had every copy of it read whole again.
func ccRestIDsPath() string { return filepath.Join(filepath.Dir(CachePath()), "cc-rest-ids.bin") }
const ccRestIDsMagic = "ccr1"
var ccRestIDWrites keptWriter
func encodeRestIDs(ids map[string][][16]byte) []byte {
var b bytes.Buffer
b.WriteString(ccRestIDsMagic)
var n [binary.MaxVarintLen64]byte
keys := make([]string, 0, len(ids))
for k := range ids {
keys = append(keys, k)
}
slices.Sort(keys)
for _, k := range keys {
b.Write(n[:binary.PutUvarint(n[:], uint64(len(k)))])
b.WriteString(k)
b.Write(n[:binary.PutUvarint(n[:], uint64(len(ids[k])))])
for _, id := range ids[k] {
b.Write(id[:])
}
}
return b.Bytes()
}
func decodeRestIDs(b []byte) map[string][][16]byte {
if !bytes.HasPrefix(b, []byte(ccRestIDsMagic)) {
return nil
}
b = b[len(ccRestIDsMagic):]
out := map[string][][16]byte{}
for len(b) > 0 {
l, k := binary.Uvarint(b)
if k <= 0 || l > uint64(len(b)-k) {
return nil
}
key := string(b[k : k+int(l)])
b = b[k+int(l):]
c, k := binary.Uvarint(b)
if k <= 0 || c > uint64(len(b)-k)/16 {
return nil
}
b = b[k:]
ids := make([][16]byte, c)
for i := range ids {
copy(ids[i][:], b[i*16:])
}
b = b[c*16:]
out[key] = ids
}
return out
}
+1 -1
View File
@@ -570,7 +570,7 @@ func Delete(agent, id string) (Trashed, error) {
}
for _, f := range fs {
delete(cache, f.path)
delete(ccUUIDMemo, f.path)
ccUUIDDrop(f.path)
}
saveCache()
wslForget(fs)
+2
View File
@@ -1656,6 +1656,8 @@ func saved() {
saving.Unlock()
ccFamilyWrites.Wait()
ccRestWrites.Wait()
ccRestIDWrites.Wait()
ccUUIDWait()
flushCallPack()
}