返回 DeepSeek-Reasonix
session_catalog_reconcile_lifetime_test.go
根目录 / desktop / session_catalog_reconcile_lifetime_test.go
1 package main
2
3 import (
4 "context"
5 "database/sql"
6 "path/filepath"
7 "sync"
8 "sync/atomic"
9 "testing"
10 "time"
11
12 "reasonix/internal/sessioncatalog"
13 )
14
15 func TestStopSessionCatalogJoinsReconcileQueuedBeforeDiscoveryStarts(t *testing.T) {
16 isolateDesktopUserDirs(t)
17 ctx, cancel := context.WithCancel(t.Context())
18 app := NewApp()
19 app.ctx = ctx
20 requested := make(chan struct{}, 1)
21 catalog, err := sessioncatalog.Open(ctx, sessioncatalog.Options{
22 InMemory: true, MetadataOnly: true, StartPaused: true,
23 OnDiscovery: func(event sessioncatalog.DiscoveryEvent) {
24 if event.Phase == "requested" {
25 requested <- struct{}{}
26 }
27 },
28 })
29 if err != nil {
30 t.Fatal(err)
31 }
32 app.sessionCatalog.Store(catalog)
33 var jobDone <-chan struct{}
34 t.Cleanup(func() {
35 cancel()
36 if !app.stopSessionCatalog(sessionCatalogTestDeadline) {
37 t.Error("catalog fixture did not close cleanly")
38 }
39 if jobDone != nil && !waitChannelBefore(jobDone, time.Now().Add(sessionCatalogTestDeadline)) {
40 t.Error("explicit reconcile outlived its fixture")
41 }
42 })
43
44 dir := t.TempDir()
45 if !app.requestSessionCatalogReconcile(dir) {
46 t.Fatal("explicit reconcile was not admitted")
47 }
48 app.catalogReconcileMu.Lock()
49 jobDone = app.catalogReconcileJobs[projectRootKey(dir)].done
50 app.catalogReconcileMu.Unlock()
51 // The worker is inside ScheduleReconcile, but paused discovery cannot settle
52 // its token. Stop must cancel and join the desktop job independently.
53 <-requested
54 if !app.stopSessionCatalog(time.Second) {
55 t.Fatal("catalog stop did not join its paused discovery waiter")
56 }
57 select {
58 case <-jobDone:
59 default:
60 t.Fatal("catalog stop returned before its reconcile goroutine exited")
61 }
62 }
63
64 func TestRetiredSessionCatalogReconcileCannotJoinReplacement(t *testing.T) {
65 isolateDesktopUserDirs(t)
66 ctx, cancel := context.WithCancel(t.Context())
67 app := NewApp()
68 app.ctx = ctx
69 var oldRequests atomic.Int32
70 openPaused := func(onDiscovery func(sessioncatalog.DiscoveryEvent)) *sessioncatalog.Catalog {
71 catalog, err := sessioncatalog.Open(ctx, sessioncatalog.Options{
72 InMemory: true, MetadataOnly: true, StartPaused: true, OnDiscovery: onDiscovery,
73 })
74 if err != nil {
75 t.Fatal(err)
76 }
77 return catalog
78 }
79 oldCatalog := openPaused(func(event sessioncatalog.DiscoveryEvent) {
80 if event.Phase == "requested" {
81 oldRequests.Add(1)
82 }
83 })
84 app.sessionCatalog.Store(oldCatalog)
85 entered := make(chan struct{}, 2)
86 oldRelease, newRelease := make(chan struct{}), make(chan struct{})
87 var oldOnce, newOnce sync.Once
88 var calls atomic.Int32
89 app.catalogReconcileHook = func(sessioncatalog.DirectoryTarget) {
90 call := calls.Add(1)
91 entered <- struct{}{}
92 if call == 1 {
93 <-oldRelease
94 } else {
95 <-newRelease
96 }
97 }
98 var jobs []<-chan struct{}
99 t.Cleanup(func() {
100 oldOnce.Do(func() { close(oldRelease) })
101 newOnce.Do(func() { close(newRelease) })
102 cancel()
103 if !app.stopSessionCatalog(sessionCatalogTestDeadline) {
104 t.Error("replacement catalog fixture did not close cleanly")
105 }
106 for _, done := range jobs {
107 if !waitChannelBefore(done, time.Now().Add(sessionCatalogTestDeadline)) {
108 t.Error("retired reconcile outlived its fixture")
109 }
110 }
111 })
112 dir := t.TempDir()
113 if !app.requestSessionCatalogReconcile(dir) {
114 t.Fatal("old reconcile was not admitted")
115 }
116 key := projectRootKey(dir)
117 app.catalogReconcileMu.Lock()
118 oldJob := app.catalogReconcileJobs[key]
119 app.catalogReconcileMu.Unlock()
120 jobs = append(jobs, oldJob.done)
121 <-entered
122 if app.stopSessionCatalog(25 * time.Millisecond) {
123 t.Fatal("stop joined the old job before its hook released")
124 }
125
126 // A timed-out rebuild may publish the next catalog while the old hook is
127 // still unwinding. The same directory must receive a distinct job owner.
128 app.sessionCatalog.Store(openPaused(nil))
129 if !app.requestSessionCatalogReconcile(dir) {
130 t.Fatal("replacement reconcile was not admitted")
131 }
132 app.catalogReconcileMu.Lock()
133 newJob := app.catalogReconcileJobs[key]
134 app.catalogReconcileMu.Unlock()
135 jobs = append(jobs, newJob.done)
136 if oldJob == newJob {
137 t.Fatal("replacement catalog inherited a retired reconcile job")
138 }
139 <-entered
140 oldOnce.Do(func() { close(oldRelease) })
141 if !waitChannelBefore(oldJob.done, time.Now().Add(time.Second)) {
142 t.Fatal("retired reconcile did not exit after its hook released")
143 }
144 app.catalogReconcileMu.Lock()
145 currentJob := app.catalogReconcileJobs[key]
146 app.catalogReconcileMu.Unlock()
147 if currentJob != newJob {
148 t.Fatal("retired reconcile removed the replacement job")
149 }
150 if oldRequests.Load() != 0 {
151 t.Fatal("retired reconcile scheduled discovery after cancellation")
152 }
153 newOnce.Do(func() { close(newRelease) })
154 if !app.stopSessionCatalog(time.Second) {
155 t.Fatal("replacement reconcile did not stop cleanly")
156 }
157 }
158
159 func TestInvalidatedSessionCatalogReleasesQueuedReconcileWithoutAppShutdown(t *testing.T) {
160 isolateDesktopUserDirs(t)
161 ctx, cancel := context.WithCancel(t.Context())
162 app := NewApp()
163 app.ctx = ctx
164 requested := make(chan struct{}, 1)
165 path := filepath.Join(t.TempDir(), "catalog.sqlite")
166 catalog, err := sessioncatalog.Open(ctx, sessioncatalog.Options{
167 Path: path, MetadataOnly: true, StartPaused: true,
168 OnDiscovery: func(event sessioncatalog.DiscoveryEvent) {
169 if event.Phase == "requested" {
170 requested <- struct{}{}
171 }
172 },
173 })
174 if err != nil {
175 t.Fatal(err)
176 }
177 app.sessionCatalog.Store(catalog)
178 var jobDone <-chan struct{}
179 t.Cleanup(func() {
180 cancel()
181 if !app.stopSessionCatalog(sessionCatalogTestDeadline) {
182 t.Error("invalidated catalog fixture did not close cleanly")
183 }
184 if jobDone != nil && !waitChannelBefore(jobDone, time.Now().Add(sessionCatalogTestDeadline)) {
185 t.Error("invalidated reconcile outlived its fixture")
186 }
187 })
188 dir := t.TempDir()
189 if !app.requestSessionCatalogReconcile(dir) {
190 t.Fatal("explicit reconcile was not admitted")
191 }
192 app.catalogReconcileMu.Lock()
193 jobDone = app.catalogReconcileJobs[projectRootKey(dir)].done
194 app.catalogReconcileMu.Unlock()
195 <-requested
196
197 // Corrupt this disposable generation's root page. A fresh public read lease
198 // must report corruption and revoke it while discovery is still paused.
199 db, err := sql.Open("sqlite", path)
200 if err != nil {
201 t.Fatal(err)
202 }
203 _, err = db.Exec(`PRAGMA writable_schema=ON; UPDATE sqlite_master SET rootpage=2147483647 WHERE type='table' AND name='catalog_state'; PRAGMA schema_version=999`)
204 closeErr := db.Close()
205 if err != nil || closeErr != nil {
206 t.Fatal(err, closeErr)
207 }
208 lease, err := catalog.OpenReadLease(ctx)
209 if lease != nil {
210 lease.Close()
211 }
212 if err == nil {
213 t.Fatal("corrupt root page remained readable")
214 }
215 select {
216 case <-catalog.Invalidated():
217 default:
218 t.Fatalf("public read did not invalidate the corrupt generation: %v", err)
219 }
220 if !waitChannelBefore(jobDone, time.Now().Add(time.Second)) {
221 t.Fatal("invalidated discovery kept the desktop job waiting for app shutdown")
222 }
223 if ctx.Err() != nil {
224 t.Fatal("reconcile completion depended on app shutdown")
225 }
226 }
227
227 lines GO