49e39aac44
Threads are authored as well as derived, so a peer could never learn about one:
the title someone typed exists nowhere in the log. The replica had 8 threads
against the laptop's 38, and 21 of those were authored.
Identity is a node-generated uid, not the integer id (local, collides across
nodes) and not cluster_key (auto-created clusters only; 11 authored threads had
none). Every write emits one observation keyed by sha256('thread:'+uid), so
threads ride the existing log instead of adding a second replication mechanism.
Reconcile projects the newest document per uid, after the auto-threader, because
authored titles must win over derived ones.
Two bugs the tests caught:
- locally created threads never set threads.hcl, so the LWW guard let any
incoming document win, including older ones;
- projection cleared cluster_key when a document carried none, which broke the
fallback that stops the same cluster arriving twice (producing duplicates).
Adds 'knox thread emit-all' to backfill existing threads.
Links (thread membership) are not replicated yet: peers receive threads without
their members. Follow-up.
285 lines
9.2 KiB
Go
285 lines
9.2 KiB
Go
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"`
|
|
}
|
|
|
|
// 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,'')
|
|
FROM threads WHERE id=?`, id,
|
|
).Scan(&d.UID, &d.ClusterKey, &d.Title, &d.Motivation, &d.Status, &d.Priority, &d.Tags, &d.Summary, &d.ResolvedAt)
|
|
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, ¤tHCL)
|
|
if err == sql.ErrNoRows && d.ClusterKey != "" {
|
|
err = k.db.QueryRow(`SELECT id, COALESCE(hcl,0) FROM threads WHERE cluster_key=?`, d.ClusterKey).Scan(&id, ¤tHCL)
|
|
}
|
|
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, hcl, provenance)
|
|
VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
|
|
d.UID, d.Title, d.Motivation, status, priority, d.Tags, d.ClusterKey, d.Summary, d.ResolvedAt, 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=?, 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)
|
|
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
|
|
}
|