From 9f378946b9592ba161f409e0cfce079359c02ff5 Mon Sep 17 00:00:00 2001 From: David Gwilliam Date: Thu, 5 Nov 2026 01:09:03 -0800 Subject: [PATCH] feat: replicate thread membership and record merges (#41) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Threads replicated without their members: the replica could list a thread but not summarise it. Membership was stored two node-local ways — thread_observations by local observation id, provenance_links by ThreadFP(int id) — so neither could cross a node boundary. The replicated fact is the entry-level edge (thread uid, entry fingerprint), because the fingerprint is already stable across nodes; both local forms are materialised from it on arrival. Unlinks replicate as tombstones, or the next reconcile would resurrect the edge. Merges now record superseded_by = successor uid and replicate both threads, so a peer resolves the merge instead of restoring the absorbed thread. One deadlock fixed along the way: MergeThreads resolved the successor uid inside its transaction, and the pool is pinned to a single connection, so the query waited on itself. --- internal/cmd/thread.go | 6 +- internal/db/db.go | 44 ++++++- internal/db/thread_links.go | 216 +++++++++++++++++++++++++++++++ internal/db/thread_links_test.go | 113 ++++++++++++++++ internal/db/thread_sync.go | 33 ++--- internal/watch/reconcile.go | 7 + 6 files changed, 397 insertions(+), 22 deletions(-) create mode 100644 internal/db/thread_links.go create mode 100644 internal/db/thread_links_test.go diff --git a/internal/cmd/thread.go b/internal/cmd/thread.go index 2ba0ad1..7107e16 100644 --- a/internal/cmd/thread.go +++ b/internal/cmd/thread.go @@ -36,7 +36,11 @@ thread. Re-running is safe: unchanged documents dedupe.`, if err != nil { return err } - fmt.Printf("emitted %d thread(s)\n", n) + links, err := kdb.EmitAllLinks() + if err != nil { + return err + } + fmt.Printf("emitted %d thread(s) and %d link(s)\n", n, links) return nil }, }, newThreadCreateCmd(kdb)) diff --git a/internal/db/db.go b/internal/db/db.go index dfda086..0b50856 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -1844,7 +1844,13 @@ func (k *KnoxDB) LinkObservationToThread(threadID, observationID int64, relevanc if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID); err != nil { return err } - return tx.Commit() + if err := tx.Commit(); err != nil { + return err + } + if e := k.EmitLinkForObservation(threadID, observationID, relevance); e != nil { + log.Printf("[knox] emit link obs %d: %v", observationID, e) + } + return nil } // AutoLinkThreadObservations resolves each entry fingerprint to its most recent @@ -2056,11 +2062,20 @@ func (k *KnoxDB) LinkEntryToThread(threadID int64, entryFP, relation string) err return fmt.Errorf("entry fingerprint must not be empty") } tfp := ThreadFP(threadID) - _, err := k.db.Exec( + if _, err := k.db.Exec( `INSERT OR IGNORE INTO provenance_links (descendant_fp, ancestor_fp, hop_distance, relation) VALUES (?, ?, 1, ?)`, entryFP, tfp, relation, - ) - return err + ); err != nil { + return err + } + // Membership is a replicated fact: without it a peer receives the thread + // without its members, which is worse than not receiving it at all. + if uid, err := k.EnsureThreadUID(threadID); err == nil { + if e := k.EmitLink(uid, LinkDoc{EntryFP: entryFP, Relation: relation}); e != nil { + log.Printf("[knox] emit link %s: %v", entryFP, e) + } + } + return nil } // profileText is the text a thread's relevance keywords are mined from: the @@ -2693,6 +2708,12 @@ func (k *KnoxDB) MergeThreads(into, from int64) error { if into == from || into <= 0 || from <= 0 { return fmt.Errorf("invalid merge: into=%d from=%d", into, from) } + // Resolve the successor identity BEFORE opening the transaction: the pool is + // pinned to one connection, so a query inside the tx would wait on itself. + intoUID, err := k.EnsureThreadUID(into) + if err != nil { + return err + } tx, err := k.db.Begin() if err != nil { return err @@ -2716,7 +2737,20 @@ func (k *KnoxDB) MergeThreads(into, from int64) error { ); err != nil { return err } - return tx.Commit() + // Point the absorbed thread at its successor so a peer can resolve the + // merge rather than resurrecting it on the next reconcile. + if _, err := tx.Exec(`UPDATE threads SET superseded_by=? WHERE id=?`, intoUID, from); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + for _, id := range []int64{into, from} { + if e := k.EmitThread(id); e != nil { + log.Printf("[knox] emit thread #%d: %v", id, e) + } + } + return nil } // DenyThreadNoise refocuses existing threads against the shared denylist: diff --git a/internal/db/thread_links.go b/internal/db/thread_links.go new file mode 100644 index 0000000..408005c --- /dev/null +++ b/internal/db/thread_links.go @@ -0,0 +1,216 @@ +package db + +import ( + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "log" +) + +// Thread link replication. +// +// Membership is stored two ways locally: thread_observations keyed by a local +// observation id (what thread_text reads), and provenance_links keyed by entry +// fingerprint (what knox_thread_link_entry writes). Neither key is portable. +// +// The replicated fact is the entry-level one — "entry X belongs to thread U" — +// because an entry fingerprint is already stable across nodes. Both local forms +// are materialised from it on arrival. + +const threadLinkSourceID = "thread_link" + +// LinkDoc is the replicated form of a membership edge. +type LinkDoc struct { + ThreadUID string `json:"thread_uid"` + EntryFP string `json:"entry_fp"` + Relation string `json:"relation,omitempty"` + Relevance string `json:"relevance,omitempty"` + // Removed is a tombstone: an unlink must replicate too, or the edge would + // be resurrected by the next reconcile on this node. + Removed bool `json:"removed,omitempty"` +} + +func linkFingerprint(threadUID, entryFP, relation string) string { + sum := sha256.Sum256([]byte(threadLinkSourceID + ":" + threadUID + "|" + entryFP + "|" + relation)) + return hex.EncodeToString(sum[:]) +} + +// EmitLink records a membership edge in the observation log. +func (k *KnoxDB) EmitLink(threadUID string, d LinkDoc) error { + if threadUID == "" || d.EntryFP == "" { + return fmt.Errorf("link needs a thread uid and entry fingerprint") + } + d.ThreadUID = threadUID + relation := d.Relation + if relation == "" { + relation = "linked" + } + d.Relation = relation + body, err := json.Marshal(d) + if err != nil { + return err + } + _, _, err = k.RecordObservation(ObservationRecord{ + Fingerprint: linkFingerprint(threadUID, d.EntryFP, relation), + SourceID: threadLinkSourceID, + SourcePath: threadUID, + ContentType: ".thread_link", + Title: "link " + d.EntryFP, + Content: string(body), + Confidence: 1.0, + IngesterVersion: "thread_link/v1", + Trigger: "thread_link", + }) + return err +} + +// EmitLinkForObservation resolves a local observation id to its entry and +// records the edge. Used by the MCP path that links by observation id. +func (k *KnoxDB) EmitLinkForObservation(threadID, observationID int64, relevance string) error { + var fp string + if err := k.db.QueryRow(`SELECT fingerprint FROM observations WHERE id=?`, observationID).Scan(&fp); err != nil { + return fmt.Errorf("resolve observation %d: %w", observationID, err) + } + uid, err := k.EnsureThreadUID(threadID) + if err != nil { + return err + } + return k.EmitLink(uid, LinkDoc{EntryFP: fp, Relation: "linked", Relevance: relevance}) +} + +// ProjectLinks applies link observations, newest per edge. Removal wins only +// when it is the newest document for that edge. +func (k *KnoxDB) ProjectLinks() (applied int, err error) { + rows, err := k.db.Query( + `SELECT COALESCE(content,''), COALESCE(hcl,0) + FROM observations WHERE source_id=? ORDER BY hcl DESC`, threadLinkSourceID) + if err != nil { + return 0, err + } + defer rows.Close() + + seen := make(map[string]struct{}) + type edge struct { + doc LinkDoc + hcl int64 + } + var edges []edge + for rows.Next() { + var content string + var hcl int64 + if err := rows.Scan(&content, &hcl); err != nil { + return 0, err + } + var d LinkDoc + if err := json.Unmarshal([]byte(content), &d); err != nil || d.ThreadUID == "" || d.EntryFP == "" { + continue + } + key := d.ThreadUID + "|" + d.EntryFP + "|" + d.Relation + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + edges = append(edges, edge{doc: d, hcl: hcl}) + } + if err := rows.Err(); err != nil { + return 0, err + } + + for _, e := range edges { + if err := k.applyLink(e.doc); err != nil { + return applied, err + } + applied++ + } + return applied, nil +} + +func (k *KnoxDB) applyLink(d LinkDoc) error { + var threadID int64 + err := k.db.QueryRow(`SELECT id FROM threads WHERE uid=?`, d.ThreadUID).Scan(&threadID) + if err == sql.ErrNoRows { + // The thread document has not arrived yet; the next reconcile retries + // because links are replayed from the log, not consumed once. + return nil + } + if err != nil { + return fmt.Errorf("resolve thread %s: %w", d.ThreadUID, err) + } + + relation := d.Relation + if relation == "" { + relation = "linked" + } + tfp := ThreadFP(threadID) + + if d.Removed { + if _, err := k.db.Exec( + `DELETE FROM provenance_links WHERE descendant_fp=? AND ancestor_fp=?`, d.EntryFP, tfp); err != nil { + return err + } + if _, err := k.db.Exec( + `DELETE FROM thread_observations WHERE thread_id=? AND observation_id IN + (SELECT id FROM observations WHERE fingerprint=?)`, threadID, d.EntryFP); err != nil { + return err + } + return nil + } + + if _, err := k.db.Exec( + `INSERT OR IGNORE INTO provenance_links (descendant_fp, ancestor_fp, hop_distance, relation) VALUES (?, ?, 1, ?)`, + d.EntryFP, tfp, relation); err != nil { + return err + } + // Local membership for the digest/text paths. One row per entry is enough; + // use the newest observation of it. + _, err = k.db.Exec( + `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) + SELECT ?, id, ? FROM observations WHERE fingerprint=? ORDER BY id DESC LIMIT 1`, + threadID, relevanceOr(d.Relevance, relation), d.EntryFP) + return err +} + +func relevanceOr(v, fallback string) string { + if v != "" { + return v + } + return fallback +} + +// EmitAllLinks backfills existing membership as link observations. +func (k *KnoxDB) EmitAllLinks() (int, error) { + rows, err := k.db.Query(`SELECT thread_id, fingerprint FROM thread_observations JOIN observations ON observations.id = thread_observations.observation_id`) + if err != nil { + return 0, err + } + type pair struct { + threadID int64 + fp string + } + var pairs []pair + for rows.Next() { + var p pair + if err := rows.Scan(&p.threadID, &p.fp); err != nil { + rows.Close() + return 0, err + } + pairs = append(pairs, p) + } + rows.Close() + + emitted := 0 + for _, p := range pairs { + uid, err := k.EnsureThreadUID(p.threadID) + if err != nil { + return emitted, err + } + if err := k.EmitLink(uid, LinkDoc{EntryFP: p.fp, Relation: "linked"}); err != nil { + return emitted, err + } + emitted++ + } + log.Printf("[knox] links: emitted %d observation(s)", emitted) + return emitted, nil +} diff --git a/internal/db/thread_links_test.go b/internal/db/thread_links_test.go new file mode 100644 index 0000000..6e99ef9 --- /dev/null +++ b/internal/db/thread_links_test.go @@ -0,0 +1,113 @@ +package db_test + +import ( + "testing" + + "github.com/david/knox/internal/db" +) + +// TestLinkReplicates: membership must travel with the thread. A peer that +// receives a thread without its members can list it but cannot summarise it. +func TestLinkReplicates(t *testing.T) { + kdb, raw := openBoth(t) + + // An entry to link to, created the way the indexer does. + if _, _, err := kdb.RecordObservation(db.ObservationRecord{ + Fingerprint: "entry-fp-1", SourceID: "test", Title: "grafana dashboard notes", + Content: "dashboards", IngesterVersion: "test/v1", Trigger: "test", + }); err != nil { + t.Fatalf("record entry: %v", err) + } + + id, err := kdb.CreateThread("Dashboards", "why", "high", `[]`, `{}`) + if err != nil { + t.Fatalf("create thread: %v", err) + } + if err := kdb.LinkEntryToThread(id, "entry-fp-1", "references"); err != nil { + t.Fatalf("link: %v", err) + } + + var linkObs int + if err := raw.QueryRow(`SELECT COUNT(*) FROM observations WHERE source_id='thread_link'`).Scan(&linkObs); err != nil { + t.Fatalf("count links: %v", err) + } + if linkObs != 1 { + t.Fatalf("link observations = %d, want 1", linkObs) + } + + // Wipe local membership, then rebuild it from the log alone. + if _, err := raw.Exec(`DELETE FROM thread_observations; DELETE FROM provenance_links;`); err != nil { + t.Fatalf("wipe: %v", err) + } + if _, err := kdb.ProjectLinks(); err != nil { + t.Fatalf("project links: %v", err) + } + + var members int + if err := raw.QueryRow( + `SELECT COUNT(*) FROM thread_observations WHERE thread_id=?`, id).Scan(&members); err != nil { + t.Fatalf("count members: %v", err) + } + if members != 1 { + t.Fatalf("thread members = %d, want 1 after projection", members) + } + var prov int + if err := raw.QueryRow( + `SELECT COUNT(*) FROM provenance_links WHERE descendant_fp='entry-fp-1'`).Scan(&prov); err != nil { + t.Fatalf("count provenance: %v", err) + } + if prov != 1 { + t.Fatalf("provenance links = %d, want 1", prov) + } +} + +// TestMergeRecordsSupersede: a merged thread must point at its successor, so a +// peer resolves the merge instead of resurrecting the absorbed thread. +func TestMergeRecordsSupersede(t *testing.T) { + kdb, raw := openBoth(t) + + into, err := kdb.CreateThread("Successor", "m", "high", `[]`, `{}`) + if err != nil { + t.Fatalf("create into: %v", err) + } + from, err := kdb.CreateThread("Absorbed", "m", "low", `[]`, `{}`) + if err != nil { + t.Fatalf("create from: %v", err) + } + if err := kdb.MergeThreads(into, from); err != nil { + t.Fatalf("merge: %v", err) + } + + var intoUID, superseded, status string + if err := raw.QueryRow(`SELECT COALESCE(uid,'') FROM threads WHERE id=?`, into).Scan(&intoUID); err != nil { + t.Fatalf("read successor: %v", err) + } + if err := raw.QueryRow( + `SELECT COALESCE(superseded_by,''), COALESCE(status,'') FROM threads WHERE id=?`, from, + ).Scan(&superseded, &status); err != nil { + t.Fatalf("read absorbed: %v", err) + } + if superseded != intoUID { + t.Fatalf("superseded_by = %q, want the successor uid %q", superseded, intoUID) + } + if status != "resolved" { + t.Fatalf("absorbed status = %q, want resolved", status) + } + + // The pointer must also survive a rebuild from the log. + if _, err := raw.Exec(`DELETE FROM thread_observations; DELETE FROM threads;`); err != nil { + t.Fatalf("wipe: %v", err) + } + if _, err := kdb.ProjectThreads(); err != nil { + t.Fatalf("project: %v", err) + } + var restored string + if err := raw.QueryRow( + `SELECT COALESCE(superseded_by,'') FROM threads WHERE uid=(SELECT uid FROM observations WHERE source_id='thread' AND content LIKE '%Absorbed%' LIMIT 1)`, + ).Scan(&restored); err != nil { + t.Fatalf("read restored: %v", err) + } + if restored != intoUID { + t.Fatalf("restored superseded_by = %q, want %q", restored, intoUID) + } +} diff --git a/internal/db/thread_sync.go b/internal/db/thread_sync.go index 6a7db43..cd7c78d 100644 --- a/internal/db/thread_sync.go +++ b/internal/db/thread_sync.go @@ -27,15 +27,16 @@ const threadSourceID = "thread" // ThreadDoc is the replicated form of a thread. Field names are part of the // wire format: older nodes ignore unknown keys, newer ones default missing ones. type ThreadDoc struct { - UID string `json:"uid"` - ClusterKey string `json:"cluster_key,omitempty"` - Title string `json:"title"` - Motivation string `json:"motivation,omitempty"` - Status string `json:"status"` - Priority string `json:"priority"` - Tags string `json:"tags,omitempty"` - Summary string `json:"summary,omitempty"` - ResolvedAt string `json:"resolved_at,omitempty"` + UID string `json:"uid"` + ClusterKey string `json:"cluster_key,omitempty"` + Title string `json:"title"` + Motivation string `json:"motivation,omitempty"` + Status string `json:"status"` + Priority string `json:"priority"` + Tags string `json:"tags,omitempty"` + Summary string `json:"summary,omitempty"` + ResolvedAt string `json:"resolved_at,omitempty"` + SupersededBy string `json:"superseded_by,omitempty"` } // NewThreadUID returns an opaque node-generated identity. Opaque on purpose: @@ -62,9 +63,9 @@ func (k *KnoxDB) ThreadDocFor(id int64) (*ThreadDoc, error) { err := k.db.QueryRow( `SELECT COALESCE(uid,''), COALESCE(cluster_key,''), title, COALESCE(motivation,''), COALESCE(status,'active'), COALESCE(priority,'medium'), COALESCE(tags,'[]'), - COALESCE(summary,''), COALESCE(resolved_at,'') + COALESCE(summary,''), COALESCE(resolved_at,''), COALESCE(superseded_by,'') FROM threads WHERE id=?`, id, - ).Scan(&d.UID, &d.ClusterKey, &d.Title, &d.Motivation, &d.Status, &d.Priority, &d.Tags, &d.Summary, &d.ResolvedAt) + ).Scan(&d.UID, &d.ClusterKey, &d.Title, &d.Motivation, &d.Status, &d.Priority, &d.Tags, &d.Summary, &d.ResolvedAt, &d.SupersededBy) if err != nil { return nil, err } @@ -226,9 +227,9 @@ func (k *KnoxDB) upsertThreadDoc(d ThreadDoc, hcl int64) error { if id == 0 { _, err := k.db.Exec( - `INSERT INTO threads (uid, title, motivation, status, priority, tags, cluster_key, summary, resolved_at, hcl, provenance) - VALUES (?,?,?,?,?,?,?,?,?,?,?)`, - d.UID, d.Title, d.Motivation, status, priority, d.Tags, d.ClusterKey, d.Summary, d.ResolvedAt, hcl, + `INSERT INTO threads (uid, title, motivation, status, priority, tags, cluster_key, summary, resolved_at, superseded_by, hcl, provenance) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`, + d.UID, d.Title, d.Motivation, status, priority, d.Tags, d.ClusterKey, d.Summary, d.ResolvedAt, d.SupersededBy, hcl, fmt.Sprintf(`{"replicated":true}`)) if err != nil { return fmt.Errorf("insert replicated thread %s: %w", d.UID, err) @@ -242,9 +243,9 @@ func (k *KnoxDB) upsertThreadDoc(d ThreadDoc, hcl int64) error { `UPDATE threads SET uid=?, title=?, motivation=?, status=?, priority=?, tags=?, cluster_key=COALESCE(NULLIF(?, ''), cluster_key), - summary=?, resolved_at=?, hcl=?, updated_at=datetime('now') + summary=?, resolved_at=?, superseded_by=?, hcl=?, updated_at=datetime('now') WHERE id=?`, - d.UID, d.Title, d.Motivation, status, priority, d.Tags, d.ClusterKey, d.Summary, d.ResolvedAt, hcl, id) + d.UID, d.Title, d.Motivation, status, priority, d.Tags, d.ClusterKey, d.Summary, d.ResolvedAt, d.SupersededBy, hcl, id) if err != nil { return fmt.Errorf("update replicated thread %s: %w", d.UID, err) } diff --git a/internal/watch/reconcile.go b/internal/watch/reconcile.go index ed34205..3be7b1a 100644 --- a/internal/watch/reconcile.go +++ b/internal/watch/reconcile.go @@ -26,5 +26,12 @@ func Reconcile(kdb *db.KnoxDB) (int, int, error) { } else if applied > 0 { created += applied } + // Membership last: links resolve against threads, so they need both the + // derived and the replicated threads to exist first. + if applied, err := kdb.ProjectLinks(); err != nil { + return created, linked, fmt.Errorf("project links: %w", err) + } else { + linked += applied + } return created, linked, nil } -- 2.52.0