Files
knox/internal/db/db_test.go
T
david 0b8ac34aee chore: checkpoint uncommitted work before session store fix
Pre-existing work-in-progress in the tree: karakeep, snippets,
skills-health and redaction ingesters, the opencode.db session sweep,
gossip and metrics changes. Checkpointed as-is so the adapter fix in the
next commit stays reviewable on its own.
2026-11-01 13:48:09 -08:00

651 lines
19 KiB
Go

package db
import (
"fmt"
"path/filepath"
"sync"
"testing"
"time"
)
func newTestDB(t *testing.T) *KnoxDB {
t.Helper()
k, err := Open(filepath.Join(t.TempDir(), "knox.db"))
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { k.Close() })
return k
}
func obs(fp, title, summary string) ObservationRecord {
return ObservationRecord{
Fingerprint: fp, SourceID: "test", Title: title, Summary: summary,
Confidence: 0.5, IngesterVersion: "test/v1",
}
}
// Multi-word queries must match terms spread across fields (AND), not require
// the literal contiguous phrase.
func TestSearchMultiTerm(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "Home Assistant", "automation for the doorbell")); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp2", "Unrelated", "gardening notes")); err != nil {
t.Fatal(err)
}
got, err := k.Search("home assistant automation", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("expected only fp1, got %+v", got)
}
if got, _ := k.Search("home gardening", 10); len(got) != 0 {
t.Fatalf("expected no cross-row match, got %+v", got)
}
}
// Re-reporting an unchanged observation is a no-op: no new row, ref_count stays 1.
func TestRecordObservationIdempotent(t *testing.T) {
k := newTestDB(t)
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); !isNew {
t.Fatal("first insert should be new")
}
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); isNew {
t.Fatal("second identical insert should be a no-op")
}
var ref, rows int
if err := k.db.QueryRow("SELECT ref_count FROM entries WHERE fingerprint='fp1'").Scan(&ref); err != nil {
t.Fatal(err)
}
if err := k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&rows); err != nil {
t.Fatal(err)
}
if ref != 1 || rows != 1 {
t.Fatalf("ref_count=%d observations=%d, want 1/1", ref, rows)
}
}
// A non-empty ContentHash dedups on content, ignoring extent changes.
func TestRecordObservationContentHash(t *testing.T) {
k := newTestDB(t)
rows := func() int {
var n int
k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&n)
return n
}
a := obs("fp1", "Log x", "levels: E1 W0")
a.ContentHash = "deadbeef"
a.LineEnd = 100
if _, _, err := k.RecordObservation(a); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after first: rows=%d, want 1", rows())
}
// Same content hash, grown extent, different summary — must be a no-op.
b := obs("fp1", "Log x", "levels: E1 W0 (1000 lines)")
b.ContentHash = "deadbeef"
b.LineEnd = 2000
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after same-hash: rows=%d, want 1 (no-op)", rows())
}
// Different content hash — must append.
c := obs("fp1", "Log x", "levels: E2 W0")
c.ContentHash = "cafef00d"
c.LineEnd = 2000
if _, _, err := k.RecordObservation(c); err != nil {
t.Fatal(err)
}
if rows() != 2 {
t.Fatalf("after changed-hash: rows=%d, want 2", rows())
}
}
// UpsertSession must not inflate agent_count across repeated calls.
func TestUpsertSessionIdempotent(t *testing.T) {
k := newTestDB(t)
for i := 0; i < 3; i++ {
if err := k.UpsertSession("ses_1", "proj", "Title", "active"); err != nil {
t.Fatal(err)
}
}
var ac int
if err := k.db.QueryRow("SELECT agent_count FROM sessions WHERE session_id='ses_1'").Scan(&ac); err != nil {
t.Fatal(err)
}
if ac != 1 {
t.Fatalf("agent_count=%d, want 1", ac)
}
}
// Content (the uncapped body) is searchable even when absent from title/summary.
func TestSearchContentField(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "Title A", "short summary only")
r.Content = "the zanzibar protocol handshake details"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
got, err := k.Search("zanzibar", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("content search failed: %+v", got)
}
}
// Threads sharing observations are suggested for merge; merging moves links and
// resolves the source.
func TestMergeThreads(t *testing.T) {
k := newTestDB(t)
var ids []int64
for i := 0; i < 3; i++ {
o := obs(fmt.Sprintf("fp%d", i), fmt.Sprintf("t%d", i), "s")
o.SourceID = "gitea" // merge signals use work sources
oid, _, _ := k.RecordObservation(o)
ids = append(ids, oid)
}
a, _ := k.CreateThread("A", "", "medium", "[]", "{}")
b, _ := k.CreateThread("B", "", "medium", "[]", "{}")
for _, oid := range ids {
k.LinkObservationToThread(a, oid, "")
k.LinkObservationToThread(b, oid, "")
}
sug, err := k.MergeSuggestions(3, 0.3)
if err != nil {
t.Fatal(err)
}
if len(sug) != 1 || sug[0].Shared != 3 {
t.Fatalf("expected one suggestion with shared=3, got %+v", sug)
}
if err := k.MergeThreads(a, b); err != nil {
t.Fatal(err)
}
if tb, _ := k.GetThread(b); tb.Status != "resolved" {
t.Fatalf("merged-from thread status=%q, want resolved", tb.Status)
}
var n int
k.db.QueryRow("SELECT COUNT(*) FROM thread_observations WHERE thread_id=?", a).Scan(&n)
if n != 3 {
t.Fatalf("into thread has %d links, want 3", n)
}
}
// SetThreadSummary clears the resummary-due flag; CurrentFocus tracks recent link counts.
func TestThreadSummaryAndFocus(t *testing.T) {
k := newTestDB(t)
o := obs("fp1", "focus topic", "s")
o.SourceID = "gitea" // CurrentFocus counts work sources only
oid, _, _ := k.RecordObservation(o)
a, _ := k.CreateThread("focus topic", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oid, "")
if err := k.SetThreadSummary(a, "current state of work"); err != nil {
t.Fatal(err)
}
as, _ := k.GroomThreads(30)
for _, x := range as {
if x.ID == a {
if x.Summary != "current state of work" {
t.Fatalf("summary not stored: %q", x.Summary)
}
if x.ResummaryDue {
t.Fatal("freshly summarized thread should not be due")
}
}
}
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != a || recent < 1 {
t.Fatalf("CurrentFocus = (%d,%d,%v), want thread %d", id, recent, err, a)
}
}
// A retained thread is never denied nor resolved by the denylist pass.
func TestThreadRetained(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
id, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(id, bid, "")
if err := k.SetThreadRetained(id, true); err != nil {
t.Fatal(err)
}
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
for _, a := range as {
if a.ID != id {
continue
}
if !a.Retained {
t.Fatal("thread not reported retained")
}
if a.Denied || a.Verdict == "deny" {
t.Fatalf("retained thread still denied (verdict=%q)", a.Verdict)
}
}
if _, closed, _ := k.DenyThreadNoise(false); len(closed) != 0 {
t.Fatalf("retained thread was resolved: %v", closed)
}
}
// Status is derived: active while recently active, stalled once quiet, and
// resolved only when explicitly closed.
func TestThreadEffectiveStatus(t *testing.T) {
k := newTestDB(t)
recent := obs("fpA", "active thread", "s")
recent.CreatedAt = time.Now().UTC().Format(time.RFC3339)
oa, _, _ := k.RecordObservation(recent)
a, _ := k.CreateThread("active thread", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oa, "")
old := obs("fpB", "old thread", "s")
old.CreatedAt = "2020-01-01T00:00:00Z"
ob, _, _ := k.RecordObservation(old)
b, _ := k.CreateThread("old thread", "", "high", "[]", "{}")
k.LinkObservationToThread(b, ob, "")
c, _ := k.CreateThread("empty thread", "", "high", "[]", "{}")
statusOf := func(id int64, filter string) string {
ts, _ := k.ListThreads(filter)
for _, x := range ts {
if x.ID == id {
return x.Status
}
}
return ""
}
if statusOf(a, "all") != "active" {
t.Fatalf("recent thread should be active")
}
if statusOf(b, "all") != "stalled" {
t.Fatalf("old thread should be stalled")
}
// A brand-new thread with no observations yet is active (falls back to its
// created_at), not immediately stalled.
if statusOf(c, "all") != "active" {
t.Fatalf("new empty thread should be active, got %q", statusOf(c, "all"))
}
if statusOf(b, "active") != "" {
t.Fatalf("stalled thread must not match active filter")
}
if statusOf(b, "stalled") != "stalled" {
t.Fatalf("stalled filter must return stalled thread")
}
// Explicit resolution wins and is sticky.
if err := k.CloseThread(a); err != nil {
t.Fatal(err)
}
if statusOf(a, "all") != "resolved" || statusOf(a, "resolved") != "resolved" {
t.Fatalf("closed thread should be resolved")
}
}
// Rebuild must take the latest observation's content, not an arbitrary row.
func TestRebuildPicksLatestContent(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "t", "s")); err != nil {
t.Fatal(err)
}
b := obs("fp1", "t", "s")
b.Content = "full body text"
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if _, _, err := k.RebuildEntriesFromObservations(); err != nil {
t.Fatal(err)
}
var content string
if err := k.db.QueryRow("SELECT content FROM entries WHERE fingerprint='fp1'").Scan(&content); err != nil {
t.Fatal(err)
}
if content != "full body text" {
t.Fatalf("entry content=%q, want latest observation's", content)
}
}
// CurrentFocus ignores passive browsing: a browser-heavy thread must not win
// over a thread with fewer but work-source observations.
func TestCurrentFocusIgnoresBrowser(t *testing.T) {
k := newTestDB(t)
bt, _ := k.CreateThread("dashboard", "", "medium", "[]", "{}")
for i := 0; i < 5; i++ {
b := obs(fmt.Sprintf("b%d", i), "Uptime Kuma", "https://uptime.example/")
b.SourceID = "browser-history"
b.SourcePath = fmt.Sprintf("https://uptime.example/%d", i)
oid, _, _ := k.RecordObservation(b)
k.LinkObservationToThread(bt, oid, "")
}
wt, _ := k.CreateThread("zigbee stack", "", "medium", "[]", "{}")
w := obs("w1", "zigbee stack work", "mosquitto")
w.SourceID = "gitea"
w.SourcePath = "david/x"
oid, _, _ := k.RecordObservation(w)
k.LinkObservationToThread(wt, oid, "")
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != wt || recent != 1 {
t.Fatalf("CurrentFocus=(%d,%d,%v), want work thread %d", id, recent, err, wt)
}
}
// Newly-arrived observations link to existing threads once (bounded by watermark).
func TestAutoLinkNewObservations(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("zigbee docker stack", "", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp1", "zigbee docker stack notes", "mosquitto compose")); err != nil {
t.Fatal(err)
}
n, err := k.AutoLinkNewObservations()
if err != nil {
t.Fatal(err)
}
if n < 1 {
t.Fatalf("expected >=1 link, got %d", n)
}
// Second pass: nothing new (watermark advanced).
if n2, _ := k.AutoLinkNewObservations(); n2 != 0 {
t.Fatalf("second pass linked %d, want 0", n2)
}
}
// GroomThreads flags a denylisted, non-work thread as "deny" and a
// work-anchored thread as not-denied, and offers a profile-derived title.
func TestGroomThreads(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
denyID, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(denyID, bid, "")
w := obs("fpw", "nr-flow-validator", "rego validation work")
w.SourceID = "gitea"
w.SourcePath = "klubhaus/nr-flow-validator"
wid, _, _ := k.RecordObservation(w)
workID, _ := k.CreateThread("nr-flow-validator Rego validation", "real work", "high", "[]", "{}")
k.LinkObservationToThread(workID, wid, "")
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
byID := map[int64]ThreadAssessment{}
for _, a := range as {
byID[a.ID] = a
}
if byID[denyID].Verdict != "deny" {
t.Errorf("deny thread verdict=%q, want deny", byID[denyID].Verdict)
}
if !byID[denyID].Denied || byID[denyID].DenyMatch == "" {
t.Errorf("deny thread should be flagged with a match")
}
if byID[workID].Verdict == "deny" {
t.Errorf("work thread must not be denied")
}
if !byID[workID].WorkAnchored {
t.Errorf("work thread should be work-anchored")
}
// Human titles get no suggestion; auto-style/denied titles do.
if byID[workID].SuggestedTitle != "" {
t.Errorf("human-titled thread should have no suggested title, got %q", byID[workID].SuggestedTitle)
}
if byID[denyID].SuggestedTitle == "" {
t.Errorf("auto-style/denied thread should have a suggested title")
}
}
// DenyThreadNoise drops denylisted browser links and resolves a denylisted
// thread that has no work-source anchor.
func TestDenyThreadNoise(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/cards")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/cards"
obsID, _, err := k.RecordObservation(b)
if err != nil {
t.Fatal(err)
}
id, err := k.CreateThread("privacy / virtual / card", "virtual cards", "medium", "[]", "{}")
if err != nil {
t.Fatal(err)
}
if err := k.LinkObservationToThread(id, obsID, ""); err != nil {
t.Fatal(err)
}
removed, closed, err := k.DenyThreadNoise(false)
if err != nil {
t.Fatal(err)
}
if removed < 1 {
t.Fatalf("removed=%d, want >=1", removed)
}
found := false
for _, c := range closed {
if c == id {
found = true
}
}
if !found {
t.Fatalf("thread #%d not closed; closed=%v", id, closed)
}
t2, _ := k.GetThread(id)
if t2.Status != "resolved" {
t.Fatalf("status=%q, want resolved", t2.Status)
}
}
// A one-character typo should still match via the vocabulary fuzzy fallback.
func TestSearchFuzzyTypo(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "amazon web services", "cloud hosting")
r.Content = "amazon web services documentation and pricing"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
for _, typo := range []string{"amazn", "servies"} {
got, err := k.Search(typo, 10)
if err != nil {
t.Fatal(err)
}
if len(got) == 0 {
t.Fatalf("typo %q returned no results", typo)
}
}
}
// "all"/empty must list every thread; the literal 'all' previously matched none.
func TestListThreadsAll(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("T", "motivation", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
for _, status := range []string{"", "all", "ALL"} {
got, err := k.ListThreads(status)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("ListThreads(%q)=%d threads, want 1", status, len(got))
}
}
}
func tmpDB(t *testing.T) *KnoxDB {
t.Helper()
kdb, err := Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { kdb.Close() })
return kdb
}
func record(t *testing.T, k *KnoxDB, fp, title string) {
t.Helper()
_, _, err := k.RecordObservation(ObservationRecord{
Fingerprint: fp,
SourceID: "test",
SourcePath: fp,
Project: "itest",
ContentType: "test",
Title: title,
Summary: "summary",
CreatedAt: "2026-08-29T00:00:00Z",
LineEnd: 0,
Confidence: 0.9,
IngesterVersion: "test/v1",
})
if err != nil {
t.Errorf("record %s: %v", fp, err)
}
}
func obsCount(t *testing.T, k *KnoxDB) int {
t.Helper()
stats, err := k.Stats()
if err != nil {
t.Fatalf("stats: %v", err)
}
n, _ := stats["total_observations"].(int)
return n
}
// TestRecordObservationConcurrentDedup: N goroutines ingesting identical
// content must produce exactly one observation row. This exercises the
// check-then-insert dedup under the writeMu + BEGIN IMMEDIATE serialization.
func TestRecordObservationConcurrentDedup(t *testing.T) {
k := tmpDB(t)
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
record(t, k, "fp:concurrent", "same title")
}()
}
wg.Wait()
if n := obsCount(t, k); n != 1 {
t.Fatalf("expected exactly 1 observation after concurrent identical ingests, got %d", n)
}
}
// TestRecordObservationDistinctFingerprints: different content must never be
// deduped away (the constraint is per-fingerprint signature, not global).
func TestRecordObservationDistinctFingerprints(t *testing.T) {
k := tmpDB(t)
record(t, k, "fp:a", "alpha")
record(t, k, "fp:b", "beta")
record(t, k, "fp:a", "alpha changed")
if n := obsCount(t, k); n != 3 {
t.Fatalf("expected 3 observations, got %d", n)
}
}
// TestPushObservationsValidation: forged/malformed rows are rejected without
// error — self node_id (poisoning vector), empty node_id, negative HCL.
func TestPushObservationsValidation(t *testing.T) {
k := tmpDB(t)
foreign := GossipObservation{
NodeID: "0123456789abcdef0123456789abcdef", HCL: 42,
Fingerprint: "fp:foreign", SourceID: "test", Title: "t", Summary: "s",
CollectedAt: "2026-08-29T00:00:00Z",
}
rows := []GossipObservation{
foreign,
{NodeID: k.NodeID(), HCL: 100, Fingerprint: "fp:self"}, // spoof poisoning attempt
{NodeID: "", HCL: 1, Fingerprint: "fp:empty"},
{NodeID: "other", HCL: -5, Fingerprint: "fp:neg"},
}
n, err := k.PushObservations(rows)
if err != nil {
t.Fatalf("push: %v", err)
}
if n != 1 {
t.Fatalf("expected exactly the one valid row inserted, got %d", n)
}
if got := obsCount(t, k); got != 1 {
t.Fatalf("expected 1 observation in the log, got %d", got)
}
}
// TestOpenReopenHCLMonotonicAcrossRestart: reopening a DB must resume the HLC
// from its persisted max (clock seeding), keep the node identity, and order the
// new observation above every previous one.
func TestOpenReopenHCLMonotonicAcrossRestart(t *testing.T) {
path := filepath.Join(t.TempDir(), "index.db")
k1, err := Open(path)
if err != nil {
t.Fatalf("open: %v", err)
}
record(t, k1, "fp:r1", "one")
record(t, k1, "fp:r2", "two")
record(t, k1, "fp:r3", "three")
nodeID1 := k1.NodeID()
maxBefore := int64(0)
rows, err := k1.ObservationsAfter(nodeID1, 0, 100)
if err != nil {
t.Fatalf("obs after: %v", err)
}
for _, r := range rows {
if r.HCL > maxBefore {
maxBefore = r.HCL
}
}
if err := k1.Close(); err != nil {
t.Fatalf("close: %v", err)
}
k2, err := Open(path)
if err != nil {
t.Fatalf("reopen: %v", err)
}
defer k2.Close()
if k2.NodeID() != nodeID1 {
t.Errorf("node id changed across reopen: %q -> %q", nodeID1, k2.NodeID())
}
record(t, k2, "fp:r4", "four")
after, err := k2.ObservationsAfter(nodeID1, maxBefore, 100)
if err != nil {
t.Fatalf("obs after (reopened): %v", err)
}
if len(after) != 1 {
t.Fatalf("expected exactly the new observation above the pre-restart max, got %d rows", len(after))
}
if after[0].Fingerprint != "fp:r4" {
t.Errorf("unexpected row above max: %s", after[0].Fingerprint)
}
}