~james/core

core/spindle/engine/cache_prune_test.go -rw-r--r-- 7.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package engine

import (
	"context"
	"errors"
	"slices"
	"testing"
	"time"

	"tangled.org/core/spindle/db"
)

func TestPruneCachesExpiryPolicies(t *testing.T) {
	ctx := context.Background()
	now := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC)
	type spec struct {
		id    string
		state string
		age   time.Duration
	}
	tests := []struct {
		name        string
		retention   time.Duration
		pendingMax  time.Duration
		entries     []spec
		wantPruned  int
		wantSurvive []string
	}{
		{
			name:        "ready entries expire by last use",
			retention:   time.Hour,
			pendingMax:  15 * time.Minute,
			entries:     []spec{{"old", "ready", 2 * time.Hour}, {"fresh", "ready", 30 * time.Minute}},
			wantPruned:  1,
			wantSurvive: []string{"fresh"},
		},
		{
			name:        "zero retention keeps ready entries",
			retention:   0,
			pendingMax:  time.Hour,
			entries:     []spec{{"ready", "ready", 24 * time.Hour}, {"pending", "pending", 2 * time.Hour}},
			wantPruned:  1,
			wantSurvive: []string{"ready"},
		},
		{
			name:        "pending entries expire by age",
			retention:   time.Hour,
			pendingMax:  time.Hour,
			entries:     []spec{{"old", "pending", 2 * time.Hour}, {"fresh", "pending", 10 * time.Minute}},
			wantPruned:  1,
			wantSurvive: []string{"fresh"},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			d := newCacheTestDB(t)
			store := &fakeStorage{objects: map[string][]byte{}}
			keys := map[string]string{}
			for _, e := range tt.entries {
				entry := cacheTestEntry(e.id, "did:plc:repo", "microvm", "deps", "hash", e.state, now.Add(-e.age))
				insertCacheTestEntry(t, d, entry)
				store.objects[entry.StorageKey] = []byte(e.id)
				keys[e.id] = entry.StorageKey
			}

			pruned, err := PruneCaches(ctx, d, store, now, tt.retention, tt.pendingMax, 0, 10)
			if err != nil {
				t.Fatalf("PruneCaches: %v", err)
			}
			if pruned != tt.wantPruned {
				t.Fatalf("pruned %d entries, want %d", pruned, tt.wantPruned)
			}
			for _, e := range tt.entries {
				survives := slices.Contains(tt.wantSurvive, e.id)
				if store.has(keys[e.id]) != survives || cacheTestEntryExists(t, d, e.id) != survives {
					t.Fatalf("entry %q survived = %v, want %v", e.id, !survives, survives)
				}
			}
		})
	}
}

func TestPruneCachesSkipsEntryRefreshedAfterScan(t *testing.T) {
	ctx := context.Background()
	d := newCacheTestDB(t)
	now := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC)
	first := cacheTestEntry("first", "did:plc:repo", "microvm", "deps", "first", "ready", now.Add(-3*time.Hour))
	refreshed := cacheTestEntry("refreshed", "did:plc:repo", "microvm", "deps", "refreshed", "ready", now.Add(-2*time.Hour))
	insertCacheTestEntry(t, d, first)
	insertCacheTestEntry(t, d, refreshed)
	store := &fakeStorage{objects: map[string][]byte{
		first.StorageKey:     []byte("first"),
		refreshed.StorageKey: []byte("refreshed"),
	}}
	store.onDelete = func(key string) {
		if key != first.StorageKey {
			return
		}
		if err := d.TouchCacheEntry(ctx, refreshed.ID, now); err != nil {
			t.Fatalf("TouchCacheEntry: %v", err)
		}
	}

	pruned, err := PruneCaches(ctx, d, store, now, time.Hour, time.Hour, 0, 10)
	if err != nil {
		t.Fatalf("PruneCaches: %v", err)
	}
	if pruned != 1 {
		t.Fatalf("pruned %d entries, want 1", pruned)
	}
	if !store.has(refreshed.StorageKey) || !cacheTestEntryExists(t, d, refreshed.ID) {
		t.Fatal("entry refreshed after expiry scan was pruned")
	}
}

