Files
knox/internal/metrics/metrics.go
david e3bbeabb6b
build / test (push) Successful in 3m19s
build / image (push) Successful in 18s
feat: always-on remote node — MCP over HTTP, TLS/token, Docker, CI, sqlc (#9)
Deploys knox as a headless, always-on replica so agents keep their memory when the laptop is off.

Closes #8. **Supersedes #5** (its hardening commit is merged in here; close #5 after this lands).

## What changed

**MCP transport + SDK**
- Moves from `mark3labs/mcp-go` v0.17 (stdio only, five releases behind) to the official `modelcontextprotocol/go-sdk` v1.8. Tool inputs are typed structs, so schemas are generated instead of hand-built.
- Adds `knox mcp --http` (Streamable HTTP). stdio remains the default.

**Transport security without a public name**
- `KNOX_AUTH_TOKEN` guards gossip and MCP HTTP; `KNOX_TLS_CERT/KEY` serve TLS; `knox tls init` mints a self-signed cert whose SANs are whatever addresses clients dial. Verified: 401 without the token, 200 with, cert valid for the overlay IP.

**Daemon hygiene**
- SIGTERM shuts down the gossip and metrics servers.
- `--version` reports the VCS revision.
- `KNOX_LOCAL_SOURCES=none` makes a node ingest nothing but still derive.
- Default watch dirs skip paths that do not exist.

**Deployment topology fixes** (all found by actually running a replica)
- `KNOX_LISTEN_ADDR` split from `KNOX_PEER_ADDR`: a container cannot bind the host's overlay IP, and previously the gossip server silently failed to start.
- Reconcile now fires on push and on startup, not only on pull. Three separate bugs left `entries` empty on a push-only node.
- Pushes batch by byte budget, not just row count — 500 content-heavy rows exceeded the 4 MiB body limit and the log stalled permanently at 3,000 observations.
- Threads and snippets derive on replicas: gating them with the ingesters left the server holding 11.5k observations and 4.9k entries but 2 of 28 threads.

**Packaging + CI**
- Multi-stage Dockerfile (static, non-root, `/data` volume).
- Gitea workflow builds on the dhg.lol daemon through the runner socket, tags `:latest` + `:<sha>`, and restarts the stack when installed. BuildKit cache mounts keep module downloads warm.

**sqlc pilot**
- Schema extracted to `internal/db/schema.sql` (embedded); read paths behind the MCP tools are generated.
- The pilot found real drift: `entries.created_at` existed only as a runtime `ALTER`. It is now declared in the schema, and `sqlcdb_pilot_test.go` fails if generated code disagrees with `db.Open`.
- FTS5 stays hand-written: sqlc ignores `CREATE VIRTUAL TABLE`, so `MATCH`/`bm25` cannot be generated.

## Verification
- `go vet ./...`, `go test ./...`, `gofmt` clean
- `scripts/conformance.sh` — official MCP suite, exit 0 against `conformance-baseline.yml` (documents the capabilities knox does not implement: resources, prompts, completions, fixture tools)
- Live: both containers healthy on dhg.lol, ports bound only to the ZeroTier address, 11,553 observations / 4,943 entries replicated and reconciled

## Deploy
Infrastructure lives in `tf-net/apps/knox` (separate repo); this branch is what is currently running in production.

Reviewed-on: #9
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 02:14:33 +00:00

165 lines
5.9 KiB
Go

// Package metrics exposes Prometheus-format metrics for a knox node.
//
// Gauges are recomputed from the database on each scrape (cheap aggregates);
// gossip counters are in-memory and incremented as the daemon exchanges data
// with peers. The registry also gains the standard Go runtime and process
// collectors from prometheus/client_golang.
package metrics
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/david/knox/internal/db"
)
// Metrics holds the gossip event counters (incremented by watch) and the
// scrape-time gauges derived from the database (refreshed on each scrape).
type Metrics struct {
// Gossip counters (live).
pullsTotal prometheus.Counter
pushesTotal prometheus.Counter
obsPulledTotal prometheus.Counter
obsPushedTotal prometheus.Counter
errorsTotal prometheus.Counter
// Snapshot gauges (updated per scrape).
observationsGauge *prometheus.GaugeVec
entriesGauge prometheus.Gauge
projectsGauge prometheus.Gauge
sessionsGauge prometheus.Gauge
pendingReflections prometheus.Gauge
peersGauge prometheus.Gauge
threadsByStatus *prometheus.GaugeVec
byOriginNode *prometheus.GaugeVec
knowledgeVector *prometheus.GaugeVec
observationsLast24h prometheus.Gauge
registry *prometheus.Registry
kdb *db.KnoxDB
}
// New builds the metrics registry bound to a knowledge index.
func New(kdb *db.KnoxDB, nodeName string) *Metrics {
reg := prometheus.NewRegistry()
m := &Metrics{
registry: reg,
kdb: kdb,
}
// Node identity aids scraping: which node produced this output.
m.nodeInfo(kdb.NodeID(), nodeName)
m.pullsTotal = newCounter(reg, "knox_gossip_pulls_total", "Peer pull round-trips completed.")
m.pushesTotal = newCounter(reg, "knox_gossip_pushes_total", "Peer push round-trips completed.")
m.obsPulledTotal = newCounter(reg, "knox_gossip_observations_pulled_total", "Observations received from peers.")
m.obsPushedTotal = newCounter(reg, "knox_gossip_observations_pushed_total", "Observations sent to peers.")
m.errorsTotal = newCounter(reg, "knox_gossip_errors_total", "Gossip errors (ping/pull/push failures).")
m.observationsGauge = newGaugeVec(reg, "knox_observations", "Observation log size.", "source_id")
m.observationsLast24h = newGauge(reg, "knox_observations_last_24h", "Observations collected in the last 24h.")
m.entriesGauge = newGauge(reg, "knox_entries", "Materialized entry cache size.")
m.projectsGauge = newGauge(reg, "knox_projects", "Distinct projects in the entry cache.")
m.sessionsGauge = newGauge(reg, "knox_sessions", "Sessions tracked.")
m.pendingReflections = newGauge(reg, "knox_pending_reflections", "Sessions awaiting reflection.")
m.peersGauge = newGauge(reg, "knox_peers", "Known peer nodes.")
m.threadsByStatus = newGaugeVec(reg, "knox_threads", "Threads by status.", "status")
m.byOriginNode = newGaugeVec(reg, "knox_observations_by_node", "Observations per originating node.", "node_id")
m.knowledgeVector = newGaugeVec(reg, "knox_knowledge_max_hcl", "Highest HCL seen per originating node.", "node_id")
// Go runtime + process collectors come from the official library.
reg.MustRegister(prometheus.NewGoCollector())
reg.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
return m
}
func newCounter(reg *prometheus.Registry, name, help string) prometheus.Counter {
c := prometheus.NewCounter(prometheus.CounterOpts{Name: name, Help: help})
reg.MustRegister(c)
return c
}
func newGauge(reg *prometheus.Registry, name, help string) prometheus.Gauge {
g := prometheus.NewGauge(prometheus.GaugeOpts{Name: name, Help: help})
reg.MustRegister(g)
return g
}
func newGaugeVec(reg *prometheus.Registry, name, help string, labels ...string) *prometheus.GaugeVec {
g := prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: name, Help: help}, labels)
reg.MustRegister(g)
return g
}
func (m *Metrics) nodeInfo(nodeID, name string) {
info := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "knox_node_info",
Help: "Node identity (always 1).",
ConstLabels: prometheus.Labels{
"node_id": nodeID,
"name": name,
},
})
m.registry.MustRegister(info)
info.Set(1)
}
// Capture refresh the DB-derived gauges from a fresh snapshot.
func (m *Metrics) Capture(s *db.MetricsSnapshot) {
m.observationsGauge.Reset()
for src, n := range s.BySource {
m.observationsGauge.WithLabelValues(src).Set(float64(n))
}
m.observationsLast24h.Set(float64(s.ObservationsLast24h))
m.entriesGauge.Set(float64(s.Entries))
m.projectsGauge.Set(float64(s.Projects))
m.sessionsGauge.Set(float64(s.Sessions))
m.pendingReflections.Set(float64(s.PendingReflections))
m.peersGauge.Set(float64(s.Peers))
m.threadsByStatus.Reset()
for st, n := range s.ThreadsByStatus {
m.threadsByStatus.WithLabelValues(st).Set(float64(n))
}
m.byOriginNode.Reset()
for nid, n := range s.ByOriginNode {
m.byOriginNode.WithLabelValues(nid).Set(float64(n))
}
m.knowledgeVector.Reset()
for nid, hcl := range s.KnowledgeVector {
m.knowledgeVector.WithLabelValues(nid).Set(float64(hcl))
}
}
// IncrementPull records a completed pull and its accepted observation count.
func (m *Metrics) IncrementPull(newObs int) {
m.pullsTotal.Inc()
m.obsPulledTotal.Add(float64(newObs))
}
// IncrementPush records a completed push and its accepted observation count.
func (m *Metrics) IncrementPush(newObs int) {
m.pushesTotal.Inc()
m.obsPushedTotal.Add(float64(newObs))
}
// IncrementErrors counts a failed gossip attempt.
func (m *Metrics) IncrementErrors() { m.errorsTotal.Inc() }
// Handler returns the /metrics scrape handler. On each scrape it refreshes
// DB-derived gauges before rendering (cost is a few cheap aggregates).
func (m *Metrics) Handler() http.Handler {
h := promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s, err := m.kdb.MetricsSnapshot(); err == nil {
m.Capture(s)
}
h.ServeHTTP(w, r)
})
}