返回 DeepSeek-Reasonix
reconcile.go
根目录 / internal / sessioncatalog / reconcile.go
1 package sessioncatalog
2
3 import (
4 "context"
5 "crypto/sha256"
6 "database/sql"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "net/url"
11 "os"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "sync"
16 "time"
17
18 "reasonix/internal/agent"
19 "reasonix/internal/projectiondb"
20 "reasonix/internal/sqliteuri"
21 )
22
23 func (c *Catalog) ReconcileDirectory(ctx context.Context, target DirectoryTarget) error {
24 if c == nil {
25 return nil
26 }
27 return c.reconcileDirectory(ctx, target, c.mutationSeq.Add(1))
28 }
29
30 func (c *Catalog) reconcileDirectory(ctx context.Context, target DirectoryTarget, sequence uint64) error {
31 if c == nil || c.db == nil {
32 return nil
33 }
34 if c.opts.MetadataOnly {
35 return c.reconcileMetadata(ctx, target, sequence)
36 }
37 return c.reconcileDirectoryFull(ctx, target, sequence)
38 }
39
40 func (c *Catalog) reconcileDirectoryFull(ctx context.Context, target DirectoryTarget, sequence uint64) error {
41 target.Path = cleanCatalogAccessPath(target.Path)
42 if target.Path == "" {
43 return nil
44 }
45 lock := c.directoryLock(target.Path)
46 lock.Lock()
47 defer lock.Unlock()
48 target.Scope, target.WorkspaceRoot = normalizeScope(target.Scope, target.WorkspaceRoot)
49 signature, err := directorySignature(target.Path)
50 if err != nil {
51 c.failDirectoryScan(ctx, target.Path, err)
52 return err
53 }
54 if unchanged, err := c.directoryScanCanSkip(ctx, target, signature); err != nil {
55 return err
56 } else if unchanged {
57 return nil
58 }
59 now := c.opts.Now().UnixMilli()
60 generation, _, err := c.beginDirectoryScan(ctx, target, signature, now)
61 if err != nil {
62 return err
63 }
64 content := newStrictRecoveryContentCache(c.testSessionContentLoadHook)
65 ordered, err := listSessionOrderWithContent(target.Path, content)
66 if err != nil {
67 c.failDirectoryScan(ctx, target.Path, err)
68 return err
69 }
70 records := make([]SessionRecord, 0, len(ordered))
71 for start := 0; start < len(ordered); start += 64 {
72 if err := ctx.Err(); err != nil {
73 c.failDirectoryScan(context.Background(), target.Path, err)
74 return err
75 }
76 end := min(start+64, len(ordered))
77 for _, info := range ordered[start:end] {
78 records = append(records, recordFromOrder(target, info))
79 }
80 runtime.Gosched()
81 }
82 records = c.filterPathMutations(records, sequence)
83 records, err = c.preserveKnownSourceStates(ctx, target.Path, records)
84 if err != nil {
85 c.failDirectoryScan(context.Background(), target.Path, err)
86 return err
87 }
88 for i := range records {
89 records[i] = classifyRecoveryLineageWithContent(normalizeSessionRecord(records[i]), content)
90 }
91 records = promoteCanonicalLeavesWithContent(records, content)
92 if err := c.commitDirectoryProjection(ctx, target, signature, generation, now, records); err != nil {
93 c.failDirectoryScan(context.Background(), target.Path, err)
94 return err
95 }
96 c.markDirectoryVerifiedIfStable(ctx, target, signature)
97 for _, record := range records {
98 if record.TurnsState == TurnsUnknown {
99 c.enqueueRepair(record.Path)
100 }
101 }
102 return nil
103 }
104
105 func directorySignature(dir string) (string, error) {
106 // os.ReadDir of a plain file returns the file itself on Windows but
107 // ENOTDIR on POSIX; stat first so both platforms reject non-directories.
108 info, err := os.Stat(dir)
109 if err != nil {
110 if os.IsNotExist(err) {
111 return "missing", nil
112 }
113 return "", err
114 }
115 if !info.IsDir() {
116 return "", fmt.Errorf("not a directory: %s", dir)
117 }
118 entries, err := os.ReadDir(dir)
119 if err != nil {
120 return "", err
121 }
122 hash := sha256.New()
123 for _, entry := range entries {
124 name := entry.Name()
125 if entry.IsDir() || (!strings.HasSuffix(name, ".jsonl") && !strings.HasSuffix(name, ".meta")) {
126 continue
127 }
128 info, err := entry.Info()
129 if err != nil {
130 return "", err
131 }
132 _, _ = fmt.Fprintf(hash, "%s\x00%d\x00%d\x00%d\n", name, info.Size(), info.ModTime().UnixNano(), info.Mode())
133 }
134 return hex.EncodeToString(hash.Sum(nil)), nil
135 }
136
137 func (c *Catalog) directoryLock(path string) *sync.Mutex {
138 path = c.pathKey(path)
139 c.directoryLocksMu.Lock()
140 defer c.directoryLocksMu.Unlock()
141 lock := c.directoryLocks[path]
142 if lock == nil {
143 lock = &sync.Mutex{}
144 c.directoryLocks[path] = lock
145 }
146 return lock
147 }
148
149 // IndexSessionPath indexes one session without walking its directory.
150 func (c *Catalog) IndexSessionPath(ctx context.Context, target DirectoryTarget, path string) error {
151 if c == nil {
152 return nil
153 }
154 return c.indexSessionPath(ctx, target, path, c.mutationSeq.Add(1))
155 }
156
157 func (c *Catalog) indexSessionPath(ctx context.Context, target DirectoryTarget, path string, sequence uint64) error {
158 if c.opts.MetadataOnly {
159 return c.indexMetadataPath(ctx, target, path, sequence)
160 }
161 path = cleanCatalogAccessPath(path)
162 if path == "" {
163 return nil
164 }
165 target.Path = cleanCatalogAccessPath(target.Path)
166 if target.Path == "" {
167 target.Path = filepath.Dir(path)
168 }
169 // Hold the directory lock so a concurrent scan cannot mark this row missing.
170 lock := c.directoryLock(target.Path)
171 lock.Lock()
172 defer lock.Unlock()
173 info, err := os.Stat(path)
174 if err != nil {
175 if os.IsNotExist(err) {
176 return nil
177 }
178 return err
179 }
180 meta, ok, err := agent.LoadBranchMeta(path)
181 if err != nil {
182 return err
183 }
184 order := agent.SessionOrderInfo{
185 Path: path,
186 CreatedAt: info.ModTime(),
187 LastActivityAt: info.ModTime(),
188 ModTime: info.ModTime(),
189 Scope: target.Scope,
190 WorkspaceRoot: target.WorkspaceRoot,
191 }
192 if ok {
193 order.CreatedAt = meta.CreatedAt
194 order.LastActivityAt = meta.UpdatedAt
195 order.ModTime = meta.UpdatedAt
196 order.Scope = meta.DefaultScope()
197 order.WorkspaceRoot = meta.WorkspaceRoot
198 order.TopicID = meta.TopicID
199 order.TopicTitle = meta.TopicTitle
200 order.CustomTitle = meta.CustomTitle
201 order.Recovered = meta.Recovered
202 order.RecoveryReason = meta.RecoveryReason
203 order.RecoveryDigest = meta.RecoveryDigest
204 order.ParentID = meta.ParentID
205 order.RecoveryPreferred = agent.RecoveryPreferenceCurrent(path, meta)
206 order.Turns = meta.Turns
207 order.Preview = meta.Preview
208 order.SchemaVersion = meta.SchemaVersion
209 order.Revision = meta.Revision
210 order.ContentDigest = meta.ContentDigest
211 order.ListingRevision = meta.ListingRevision
212 order.ListingContentDigest = meta.ListingContentDigest
213 order.HeadID, order.HeadCount, order.LogSchema = meta.HeadID, meta.HeadCount, meta.LogSchema
214 }
215 if order.CreatedAt.IsZero() {
216 order.CreatedAt = info.ModTime()
217 }
218 if order.LastActivityAt.IsZero() {
219 order.LastActivityAt = info.ModTime()
220 }
221 record := recordFromOrder(target, order)
222 record.enqueueSequence = sequence
223 projectionDirty, err := c.upsertExactPathSession(ctx, record)
224 if err != nil {
225 return err
226 }
227 if projectionDirty {
228 // Queue after the exact source row is durable. The non-blocking worker
229 // will acquire this directory lock after IndexSessionPath returns and
230 // publish the full sibling-aware projection in one transaction.
231 c.RequestReconcile(target)
232 }
233 if record.TurnsState == TurnsUnknown {
234 c.enqueueRepair(record.Path)
235 }
236 return nil
237 }
238
239 func recordFromOrder(target DirectoryTarget, info agent.SessionOrderInfo) SessionRecord {
240 scope, root := normalizeScope(info.Scope, info.WorkspaceRoot)
241 if info.TopicID == "" {
242 scope, root = target.Scope, target.WorkspaceRoot
243 }
244 // A stale projection is never certified, but its last-known preview and
245 // count stay as display hints so the row does not vanish during repair.
246 turnsState := TurnsValid
247 if !info.ListingProjectionFresh() {
248 turnsState = TurnsUnknown
249 }
250 heads := projectSessionHeads(info)
251 contentFingerprint := sessionContentFingerprint(info.Path) + heads.fingerprint
252 metaFingerprint := fileFingerprint(agent.BranchMetaPath(info.Path))
253 if heads.stale {
254 turnsState = TurnsUnknown
255 }
256 createdAt := unixMilli(info.CreatedAt)
257 lastActivityAt := unixMilli(info.LastActivityAt)
258 // File mtime fills a missing clock. Do not raise a known sidecar UpdatedAt:
259 // repair and other metadata writes bump mtime without new user turns.
260 if st, err := os.Stat(info.Path); err == nil {
261 fileMS := st.ModTime().UnixMilli()
262 if createdAt <= 0 {
263 createdAt = fileMS
264 }
265 if lastActivityAt <= 0 {
266 lastActivityAt = fileMS
267 }
268 }
269 return normalizeSessionRecord(SessionRecord{
270 Path: info.Path,
271 Directory: target.Path,
272 Scope: scope,
273 WorkspaceRoot: root,
274 TopicID: info.TopicID,
275 TopicTitle: info.TopicTitle,
276 CustomTitle: info.CustomTitle,
277 CreatedAt: createdAt,
278 LastActivityAt: lastActivityAt,
279 Preview: info.Preview,
280 Turns: info.Turns,
281 TurnsState: turnsState,
282 Recovered: info.Recovered,
283 RecoveryReason: info.RecoveryReason,
284 RecoveryDigest: info.RecoveryDigest,
285 ParentID: info.ParentID,
286 RecoveryPreferred: info.RecoveryPreferred,
287 RecoveryCopy: false,
288 LogFormat: heads.logFormat,
289 HeadCount: heads.headCount,
290 SelectedHeadID: heads.selected,
291 heads: heads.heads,
292 ContentFingerprint: contentFingerprint,
293 MetaFingerprint: metaFingerprint,
294 Health: HealthOK,
295 })
296 }
297
298 func unixMilli(value time.Time) int64 {
299 if value.IsZero() {
300 return 0
301 }
302 return value.UnixMilli()
303 }
304
305 func fileFingerprint(path string) string {
306 info, err := os.Stat(path)
307 if err != nil {
308 return ""
309 }
310 return fmt.Sprintf("%d:%d", info.Size(), info.ModTime().UnixNano())
311 }
312
313 func sessionContentFingerprint(path string) string {
314 return fileFingerprint(path) + "|" + fileFingerprint(agent.SessionEventLogPath(path))
315 }
316
317 // beginDirectoryScan starts or resumes a directory scan. When the previous
318 // scan for the same signature was interrupted mid-way, the stored scan_cursor
319 // is returned so ReconcileDirectory continues instead of restarting from 0.
320 func (c *Catalog) beginDirectoryScan(ctx context.Context, target DirectoryTarget, signature string, now int64) (int64, string, error) {
321 c.mutationMu.Lock()
322 defer c.mutationMu.Unlock()
323 tx, err := c.db.BeginTx(ctx, nil)
324 if err != nil {
325 return 0, "", err
326 }
327 var previousSig, previousState, previousCursor string
328 var previousGeneration int64
329 pathKey := c.pathKey(target.Path)
330 if err := c.removeRemappedDirectoryIdentity(ctx, tx, target.Path, pathKey); err != nil {
331 _ = tx.Rollback()
332 return 0, "", err
333 }
334 err = tx.QueryRowContext(ctx, `SELECT signature,state,scan_cursor,scan_generation FROM catalog_directories WHERE path_key=?`,
335 pathKey).Scan(&previousSig, &previousState, &previousCursor, &previousGeneration)
336 resume := err == nil && previousState == "scanning" && previousSig == signature && strings.TrimSpace(previousCursor) != ""
337 if errors.Is(err, sql.ErrNoRows) {
338 err = nil
339 }
340 if err != nil {
341 _ = tx.Rollback()
342 return 0, "", err
343 }
344 if resume {
345 if _, err := tx.ExecContext(ctx, `UPDATE catalog_directories SET path=?,scope=?,workspace_root=?,state='scanning',error='',signature=? WHERE path_key=?`,
346 target.Path, target.Scope, target.WorkspaceRoot, signature, pathKey); err != nil {
347 _ = tx.Rollback()
348 return 0, "", err
349 }
350 if previousGeneration == 0 {
351 previousGeneration = 1
352 }
353 return previousGeneration, previousCursor, tx.Commit()
354 }
355 if _, err := tx.ExecContext(ctx, `INSERT INTO catalog_directories(path,path_key,scope,workspace_root,state,error,signature)
356 VALUES(?,?,?,?,'scanning','',?) ON CONFLICT(path_key) DO UPDATE SET
357 path=excluded.path,scope=excluded.scope,workspace_root=excluded.workspace_root,state='scanning',error='',
358 signature=excluded.signature,scan_generation=catalog_directories.scan_generation+1,scan_cursor='',indexed=0`,
359 target.Path, pathKey, target.Scope, target.WorkspaceRoot, signature); err != nil {
360 _ = tx.Rollback()
361 return 0, "", err
362 }
363 var generation int64
364 if err := tx.QueryRowContext(ctx, `SELECT scan_generation FROM catalog_directories WHERE path_key=?`, pathKey).Scan(&generation); err != nil {
365 _ = tx.Rollback()
366 return 0, "", err
367 }
368 if generation == 0 {
369 generation = 1
370 if _, err := tx.ExecContext(ctx, `UPDATE catalog_directories SET scan_generation=1 WHERE path_key=?`, pathKey); err != nil {
371 _ = tx.Rollback()
372 return 0, "", err
373 }
374 }
375 return generation, "", tx.Commit()
376 }
377
378 // commitDirectoryProjection publishes a complete sibling-aware directory
379 // snapshot. Parsing and lineage classification happen before this function;
380 // readers therefore observe either the previous committed projection or every
381 // row, tombstone, missing marker, topic aggregate, and readiness update from
382 // this transaction together.
383 func (c *Catalog) commitDirectoryProjection(ctx context.Context, target DirectoryTarget, signature string, generation, now int64, records []SessionRecord) error {
384 c.mutationMu.Lock()
385 tx, err := c.db.BeginTx(ctx, nil)
386 if err != nil {
387 c.mutationMu.Unlock()
388 return err
389 }
390 rollback := func(commitErr error) error {
391 _ = tx.Rollback()
392 c.mutationMu.Unlock()
393 return commitErr
394 }
395 stmt, err := tx.PrepareContext(ctx, sessionInsertSQL+directoryProjectionUpdateSQL)
396 if err != nil {
397 return rollback(err)
398 }
399 affected := map[TopicKey]struct{}{}
400 directoryKey := c.pathKey(target.Path)
401 for start := 0; start < len(records); start += 64 {
402 if err := ctx.Err(); err != nil {
403 _ = stmt.Close()
404 return rollback(err)
405 }
406 end := min(start+64, len(records))
407 for _, record := range records[start:end] {
408 pathKey := c.pathKey(record.Path)
409 remapped, err := removeRemappedSessionIdentity(ctx, tx, record.Path, pathKey)
410 if err != nil {
411 _ = stmt.Close()
412 return rollback(err)
413 }
414 for _, key := range remapped {
415 affected[key] = struct{}{}
416 }
417 var previous TopicKey
418 if err := tx.QueryRowContext(ctx, `SELECT scope,workspace_root,workspace_root_key,topic_id FROM catalog_sessions WHERE path_key=?`, pathKey).
419 Scan(&previous.Scope, &previous.WorkspaceRoot, &previous.workspaceKey, &previous.TopicID); err == nil && previous.TopicID != "" {
420 affected[previous] = struct{}{}
421 } else if err != nil && !errors.Is(err, sql.ErrNoRows) {
422 _ = stmt.Close()
423 return rollback(err)
424 }
425 if err := c.writeDirectoryRow(ctx, tx, stmt, record, pathKey, directoryKey, generation); err != nil {
426 _ = stmt.Close()
427 return rollback(err)
428 }
429 if record.TopicID != "" {
430 affected[TopicKey{Scope: record.Scope, WorkspaceRoot: record.WorkspaceRoot,
431 workspaceKey: c.workspaceRootKey(record.Scope, record.WorkspaceRoot), TopicID: record.TopicID}] = struct{}{}
432 }
433 if err := c.updateFoldedTopicTombstones(ctx, tx, previous, record, now); err != nil {
434 _ = stmt.Close()
435 return rollback(err)
436 }
437 }
438 if c.testReconcileBatchHook != nil {
439 c.testReconcileBatchHook(end)
440 }
441 runtime.Gosched()
442 }
443 if err := stmt.Close(); err != nil {
444 return rollback(err)
445 }
446
447 rows, err := tx.QueryContext(ctx, `SELECT scope,workspace_root,workspace_root_key,topic_id FROM catalog_sessions
448 WHERE directory_key=? AND seen_generation<? AND topic_id<>''`, directoryKey, generation)
449 if err != nil {
450 return rollback(err)
451 }
452 for rows.Next() {
453 var key TopicKey
454 if err := rows.Scan(&key.Scope, &key.WorkspaceRoot, &key.workspaceKey, &key.TopicID); err != nil {
455 _ = rows.Close()
456 return rollback(err)
457 }
458 affected[key] = struct{}{}
459 }
460 if err := rows.Close(); err != nil {
461 return rollback(err)
462 }
463 if _, err := tx.ExecContext(ctx, `UPDATE catalog_sessions SET
464 missing_since=CASE WHEN missing_since=0 THEN ? ELSE missing_since END,
465 health='missing'
466 WHERE directory_key=? AND seen_generation<?`, now, directoryKey, generation); err != nil {
467 return rollback(err)
468 }
469 cutoff := now - c.opts.MissingGrace.Milliseconds()
470 if _, err := tx.ExecContext(ctx, `DELETE FROM catalog_sessions
471 WHERE directory_key=? AND seen_generation<? AND missing_since>0 AND missing_since<=?`, directoryKey, generation, cutoff); err != nil {
472 return rollback(err)
473 }
474 for key := range affected {
475 if err := c.recomputeTopic(ctx, tx, key); err != nil {
476 return rollback(err)
477 }
478 }
479 if _, err := tx.ExecContext(ctx, `UPDATE catalog_directories SET state='ready',error='',signature=?,
480 scan_cursor='',indexed=?,total=?,completed_at=? WHERE path_key=?`, signature, len(records), len(records), now, directoryKey); err != nil {
481 return rollback(err)
482 }
483 revision, err := bumpRevision(ctx, tx)
484 if err != nil {
485 return rollback(err)
486 }
487 if err := tx.Commit(); err != nil {
488 c.mutationMu.Unlock()
489 return err
490 }
491 c.mutationMu.Unlock()
492
493 c.publishRevision(revision, []string{target.WorkspaceRoot}, "reconcile_complete")
494 c.refreshCounts(ctx)
495 c.statusMu.Lock()
496 c.status.State = StateReady
497 c.status.LastError = ""
498 c.statusMu.Unlock()
499 return nil
500 }
501
502 func (c *Catalog) finishDirectoryScan(ctx context.Context, target DirectoryTarget, signature string, generation, now int64, total int) error {
503 c.mutationMu.Lock()
504 defer c.mutationMu.Unlock()
505 tx, err := c.db.BeginTx(ctx, nil)
506 if err != nil {
507 return err
508 }
509 directoryKey := c.pathKey(target.Path)
510 rows, err := tx.QueryContext(ctx, `SELECT scope,workspace_root,workspace_root_key,topic_id FROM catalog_sessions
511 WHERE directory_key=? AND seen_generation<? AND topic_id<>''`, directoryKey, generation)
512 if err != nil {
513 _ = tx.Rollback()
514 return err
515 }
516 affected := map[TopicKey]struct{}{}
517 for rows.Next() {
518 var key TopicKey
519 if err := rows.Scan(&key.Scope, &key.WorkspaceRoot, &key.workspaceKey, &key.TopicID); err != nil {
520 _ = rows.Close()
521 _ = tx.Rollback()
522 return err
523 }
524 affected[key] = struct{}{}
525 }
526 if err := rows.Close(); err != nil {
527 _ = tx.Rollback()
528 return err
529 }
530 if _, err := tx.ExecContext(ctx, `UPDATE catalog_sessions SET
531 missing_since=CASE WHEN missing_since=0 THEN ? ELSE missing_since END,
532 health='missing'
533 WHERE directory_key=? AND seen_generation<?`, now, directoryKey, generation); err != nil {
534 _ = tx.Rollback()
535 return err
536 }
537 cutoff := now - c.opts.MissingGrace.Milliseconds()
538 if _, err := tx.ExecContext(ctx, `DELETE FROM catalog_sessions
539 WHERE directory_key=? AND seen_generation<? AND missing_since>0 AND missing_since<=?`, directoryKey, generation, cutoff); err != nil {
540 _ = tx.Rollback()
541 return err
542 }
543 for key := range affected {
544 if err := c.recomputeTopic(ctx, tx, key); err != nil {
545 _ = tx.Rollback()
546 return err
547 }
548 }
549 if _, err := tx.ExecContext(ctx, `UPDATE catalog_directories SET state='ready',error='',signature=?,
550 scan_cursor='',indexed=?,total=?,completed_at=? WHERE path_key=?`, signature, total, total, now, directoryKey); err != nil {
551 _ = tx.Rollback()
552 return err
553 }
554 revision, err := bumpRevision(ctx, tx)
555 if err != nil {
556 _ = tx.Rollback()
557 return err
558 }
559 if err := tx.Commit(); err != nil {
560 return err
561 }
562 c.publishRevision(revision, []string{target.WorkspaceRoot}, "reconcile_complete")
563 c.refreshCounts(ctx)
564 c.statusMu.Lock()
565 c.status.State = StateReady
566 c.status.LastError = ""
567 c.statusMu.Unlock()
568 return nil
569 }
570
571 // Rebuild replaces only the disposable catalog. Authoritative sessions and
572 // sidecars are never changed or removed by this operation. The live database
573 // stays in place until a fully-populated replacement is validated and swapped.
574 func Rebuild(ctx context.Context, path string, targets []DirectoryTarget) (Status, error) {
575 return RebuildWithRevisionFloor(ctx, path, targets, 0)
576 }
577
578 // RebuildWithRevisionFloor preserves the caller's revision epoch while
579 // atomically replacing the disposable projection. Desktop clients retain
580 // revision fences across the rebuild, so a replacement must never publish a
581 // lower revision than the catalog they already rendered.
582 func RebuildWithRevisionFloor(ctx context.Context, path string, targets []DirectoryTarget, revisionFloor uint64) (Status, error) {
583 targets = UniqueDirectoryTargets(targets)
584 if strings.TrimSpace(path) == "" {
585 path = DefaultPath()
586 }
587 if strings.TrimSpace(path) == "" {
588 catalog, err := Open(ctx, Options{InMemory: true, DisableRepair: true})
589 if err != nil {
590 return Status{}, err
591 }
592 if err := setCatalogRevisionFloor(ctx, catalog.db, revisionFloor); err != nil {
593 closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
594 _ = catalog.Close(closeCtx)
595 cancel()
596 return Status{}, err
597 }
598 catalog.rememberRevision(revisionFloor)
599 for _, target := range targets {
600 if err := catalog.ReconcileDirectory(ctx, target); err != nil {
601 closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
602 _ = catalog.Close(closeCtx)
603 cancel()
604 return catalog.Status(), err
605 }
606 }
607 status := catalog.Status()
608 closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
609 _ = catalog.Close(closeCtx)
610 cancel()
611 return status, nil
612 }
613 err := projectiondb.Rebuild(ctx, projectiondb.OpenOptions{
614 Path: path,
615 MemoryName: "session-catalog-rebuild",
616 Migrations: sessionMigrations(),
617 RetainBackup: true,
618 }, func(ctx context.Context, db *sql.DB) error {
619 if err := setCatalogRevisionFloor(ctx, db, revisionFloor); err != nil {
620 return err
621 }
622 // Populate through a catalog that owns this temporary database handle
623 // without starting background repair workers.
624 temp := &Catalog{
625 db: db,
626 opts: Options{Path: path, DisableRepair: true, Now: time.Now, MissingGrace: defaultMissingGrace},
627 pathIdentity: PathIdentityKey,
628 writeQueued: map[string]SessionRecord{},
629 directoryLocks: map[string]*sync.Mutex{},
630 stop: make(chan struct{}),
631 status: Status{State: StateReady, Mode: ModeDisk, Path: path, Revision: revisionFloor},
632 }
633 temp.revision.Store(revisionFloor)
634 temp.workerCtx, temp.workerCancel = context.WithCancel(ctx)
635 defer temp.workerCancel()
636 for _, target := range targets {
637 if err := temp.ReconcileDirectory(ctx, target); err != nil {
638 return err
639 }
640 }
641 return nil
642 })
643 if err != nil {
644 return Status{}, err
645 }
646 // Open the published replacement briefly for a status snapshot, then close.
647 catalog, err := Open(ctx, Options{Path: path, DisableRepair: true})
648 if err != nil {
649 return Status{State: StateReady, Mode: ModeDisk, Path: path, Revision: revisionFloor}, nil
650 }
651 status := catalog.Status()
652 closeCtx, cancel := context.WithTimeout(context.Background(), time.Second)
653 _ = catalog.Close(closeCtx)
654 cancel()
655 return status, nil
656 }
657
658 func setCatalogRevisionFloor(ctx context.Context, db *sql.DB, revisionFloor uint64) error {
659 if db == nil || revisionFloor == 0 {
660 return nil
661 }
662 _, err := db.ExecContext(ctx, `UPDATE catalog_state SET revision=? WHERE id=1 AND revision<?`, revisionFloor, revisionFloor)
663 return err
664 }
665
666 // Inspect is read-only. It never migrates, repairs, quarantines, or rewrites a
667 // catalog, making it suitable for `reasonix doctor sessions`.
668 func Inspect(ctx context.Context, path string) (Status, error) {
669 if strings.TrimSpace(path) == "" {
670 path = DefaultPath()
671 }
672 status := Status{State: StateDegraded, Mode: ModeDisk, Path: path}
673 if strings.TrimSpace(path) == "" {
674 status.LastError = "catalog path unavailable"
675 return status, nil
676 }
677 inspection := projectiondb.Inspect(ctx, path)
678 if err := ctx.Err(); err != nil {
679 return status, err
680 }
681 if inspection.Error != "" && !inspection.Exists {
682 status.LastError = inspection.Error
683 return status, nil
684 }
685 if !inspection.Exists {
686 status.LastError = "catalog does not exist"
687 return status, nil
688 }
689 if inspection.Integrity != "" && inspection.Integrity != "ok" {
690 status.LastError = inspection.Integrity
691 return status, nil
692 }
693 if inspection.Error != "" {
694 status.LastError = inspection.Error
695 return status, nil
696 }
697 dsn, err := sqliteuri.Disk(path, url.Values{
698 "mode": {"ro"},
699 "_pragma": {"busy_timeout(150)"},
700 })
701 if err != nil {
702 status.LastError = "build read-only database URI: " + err.Error()
703 return status, nil
704 }
705 db, err := sql.Open("sqlite", dsn)
706 if err != nil {
707 status.LastError = "open read-only database: " + err.Error()
708 return status, nil
709 }
710 defer db.Close()
711 result := status
712 fail := func(stage string, err error) (Status, error) {
713 if ctxErr := ctx.Err(); ctxErr != nil {
714 return status, ctxErr
715 }
716 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
717 return status, err
718 }
719 status.LastError = stage + ": " + err.Error()
720 return status, nil
721 }
722 queries := []struct {
723 stage string
724 query string
725 dest any
726 }{
727 {"read catalog revision", `SELECT revision FROM catalog_state WHERE id=1`, &result.Revision},
728 {"count indexed sessions", `SELECT COUNT(*) FROM catalog_sessions`, &result.Indexed},
729 {"count pending repairs", `SELECT COUNT(*) FROM catalog_sessions WHERE turns_state='unknown'`, &result.RepairPending},
730 {"count active repairs", `SELECT COUNT(*) FROM catalog_sessions WHERE turns_state='unknown' AND repair_state IN ('pending','active')`, &result.RepairActive},
731 {"count deferred repairs", `SELECT COUNT(*) FROM catalog_sessions WHERE turns_state='unknown' AND repair_state='deferred'`, &result.RepairDeferred},
732 {"count blocked repairs", `SELECT COUNT(*) FROM catalog_sessions WHERE turns_state='unknown' AND repair_state='blocked'`, &result.RepairBlocked},
733 {"read next repair time", `SELECT COALESCE(MIN(repair_retry_at),0) FROM catalog_sessions WHERE turns_state='unknown' AND repair_state='deferred'`, &result.NextRepairAt},
734 {"count physical sessions", `SELECT COUNT(*) FROM catalog_sessions WHERE missing_since=0`, &result.PhysicalSessions},
735 {"count logical sessions", `SELECT COUNT(*) FROM catalog_topics`, &result.LogicalSessions},
736 {"count recovery groups", `SELECT COUNT(DISTINCT recovery_group_id) FROM catalog_sessions WHERE recovered=1 AND recovery_group_id<>'' AND missing_since=0`, &result.RecoveryGroups},
737 {"count recovery branches", `SELECT COUNT(*) FROM catalog_sessions WHERE recovered=1 AND missing_since=0`, &result.RecoveryBranches},
738 {"count diverged recoveries", `SELECT COUNT(*) FROM catalog_sessions WHERE recovered=1 AND recovery_role='diverged' AND missing_since=0`, &result.RecoveryDiverged},
739 {"count cleanup eligible recoveries", `SELECT COUNT(*) FROM catalog_sessions WHERE recovered=1 AND recovery_role='covered_copy' AND missing_since=0`, &result.CleanupEligible},
740 }
741 for _, query := range queries {
742 if err := db.QueryRowContext(ctx, query.query).Scan(query.dest); err != nil {
743 return fail(query.stage, err)
744 }
745 }
746 rows, err := db.QueryContext(ctx, `SELECT repair_error_kind,COUNT(*) FROM catalog_sessions
747 WHERE turns_state='unknown' AND repair_error_kind<>'' GROUP BY repair_error_kind`)
748 if err != nil {
749 return fail("count repair error kinds", err)
750 }
751 result.RepairErrorKinds = map[string]int64{}
752 for rows.Next() {
753 var kind string
754 var count int64
755 if err := rows.Scan(&kind, &count); err != nil {
756 _ = rows.Close()
757 return fail("scan repair error kinds", err)
758 }
759 result.RepairErrorKinds[kind] = count
760 }
761 if err := rows.Err(); err != nil {
762 _ = rows.Close()
763 return fail("iterate repair error kinds", err)
764 }
765 if err := rows.Close(); err != nil {
766 return fail("close repair error kinds", err)
767 }
768 result.State = StateReady
769 result.LastError = ""
770 return result, nil
771 }
772
772 lines GO