func TestPruneCachesDeleteFailureRemainsRetryable(t *testing.T) {
	for _, initialState := range []string{"ready", "deleting"} {
		t.Run(initialState, func(t *testing.T) {
			ctx := context.Background()
			d := newCacheTestDB(t)
			now := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC)
			entry := cacheTestEntry("retry", "did:plc:repo", "microvm", "deps", "hash", initialState, now.Add(-2*time.Hour))
			insertCacheTestEntry(t, d, entry)
			deleteErr := errors.New("delete failed")
			store := &fakeStorage{
				objects:   map[string][]byte{entry.StorageKey: []byte("archive")},
				deleteErr: deleteErr,
			}

			pruned, err := PruneCaches(ctx, d, store, now, time.Hour, time.Hour, 0, 10)
			if !errors.Is(err, deleteErr) {
				t.Fatalf("first PruneCaches error = %v, want %v", err, deleteErr)
			}
			if pruned != 0 {
				t.Fatalf("first prune count = %d, want 0", pruned)
			}
			state, _, _ := cacheTestEntryState(t, d, entry.ID)
			if state != initialState {
				t.Fatalf("state after delete failure = %q, want %q", state, initialState)
			}
			if !store.has(entry.StorageKey) {
				t.Fatal("failed delete removed object")
			}

			pruned, err = PruneCaches(ctx, d, store, now, time.Hour, time.Hour, 0, 10)
			if err != nil {
				t.Fatalf("retry PruneCaches: %v", err)
			}
			if pruned != 1 || store.has(entry.StorageKey) || cacheTestEntryExists(t, d, entry.ID) {
				t.Fatalf("retry result = pruned %d, object %v, metadata %v", pruned, store.has(entry.StorageKey), cacheTestEntryExists(t, d, entry.ID))
			}
		})
	}
}

func TestPruneCachesRetriesQueuedObjectDeletion(t *testing.T) {
	ctx := context.Background()
	d := newCacheTestDB(t)
	now := time.Now()
	key := "objects/did:web:example.com/orphan"
	if err := d.ApplyEventBatch(nil, func(tx *db.EventBatchTx) error {
		return tx.QueueCacheObjectDeletion(ctx, key, now)
	}); err != nil {
		t.Fatal(err)
	}
	deleteErr := errors.New("delete failed")
	store := &fakeStorage{
		objects:   map[string][]byte{key: []byte("archive")},
		deleteErr: deleteErr,
	}
	if _, err := PruneCaches(ctx, d, store, now, time.Hour, time.Hour, 0, 10); !errors.Is(err, deleteErr) {
		t.Fatalf("first prune error = %v, want %v", err, deleteErr)
	}
	pending, err := d.PendingCacheObjectDeletions(ctx, 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(pending) != 1 || pending[0] != key {
		t.Fatalf("pending object deletions = %v", pending)
	}
	pruned, err := PruneCaches(ctx, d, store, now, time.Hour, time.Hour, 0, 10)
	if err != nil {
		t.Fatal(err)
	}
	if pruned != 1 || store.has(key) {
		t.Fatalf("retry pruned %d, object remains %t", pruned, store.has(key))
	}
}

func TestPruneCachesEvictsLeastRecentlyUsedOverTotal(t *testing.T) {
	ctx := context.Background()
	d := newCacheTestDB(t)
	now := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC)
	store := &fakeStorage{objects: map[string][]byte{}}
	add := func(id, state string, age time.Duration, size, restores int64) {
		entry := cacheTestEntry(id, "did:plc:repo", "microvm", id, "hash", state, now.Add(-age))
		entry.SizeBytes, entry.RestoreCount = size, restores
		insertCacheTestEntry(t, d, entry)
		store.objects[entry.StorageKey] = []byte(id)
	}
	add("pinned", "ready", 4*time.Hour, 40, 1)
	add("oldest", "ready", 3*time.Hour, 40, 0)
	add("older", "ready", 2*time.Hour, 40, 0)
	add("newest", "ready", time.Hour, 40, 0)
	add("reserved", "pending", time.Minute, 1000, 0)

	pruned, err := PruneCaches(ctx, d, store, now, 0, 24*time.Hour, 90, 10)
	if err != nil {
		t.Fatalf("PruneCaches: %v", err)
	}
	if pruned != 2 {
		t.Fatalf("pruned %d entries, want 2", pruned)
	}
	for id, survives := range map[string]bool{"pinned": true, "oldest": false, "older": false, "newest": true, "reserved": true} {
		if store.has("objects/"+id) != survives || cacheTestEntryExists(t, d, id) != survives {
			t.Fatalf("entry %q survived = %v, want %v", id, !survives, survives)
		}
	}
}