fix: rebuild derived state on startup when the log has data but entries do not (#8)
A replica that restarts with a populated observation log and an empty entries cache had no trigger to reconcile: pushes and pulls only fire on *new* rows, and the node is already in sync. It now rebuilds once at startup.
This commit is contained in:
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user