diff --git a/internal/db/db.go b/internal/db/db.go index 87152b4..ca945ad 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -952,6 +952,20 @@ func (k *KnoxDB) MarkSessionIndexed(sessionID string) error { return err } +// DerivedStateCounts returns the number of observations in the append-only log +// and the number of materialized entries. Callers use it to decide whether the +// derived cache needs rebuilding (e.g. a replica that starts with a log but no +// entries because it never saw a push or pull since the cache was wiped). +func (k *KnoxDB) DerivedStateCounts() (observations, entries int, err error) { + if err = k.db.QueryRow("SELECT COUNT(*) FROM observations").Scan(&observations); err != nil { + return 0, 0, fmt.Errorf("count observations: %w", err) + } + if err = k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&entries); err != nil { + return 0, 0, fmt.Errorf("count entries: %w", err) + } + return observations, entries, nil +} + func (k *KnoxDB) Stats() (map[string]any, error) { stats := make(map[string]any) diff --git a/internal/watch/watch.go b/internal/watch/watch.go index fe684d4..7743c01 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -209,6 +209,19 @@ func (w *Watcher) Start() error { log.Printf("[knox] obsidian vault: %s", w.vault) } + // A node that starts with a populated log but an empty entries cache — a + // freshly deployed replica, or any node whose derived state was wiped — has + // nothing to trigger a reconcile, so build it once at startup. Reconcile is + // only cheap-ish, not free, hence the guard. + if obs, entries, err := w.knoxDB.DerivedStateCounts(); err == nil && obs > 0 && entries == 0 { + log.Printf("[knox] derived state empty with %d observations: rebuilding", obs) + if created, linked, err := Reconcile(w.knoxDB); err != nil { + log.Printf("[knox] startup reconcile: %v", err) + } else { + log.Printf("[knox] startup reconcile done: %d created, %d linked", created, linked) + } + } + debounce := newFileDebouncer() browserTicker := time.NewTicker(browserInterval) giteaTicker := time.NewTicker(10 * time.Minute)