mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-16 00:12:06 +00:00
Part 1 of #2107, scoped as discussed there: the backfill on its own, no catalogue promotion. ## Problem Ingest decides a GRP_TXT's channel and a transport packet's region scope once, at insert time. A row stored before its key was known keeps `channel_hash = 'enc_XX'` / `scope_name = ''` forever, even after the key is added — via `hashChannels` plus a restart, or at runtime when the `autoRegionKeys` tier picks up a newly declared region. On live.saarmesh.de we have been closing that gap with an out-of-tree script that rewrites the DB and restarts the container; this moves it into the ingestor and removes the restart. ## What this does **Ingestor** — `cmd/ingestor/key_backfill.go` - Runs after the write path is ready, and again whenever the key set grows (kicked after every `autoRegionKeys` refresh; a no-op when nothing is new). - Touches **only unresolved rows**: `enc_*` GRP_TXT and transport rows with `scope_name = ''`. Every `UPDATE` carries the unresolved value in its `WHERE`, so a row resolved meanwhile by live ingest keeps its value. A decrypted channel or named scope is never rewritten. - **Same decision as ingest**: `DecodePacket` with the full channel key map → `PayloadJSON`, and `regionKeySnapshot.match()` with the full snapshot — including abstaining on an ambiguous collision (#1609). The scope-match counters are not touched; they describe live traffic. - **Bounded**: each batch covers a fixed window of 5000 transmission ids. Unresolved rows are sparse (hundreds in a million), and the ingestor has a single SQLite connection, so a "next N matching rows" query would scan most of the table in one statement while ingest waits. A fixed id window keeps every read a short primary-key range scan. The writer is yielded between windows. - **Resumable and transactional**: one transaction per window holds the rewrites, their change-feed rows and the advanced cursor (`key_backfill_state`). A cancelled or crashed run resumes at its last commit; nothing is applied twice. - **Key-set growth**: a run is tied to the fingerprint of the key set it started with. If the set changes mid-run, the run restarts from the beginning, so a key added halfway still sees all of history. Each key gets one complete pass (`key_backfill_done`); a restart with an unchanged key set does no work. A key that leaves the set forgets its pass and is replayed if it returns. - **Derived field**: a named ADVERT fills `nodes.default_scope` / `inactive_nodes.default_scope` only where it is still empty. A known `default_scope` is newer evidence than a backfilled advert and is never overwritten. **Change feed** — `internal/dbschema/key_backfill.go`, `cmd/server/tx_rewrite_feed.go` - Each rewrite appends a row to `tx_rewrite_feed` in the same transaction as the rewrite. - The server tails it exactly like `advert_route_evidence`: cursor captured before `Load`, absent table re-probed (not required by `AssertReady`, so an older ingestor simply means no feed), polled from `IngestNewObservations`. It refreshes `DecodedJSON` / `ScopeName` of loaded transmissions, resets the `ParsedDecoded` cache, recharges tracked bytes, and invalidates the channel caches. **No restart needed.** - The feed carries only the transmission id; current values are read from `transmissions`, so replaying a row is harmless. Rows older than 24h are pruned. ## Tests Ingestor (`key_backfill_test.go`) — fixtures are real wire frames: GRP_TXT encrypted AES-128-ECB with the firmware MAC, transport frames with the real region HMAC. - decrypts only unresolved rows; already-decrypted and unknown-key rows untouched - backfilled `decoded_json` / `channel_hash` are byte-identical to what `BuildPacketData` stores at ingest - unique match named; a constructed two-name collision on the same payload stays unmatched; named and non-transport rows untouched - ingest scope-match counters unchanged - ADVERT fills only an empty `default_scope` - idempotent: second pass writes nothing, done keys recorded, state cleared - cancel between commits → resume from the committed cursor, every row exactly once, in order - stale run fingerprint (key added mid-run) → restart reaches rows below the old cursor - a later key only adds its own rows; a removed key is replayed over the gap when it returns - a row resolved between decide and commit keeps its value and gets no feed entry - channel hash byte derivation matches the builtin Public key (0x11) - old feed rows pruned Server (`tx_rewrite_feed_test.go`) - rewrite reaches the loaded store through the normal `IngestNewObservations` poll, including a previously parsed `ParsedDecoded` (verified to fail without the `sync.Once` reset) - cursor starts at the load watermark - absent feed is a no-op and is picked up once created, without restart - failed read keeps the cursor and retries - feed row for an unloaded transmission advances the cursor and is ignored `gofmt` clean, `go vet` clean, no `go.mod` / `go.sum` changes. ## Validation against production data Ran the backfill on a snapshot of live.saarmesh.de taken **before** last night's run of our out-of-tree script (13,100 unresolved rows, 164 channel keys, 24 region keys incl. 2 derived), with the current config. It rewrote **the same 31 transmissions with the same channel names** as the script did on production (compared by id), named 0 scopes (script: 0), and a second pass wrote nothing. Browser validation (AGENTS rule 2): this changes no UI. The visible effect — a decrypted message or named scope appearing without a restart — is covered by the server feed tests; I have not yet run it against a deployed instance. ## Notes for review - Window size (5000 ids), inter-batch yield (10 ms) and feed retention (24h) are constants for now; per rule 8 they can move to config/customizer later if anyone needs to tune them. - `client_rx_observations.scope_name` is not backfilled here; happy to add it in a follow-up if wanted. - The orphaned "scope-repair" mention in `region_keys.go`'s `scopeMatch.Candidates` comment predates this PR; I left it alone. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01BKaogNXgy8dEQruqzR5foP --------- Co-authored-by: SaarMesh-Bot <300107934+SaarMesh-Bot@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
119 lines
3.3 KiB
Go
119 lines
3.3 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"sync"
|
|
)
|
|
|
|
// tx_rewrite_feed (#2107) is the ingestor's change feed for transmissions it
|
|
// rewrote in place: a GRP_TXT it can now decrypt, a transport scope it can now
|
|
// name (cmd/ingestor/key_backfill.go). IngestNewFromDB only ever looks at
|
|
// id > maxTxID, so without this feed a rewritten row stayed stale in memory
|
|
// until the next restart.
|
|
//
|
|
// Same shape as advert_route_evidence: the table is optional (an older
|
|
// ingestor never creates it), so absence is re-probed rather than cached, and
|
|
// the server tails it with its own cursor captured before Load. A feed row
|
|
// carries only the transmission id; the current values are read from
|
|
// transmissions, so replaying a row is harmless and the newest write wins.
|
|
|
|
// txRewriteFeedPresent reports whether the ingestor has created the feed.
|
|
func (db *DB) txRewriteFeedPresent() bool {
|
|
if db == nil || db.conn == nil {
|
|
return false
|
|
}
|
|
if db.txRewriteFeedTable.Load() {
|
|
return true
|
|
}
|
|
var exists int
|
|
if err := db.conn.QueryRow(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='tx_rewrite_feed'`).Scan(&exists); err != nil {
|
|
return false
|
|
}
|
|
db.txRewriteFeedTable.Store(true)
|
|
return true
|
|
}
|
|
|
|
// pollTxRewrites applies up to limit feed rows to the in-memory store. A
|
|
// transmission the store does not hold (evicted, or outside the loaded
|
|
// window) is skipped: if it is ever loaded again it is read fresh from the DB.
|
|
// A failed read leaves the cursor where it was, so the next poll retries.
|
|
func (s *PacketStore) pollTxRewrites(limit int) error {
|
|
s.txRewriteMu.Lock()
|
|
defer s.txRewriteMu.Unlock()
|
|
if !s.db.txRewriteFeedPresent() {
|
|
return nil
|
|
}
|
|
if limit <= 0 || limit > 500 {
|
|
limit = 500
|
|
}
|
|
scopeCol := "NULL"
|
|
if s.db.hasScopeName {
|
|
scopeCol = "t.scope_name"
|
|
}
|
|
rows, err := s.db.conn.Query(`
|
|
SELECT f.id, f.tx_id, t.decoded_json, `+scopeCol+`
|
|
FROM tx_rewrite_feed f LEFT JOIN transmissions t ON t.id = f.tx_id
|
|
WHERE f.id > ? ORDER BY f.id LIMIT ?`, s.txRewriteCursor, limit)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
type rewrite struct {
|
|
id int64
|
|
txID int
|
|
decoded sql.NullString
|
|
scope sql.NullString
|
|
}
|
|
var batch []rewrite
|
|
for rows.Next() {
|
|
var r rewrite
|
|
if err := rows.Scan(&r.id, &r.txID, &r.decoded, &r.scope); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
batch = append(batch, r)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil || len(batch) == 0 {
|
|
return err
|
|
}
|
|
|
|
channelChanged := false
|
|
s.mu.Lock()
|
|
for _, r := range batch {
|
|
s.txRewriteCursor = r.id
|
|
tx := s.byTxID[r.txID]
|
|
if tx == nil {
|
|
continue
|
|
}
|
|
if r.decoded.Valid && r.decoded.String != tx.DecodedJSON {
|
|
tx.DecodedJSON = r.decoded.String
|
|
// ParsedDecoded caches behind a sync.Once; reset both under the
|
|
// write lock so the next reader parses the new JSON.
|
|
tx.decodedOnce = sync.Once{}
|
|
tx.parsedDecoded = nil
|
|
s.trackedBytes += rechargeTx(tx)
|
|
if tx.PayloadType != nil && *tx.PayloadType == PayloadGRP_TXT {
|
|
channelChanged = true
|
|
}
|
|
}
|
|
if s.db.hasScopeName && r.scope.Valid && (tx.ScopeName == nil || *tx.ScopeName != r.scope.String) {
|
|
v := r.scope.String
|
|
tx.ScopeName = &v
|
|
}
|
|
}
|
|
s.mu.Unlock()
|
|
|
|
if channelChanged {
|
|
s.invalidateCachesFor(cacheInvalidation{hasChannelData: true})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *PacketStore) refreshTxRewrites() {
|
|
if err := s.pollTxRewrites(500); err != nil {
|
|
log.Printf("[store] tx rewrite feed poll: %v", err)
|
|
}
|
|
}
|