Compare commits

2 Commits

Author SHA1 Message Date
david 9f378946b9 feat: replicate thread membership and record merges (#41)
build / image (push) Successful in 39s
build / test (push) Successful in 5m9s
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.
2026-11-05 01:09:03 -08:00
david 00f277cf76 feat: replicate threads through the observation log (#45)
build / test (push) Successful in 3m28s
build / image (push) Successful in 19s
feat: replicate threads through the observation log (#45)

Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 08:47:39 +00:00
10 changed files with 1032 additions and 44 deletions
+22 -1
View File
@@ -22,7 +22,28 @@ motivation, and in-flight knowledge development work.
Subcommands: create, list, link, link-entry, relate, golden, prune, rescan, close, show, note`,
}
cmd.AddCommand(newThreadCreateCmd(kdb))
cmd.AddCommand(
&cobra.Command{
Use: "emit-all",
Short: "Backfill thread observations so existing threads replicate",
Long: `Backfill thread observations.
Threads written before replication existed have no observation, so no peer can
learn about them. This assigns a uid to each and emits one observation per
thread. Re-running is safe: unchanged documents dedupe.`,
RunE: func(c *cobra.Command, args []string) error {
n, err := kdb.EmitAllThreads()
if err != nil {
return err
}
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))
cmd.AddCommand(newThreadAutoCmd(kdb))
cmd.AddCommand(newThreadDraftCmd(kdb))
cmd.AddCommand(newThreadUpdateCmd(kdb))
+67 -7
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"log"
"math"
"os"
"path/filepath"
@@ -187,6 +188,9 @@ func Open(path string) (*KnoxDB, error) {
"ALTER TABLE threads ADD COLUMN retained INTEGER DEFAULT 0",
"ALTER TABLE threads ADD COLUMN summary TEXT DEFAULT ''",
"ALTER TABLE threads ADD COLUMN summarized_at TEXT DEFAULT ''",
"ALTER TABLE threads ADD COLUMN uid TEXT",
"ALTER TABLE threads ADD COLUMN hcl INTEGER",
"ALTER TABLE threads ADD COLUMN superseded_by TEXT",
"ALTER TABLE snippets ADD COLUMN junk INTEGER DEFAULT 0",
"ALTER TABLE snippets ADD COLUMN kind TEXT DEFAULT 'code'",
}
@@ -228,6 +232,12 @@ func Open(path string) (*KnoxDB, error) {
return nil, fmt.Errorf("create locator index: %w", err)
}
// Thread replication identity index, likewise after the uid migration: a
// fresh DB has the column from Schema, an existing one only gains it above.
if _, err := db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_threads_uid ON threads(uid) WHERE uid IS NOT NULL AND uid != ''`); err != nil {
return nil, fmt.Errorf("create thread uid index: %w", err)
}
// Thread idempotency index must come after the cluster_key migration (a
// fresh DB has the column from Schema; an existing DB gets it above).
if _, err := db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_threads_cluster ON threads(cluster_key) WHERE cluster_key IS NOT NULL AND cluster_key != ''`); err != nil {
@@ -1649,15 +1659,21 @@ func (k *KnoxDB) CreateThreadCluster(title, motivation, priority, tags, provenan
// concurrent creators (thread ticker + post-pull reconcile, or two gossip
// nodes converging on the same cluster) lose the race into a no-op instead
// of a UNIQUE error, then pick up the winner's id.
uid := NewThreadUID()
res, err := k.db.Exec(
`INSERT OR IGNORE INTO threads (title, motivation, priority, tags, provenance, cluster_key) VALUES (?, ?, ?, ?, ?, ?)`,
title, motivation, priority, tags, provenance, clusterKey,
`INSERT OR IGNORE INTO threads (title, motivation, priority, tags, provenance, cluster_key, uid) VALUES (?, ?, ?, ?, ?, ?, ?)`,
title, motivation, priority, tags, provenance, clusterKey, uid,
)
if err != nil {
return 0, false, err
}
if n, _ := res.RowsAffected(); n > 0 {
id, _ := res.LastInsertId()
// Replicate the thread itself: titles and motivations are authored, so
// they exist nowhere in the log until this runs.
if err := k.EmitThread(id); err != nil {
log.Printf("[knox] emit thread #%d: %v", id, err)
}
return id, true, nil
}
// Ignored insert: a thread with this cluster key already exists.
@@ -1737,6 +1753,11 @@ func (k *KnoxDB) CloseThread(id int64) error {
`UPDATE threads SET status='resolved', resolved_at=datetime('now'), updated_at=datetime('now') WHERE id=?`,
id,
)
if err == nil {
if e := k.EmitThread(id); e != nil {
log.Printf("[knox] emit thread #%d: %v", id, e)
}
}
return err
}
@@ -1777,6 +1798,11 @@ func (k *KnoxDB) UpdateThread(id int64, title, motivation, priority, tags string
`UPDATE threads SET title=?, motivation=?, priority=?, tags=?, provenance=?, updated_at=datetime('now') WHERE id=?`,
title, motivation, priority, tags, provenance, id,
)
if err == nil {
if e := k.EmitThread(id); e != nil {
log.Printf("[knox] emit thread #%d: %v", id, e)
}
}
return true, err
}
@@ -1818,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
@@ -2030,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
@@ -2667,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
@@ -2690,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:
+8 -1
View File
@@ -123,9 +123,16 @@ CREATE TABLE IF NOT EXISTS threads (
cluster_key TEXT,
retained INTEGER DEFAULT 0,
summary TEXT DEFAULT '',
summarized_at TEXT DEFAULT ''
summarized_at TEXT DEFAULT '',
-- Replication identity and last-write clock. uid is opaque and node-
-- generated; the integer id is local and cannot address a thread across
-- nodes. superseded_by points at the uid that absorbed this thread.
uid TEXT,
hcl INTEGER,
superseded_by TEXT
);
-- SETTINGS: key-value store for runtime configuration
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
+216
View File
@@ -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
}
+113
View File
@@ -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)
}
}
+285
View File
@@ -0,0 +1,285 @@
package db
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
)
// Thread replication.
//
// Threads are authored as well as derived, so they cannot be rebuilt from the
// entry/observation data alone — a title someone typed exists nowhere else.
// Each thread therefore emits an observation on every meaningful write, and
// reconcile projects the log back into the threads table. That keeps one
// replication path (the observation log) instead of adding a second one.
//
// The identity is a node-generated uid, not the integer id: autoincrement ids
// are local and collide across nodes, and cluster_key covers only auto-created
// clusters (an authored thread may have none).
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"`
SupersededBy string `json:"superseded_by,omitempty"`
}
// NewThreadUID returns an opaque node-generated identity. Opaque on purpose:
// nothing should parse it, and any format change must not break comparisons.
func NewThreadUID() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
// crypto/rand failing is not a condition to paper over with a weak id.
panic(fmt.Sprintf("thread uid: %v", err))
}
return hex.EncodeToString(b)
}
// threadFingerprint is stable across edits so every version of a thread lands
// on the same log key and the newest wins.
func threadFingerprint(uid string) string {
sum := sha256.Sum256([]byte(threadSourceID + ":" + uid))
return hex.EncodeToString(sum[:])
}
// ThreadDocFor reads a thread as its replicated form.
func (k *KnoxDB) ThreadDocFor(id int64) (*ThreadDoc, error) {
var d ThreadDoc
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(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, &d.SupersededBy)
if err != nil {
return nil, err
}
return &d, nil
}
// EmitThread records the thread's current state in the observation log so peers
// can converge on it. It is called after the write (not inside the same
// transaction): a missed append leaves the thread unpropagated until the next
// edit or a backfill, which is recoverable; a thread row rolled back after its
// observation landed would be the harder failure to explain.
func (k *KnoxDB) EmitThread(id int64) error {
doc, err := k.ThreadDocFor(id)
if err != nil {
return err
}
if doc.UID == "" {
return fmt.Errorf("thread #%d has no uid", id)
}
body, err := json.Marshal(doc)
if err != nil {
return err
}
title := doc.Title
if len(title) > 200 {
title = title[:200]
}
fp := threadFingerprint(doc.UID)
_, _, err = k.RecordObservation(ObservationRecord{
Fingerprint: fp,
SourceID: threadSourceID,
SourcePath: doc.UID,
ContentType: ".thread",
Title: title,
Summary: doc.Motivation,
Content: string(body),
Confidence: 1.0,
IngesterVersion: "thread/v1",
Trigger: "thread_write",
Provenance: fmt.Sprintf(`{"thread_uid":%q}`, doc.UID),
})
if err != nil {
return err
}
// Mirror the clock onto the row. Without it a local thread carries hcl=0,
// so the LWW guard would let every incoming document win — including older
// ones, which is the opposite of last-write-wins.
var hcl int64
if e := k.db.QueryRow(
`SELECT COALESCE(hcl,0) FROM observations WHERE fingerprint=? ORDER BY id DESC LIMIT 1`, fp,
).Scan(&hcl); e == nil && hcl > 0 {
if _, e := k.db.Exec(`UPDATE threads SET hcl=? WHERE id=?`, hcl, id); e != nil {
return e
}
}
return nil
}
// EnsureThreadUID assigns an identity to a thread that predates replication.
func (k *KnoxDB) EnsureThreadUID(id int64) (string, error) {
var uid string
if err := k.db.QueryRow(`SELECT COALESCE(uid,'') FROM threads WHERE id=?`, id).Scan(&uid); err != nil {
return "", err
}
if uid != "" {
return uid, nil
}
uid = NewThreadUID()
if _, err := k.db.Exec(`UPDATE threads SET uid=? WHERE id=?`, uid, id); err != nil {
return "", fmt.Errorf("assign uid: %w", err)
}
return uid, nil
}
// ThreadUIDForID returns the thread's uid, assigning one if it has none.
func (k *KnoxDB) ThreadUIDForID(id int64) (string, error) { return k.EnsureThreadUID(id) }
// ProjectThreads applies thread observations to the threads table, newest first
// per uid. It is the reconcile half of EmitThread, and it runs *after* the
// auto-threader so that authored state wins over derived state.
//
// Identity resolution: a document carrying a cluster_key that a local row
// already has adopts that row's identity instead of creating a duplicate — the
// case where two nodes derived the same cluster before hearing about each other.
func (k *KnoxDB) ProjectThreads() (applied int, err error) {
rows, err := k.db.Query(
`SELECT COALESCE(content,''), COALESCE(hcl,0), COALESCE(node_id,'')
FROM observations
WHERE source_id=?
ORDER BY hcl DESC, node_id DESC`, threadSourceID)
if err != nil {
return 0, err
}
defer rows.Close()
seen := make(map[string]struct{})
type docRow struct {
doc ThreadDoc
hcl int64
nodes string
}
var docs []docRow
for rows.Next() {
var content, node string
var hcl int64
if err := rows.Scan(&content, &hcl, &node); err != nil {
return 0, err
}
var d ThreadDoc
if err := json.Unmarshal([]byte(content), &d); err != nil || d.UID == "" {
continue
}
if _, dup := seen[d.UID]; dup {
continue // an older version of the same thread
}
seen[d.UID] = struct{}{}
docs = append(docs, docRow{doc: d, hcl: hcl, nodes: node})
}
if err := rows.Err(); err != nil {
return 0, err
}
for _, dr := range docs {
if err := k.upsertThreadDoc(dr.doc, dr.hcl); err != nil {
return applied, err
}
applied++
}
return applied, nil
}
func (k *KnoxDB) upsertThreadDoc(d ThreadDoc, hcl int64) error {
status := d.Status
if status == "" {
status = "active"
}
priority := d.Priority
if priority == "" {
priority = "medium"
}
// Resolve identity: uid first, then cluster_key for a row that never got a
// uid (derived locally on this node before the peer's thread arrived).
var id int64
var currentHCL int64
err := k.db.QueryRow(`SELECT id, COALESCE(hcl,0) FROM threads WHERE uid=?`, d.UID).Scan(&id, &currentHCL)
if err == sql.ErrNoRows && d.ClusterKey != "" {
err = k.db.QueryRow(`SELECT id, COALESCE(hcl,0) FROM threads WHERE cluster_key=?`, d.ClusterKey).Scan(&id, &currentHCL)
}
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("resolve thread %s: %w", d.UID, err)
}
// Last write wins on the logical clock. Without this guard the cluster_key
// path can let an older document overwrite a newer one, because two peers
// may have minted different uids for the same cluster.
if id != 0 && currentHCL > hcl {
return nil
}
if id == 0 {
_, err := k.db.Exec(
`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)
}
return nil
}
// cluster_key is identity, not content: a document emitted before the key was
// assigned carries "", and clearing the local one would break the fallback
// that stops the same cluster arriving twice.
_, err = k.db.Exec(
`UPDATE threads
SET uid=?, title=?, motivation=?, status=?, priority=?, tags=?,
cluster_key=COALESCE(NULLIF(?, ''), cluster_key),
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, d.SupersededBy, hcl, id)
if err != nil {
return fmt.Errorf("update replicated thread %s: %w", d.UID, err)
}
return nil
}
// EmitAllThreads backfills the log for threads that predate replication. Safe to
// run repeatedly: unchanged documents dedupe in RecordObservation.
func (k *KnoxDB) EmitAllThreads() (int, error) {
rows, err := k.db.Query(`SELECT id FROM threads ORDER BY id`)
if err != nil {
return 0, err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return 0, err
}
ids = append(ids, id)
}
rows.Close()
emitted := 0
for _, id := range ids {
if _, err := k.EnsureThreadUID(id); err != nil {
return emitted, err
}
if err := k.EmitThread(id); err != nil {
return emitted, err
}
emitted++
}
log.Printf("[knox] threads: emitted %d observation(s)", emitted)
return emitted, nil
}
+145
View File
@@ -0,0 +1,145 @@
package db_test
import (
"database/sql"
"encoding/json"
"path/filepath"
"testing"
_ "modernc.org/sqlite"
"github.com/david/knox/internal/db"
)
// openBoth returns the knox handle plus a second connection for assertions:
// KnoxDB keeps its connection private (and pins MaxOpenConns to 1), so tests
// inspect the file directly. WAL makes the second reader safe.
func openBoth(t *testing.T) (*db.KnoxDB, *sql.DB) {
t.Helper()
path := filepath.Join(t.TempDir(), "index.db")
kdb, err := db.Open(path)
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { _ = kdb.Close() })
raw, err := sql.Open("sqlite", path)
if err != nil {
t.Fatalf("open raw: %v", err)
}
t.Cleanup(func() { _ = raw.Close() })
return kdb, raw
}
// TestCreateThreadEmitsObservation: a thread's title and motivation are
// authored, so they exist nowhere in the log until the write emits them. Without
// this, a peer can never learn the thread existed.
func TestCreateThreadEmitsObservation(t *testing.T) {
kdb, raw := openBoth(t)
id, err := kdb.CreateThread("Grafana dashboards", "why we standardised them", "high", `["grafana"]`, `{}`)
if err != nil {
t.Fatalf("create: %v", err)
}
var n int
if err := raw.QueryRow(`SELECT COUNT(*) FROM observations WHERE source_id='thread'`).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
if n != 1 {
t.Fatalf("thread observations = %d, want 1", n)
}
var uid string
if err := raw.QueryRow(`SELECT COALESCE(uid,'') FROM threads WHERE id=?`, id).Scan(&uid); err != nil {
t.Fatalf("uid: %v", err)
}
if uid == "" {
t.Fatal("thread has no uid, so it cannot be addressed across nodes")
}
}
// TestProjectThreadsRestoresAuthoredState: reconcile must be able to rebuild
// authored threads from the log — that is the whole point of replicating them.
func TestProjectThreadsRestoresAuthoredState(t *testing.T) {
kdb, raw := openBoth(t)
id, err := kdb.CreateThread("Original title", "original motivation", "high", `[]`, `{}`)
if err != nil {
t.Fatalf("create: %v", err)
}
// Wipe the materialized row but keep the log, mimicking a fresh node.
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 title, motivation, priority string
if err := raw.QueryRow(`SELECT title, COALESCE(motivation,''), COALESCE(priority,'') FROM threads`).Scan(&title, &motivation, &priority); err != nil {
t.Fatalf("read back: %v", err)
}
if title != "Original title" || motivation != "original motivation" || priority != "high" {
t.Fatalf("restored %q/%q/%q, want the authored values", title, motivation, priority)
}
_ = id
}
// TestProjectThreadsLastWriteWins: a stale document must not clobber a newer
// edit, including through the cluster_key fallback where two nodes minted
// different uids for the same cluster.
func TestProjectThreadsLastWriteWins(t *testing.T) {
kdb, raw := openBoth(t)
id, err := kdb.CreateThread("Fresh title", "m", "medium", `[]`, `{}`)
if err != nil {
t.Fatalf("create: %v", err)
}
if _, err := kdb.UpdateThread(id, "Newer title", "", "", ""); err != nil {
t.Fatalf("update: %v", err)
}
// Fabricate an older document with a different uid but the same cluster_key,
// the shape two peers produce when they each derive the same cluster.
uid, _ := kdb.ThreadUIDForID(id)
old := db.ThreadDoc{UID: "older-uid", ClusterKey: "shared-cluster", Title: "Stale title", Status: "active", Priority: "low"}
body, _ := json.Marshal(old)
if _, _, err := kdb.RecordObservation(db.ObservationRecord{
Fingerprint: "fp-old-doc", SourceID: "thread", Content: string(body),
Title: "Stale title", IngesterVersion: "thread/v1", Trigger: "test",
}); err != nil {
t.Fatalf("record stale doc: %v", err)
}
// The clock assigns now, so force this document into the past: it must lose
// to the thread's own newer write.
if _, err := raw.Exec(`UPDATE observations SET hcl=1 WHERE fingerprint='fp-old-doc'`); err != nil {
t.Fatalf("age the doc: %v", err)
}
if _, err := raw.Exec(`UPDATE threads SET cluster_key='shared-cluster' WHERE id=?`, id); err != nil {
t.Fatalf("set cluster key: %v", err)
}
if _, err := kdb.ProjectThreads(); err != nil {
t.Fatalf("project: %v", err)
}
var title, gotUID string
var count int
if err := raw.QueryRow(`SELECT title, COALESCE(uid,'') FROM threads WHERE id=?`, id).Scan(&title, &gotUID); err != nil {
t.Fatalf("read: %v", err)
}
if title != "Newer title" {
t.Fatalf("title = %q, want the newer edit", title)
}
if gotUID != uid {
t.Fatalf("uid = %q, want the newer document's identity %q", gotUID, uid)
}
if err := raw.QueryRow(`SELECT COUNT(*) FROM threads`).Scan(&count); err != nil {
t.Fatalf("count: %v", err)
}
if count != 1 {
t.Fatalf("threads = %d, want 1 (no duplicate from the cluster_key fallback)", count)
}
}
+104 -28
View File
@@ -19,7 +19,7 @@ type LogIngester struct {
}
func NewLogIngester() *LogIngester {
return &LogIngester{Version: "log-parser/v2"}
return &LogIngester{Version: "log-parser/v3"}
}
func (l *LogIngester) SourceID() string { return "opencode-log" }
@@ -47,7 +47,7 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
sessionIDs []string
models []string
agents []string
signatures []string
sigs = map[string]*logSig{}
totalLines int
errCount int
warnCount int
@@ -82,7 +82,7 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
} else {
errCount++
}
signatures = append(signatures, normalizeLogLine(line))
recordSignature(sigs, line)
}
base := filepath.Base(path)
@@ -92,10 +92,12 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
createdAt = fi.ModTime().UTC().Format(time.RFC3339)
}
uniq := uniqueSorted(signatures)
contentHash := hashSignatures(uniq, errCount, warnCount)
ordered := sortedSignatures(sigs)
rendered := renderSignatures(ordered)
summary := buildLogSummary(uniq, errCount, warnCount)
contentHash := hashSignatures(ordered, errCount, warnCount)
summary := buildLogSummary(ordered, errCount, warnCount)
confidence := 0.6
if errCount > 0 || warnCount > 0 {
@@ -109,7 +111,7 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
ContentType: ".log",
Title: "Log " + base,
Summary: summary,
Content: strings.Join(uniq, "\n"),
Content: strings.Join(rendered, "\n"),
CreatedAt: createdAt,
Confidence: confidence,
IngesterVersion: l.Version,
@@ -121,7 +123,7 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
"agents": uniqueSlice(agents),
"error_count": errCount,
"warn_count": warnCount,
"errors_sample": firstN(uniq, 5),
"errors_sample": firstN(rendered, 5),
"file_size": fmt.Sprintf("%d lines", totalLines),
},
}, nil
@@ -149,19 +151,107 @@ func normalizeLogLine(line string) string {
return truncate(s, 160)
}
// hashSignatures is the change signal: it depends only on the set of distinct
// error signatures and the level counts — not on total line count or ordering.
func hashSignatures(sigs []string, errCount, warnCount int) string {
// logSig is one normalized error signature plus the dates it was seen on.
//
// The date range is the point of the digest: a signature with volatile values
// stripped cannot tell a failure that was fixed last week from one that is
// happening right now.
type logSig struct {
text string
first, last string // YYYY-MM-DD, empty when the line carries no timestamp
}
var tsDateRE = regexp.MustCompile(`^timestamp=(\d{4}-\d{2}-\d{2})`)
// logLineDate returns the day a log line was written, or "" when it has no
// leading timestamp.
func logLineDate(line string) string {
if m := tsDateRE.FindStringSubmatch(line); len(m) > 1 {
return m[1]
}
return ""
}
// recordSignature folds one serious log line into the signature map, widening
// the date range of an existing signature instead of repeating it.
func recordSignature(sigs map[string]*logSig, line string) {
text := normalizeLogLine(line)
day := logLineDate(line)
s, ok := sigs[text]
if !ok {
sigs[text] = &logSig{text: text, first: day, last: day}
return
}
if day == "" {
return
}
if s.first == "" || day < s.first {
s.first = day
}
if day > s.last {
s.last = day
}
}
// sortedSignatures orders by most recently seen first, so the digest leads with
// what is happening now rather than whatever sorts first alphabetically.
func sortedSignatures(sigs map[string]*logSig) []*logSig {
out := make([]*logSig, 0, len(sigs))
for _, s := range sigs {
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool {
if out[i].last != out[j].last {
return out[i].last > out[j].last
}
if out[i].first != out[j].first {
return out[i].first > out[j].first
}
return out[i].text < out[j].text
})
return out
}
func renderSignature(s *logSig) string {
switch {
case s.first == "":
return s.text
case s.first == s.last:
return s.first + " " + s.text
default:
return s.first + ".." + s.last + " " + s.text
}
}
func renderSignatures(sigs []*logSig) []string {
out := make([]string, len(sigs))
for i, s := range sigs {
out[i] = renderSignature(s)
}
return out
}
// hashSignatures is the change signal: it depends on the set of distinct error
// signatures with the dates they were seen — not on total line count or
// ordering. Volatile values (run ids, session ids, times of day) are already
// stripped, so a recurring error only moves the hash when it recurs on a new
// day, which is exactly when the digest needs rewriting.
func hashSignatures(sigs []*logSig, errCount, warnCount int) string {
h := sha256.New()
for _, s := range sigs {
h.Write([]byte(s))
h.Write([]byte(s.text))
h.Write([]byte{'\t'})
h.Write([]byte(s.first))
h.Write([]byte{'~'})
h.Write([]byte(s.last))
h.Write([]byte{'\n'})
}
fmt.Fprintf(h, "E=%d W=%d", errCount, warnCount)
return fmt.Sprintf("%x", h.Sum(nil)[:8])
}
func buildLogSummary(sigs []string, errCount, warnCount int) string {
func buildLogSummary(sigs []*logSig, errCount, warnCount int) string {
if errCount == 0 && warnCount == 0 {
return "no errors"
}
@@ -169,25 +259,11 @@ func buildLogSummary(sigs []string, errCount, warnCount int) string {
fmt.Fprintf(&b, "levels: E%d W%d", errCount, warnCount)
if len(sigs) > 0 {
b.WriteString(" | err: ")
b.WriteString(strings.Join(firstN(sigs, 5), " ;; "))
b.WriteString(strings.Join(firstN(renderSignatures(sigs), 5), " ;; "))
}
return b.String()
}
// uniqueSorted returns de-duplicated, lexicographically sorted signatures.
func uniqueSorted(items []string) []string {
seen := make(map[string]bool)
var out []string
for _, s := range items {
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
sort.Strings(out)
return out
}
func firstN(items []string, n int) []string {
if len(items) > n {
return items[:n]
+58 -7
View File
@@ -34,16 +34,16 @@ func TestLogIgnoresInfoTimeoutSubstring(t *testing.T) {
}
}
// The content hash must be stable across volatile differences (timestamps, run
// ids, session/message ids, line numbers, extra INFO) and change only when the
// distinct error set changes.
func TestLogContentHashStability(t *testing.T) {
// The content hash must be stable across volatile differences (times of day,
// run ids, session/message ids, line numbers, extra INFO) within the same day,
// so an unchanged error set collapses to a no-op.
func TestLogContentHashStableWithinDay(t *testing.T) {
base := `[] level=ERROR run=aaaa session.id=ses_abc123 messageID=msg_zzz999 error="Not Found"` + "\n"
a := `timestamp=2026-10-01T00:00:00.000Z ` + base
// Same error, different volatile values, plus unrelated INFO noise.
b := `timestamp=2026-10-02T12:34:56.789Z ` + base +
`timestamp=2026-10-02T12:34:57.000Z level=INFO run=cccc message="resolved path" arg=timeout` + "\n"
b := `timestamp=2026-10-01T23:59:59.999Z [] level=ERROR run=ffff session.id=ses_def456 messageID=msg_yyy111 error="Not Found"` + "\n" +
`timestamp=2026-10-01T23:59:58.000Z level=INFO run=cccc message="resolved path" arg=timeout` + "\n"
l := NewLogIngester()
ra, err := l.Ingest(writeTempLog(t, a))
@@ -55,7 +55,7 @@ func TestLogContentHashStability(t *testing.T) {
t.Fatal(err)
}
if ra.ContentHash != rb.ContentHash {
t.Fatalf("hash should be stable: %s != %s", ra.ContentHash, rb.ContentHash)
t.Fatalf("hash should be stable within a day: %s != %s", ra.ContentHash, rb.ContentHash)
}
// A genuinely new distinct error changes the hash.
@@ -68,3 +68,54 @@ func TestLogContentHashStability(t *testing.T) {
t.Fatal("hash should change when a new distinct error appears")
}
}
// A recurring error must move the hash once it recurs on a new day: the digest
// carries the dates, so "still happening" is a content change.
func TestLogContentHashTracksNewDays(t *testing.T) {
base := `[] level=ERROR run=aaaa session.id=ses_abc123 messageID=msg_zzz999 error="Not Found"` + "\n"
l := NewLogIngester()
day1, err := l.Ingest(writeTempLog(t, `timestamp=2026-10-01T00:00:00.000Z `+base))
if err != nil {
t.Fatal(err)
}
day2, err := l.Ingest(writeTempLog(t, `timestamp=2026-10-02T12:34:56.789Z `+base))
if err != nil {
t.Fatal(err)
}
if day1.ContentHash == day2.ContentHash {
t.Fatal("hash should change when the same error recurs on a new day")
}
}
// The digest must say when an error happened. A signature with volatile values
// stripped cannot distinguish a fixed failure from a live one.
func TestLogDigestKeepsDates(t *testing.T) {
line := `[] level=ERROR run=aaaa session.id=ses_abc123 messageID=msg_zzz999 error="Not Found"`
content := "" +
`timestamp=2026-10-01T00:00:00.000Z ` + line + "\n" +
`timestamp=2026-10-02T12:34:56.789Z ` + line + "\n" +
`timestamp=2026-10-02T12:35:00.000Z level=INFO run=cccc message="unrelated"` + "\n"
r, err := NewLogIngester().Ingest(writeTempLog(t, content))
if err != nil {
t.Fatal(err)
}
want := `2026-10-01..2026-10-02 [] level=ERROR run=<RUN> session.id=<SES> messageID=<MSG> error="Not Found"`
if r.Content != want {
t.Fatalf("content=%q, want %q", r.Content, want)
}
if got, wantSummary := r.Summary, "levels: E2 W0 | err: "+want; got != wantSummary {
t.Fatalf("summary=%q, want %q", got, wantSummary)
}
// A single-day error renders one date, not a range.
single, err := NewLogIngester().Ingest(writeTempLog(t, `timestamp=2026-10-03T05:00:00.000Z `+line+"\n"))
if err != nil {
t.Fatal(err)
}
if single.Content != `2026-10-03 [] level=ERROR run=<RUN> session.id=<SES> messageID=<MSG> error="Not Found"` {
t.Fatalf("single-day content=%q", single.Content)
}
}
+14
View File
@@ -19,5 +19,19 @@ func Reconcile(kdb *db.KnoxDB) (int, int, error) {
if err != nil {
return 0, 0, fmt.Errorf("auto-thread: %w", err)
}
// Replicated threads are applied last: they carry authored titles and
// motivations, which must win over anything the heuristic just derived.
if applied, err := kdb.ProjectThreads(); err != nil {
return created, linked, fmt.Errorf("project threads: %w", err)
} 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
}