From 2bb872ec85fe20b696688776ad7dfbb190dea791 Mon Sep 17 00:00:00 2001 From: zfouts Date: Tue, 1 Dec 2026 15:42:04 -0600 Subject: [PATCH 1/3] fix(ingestor): resolve both visits of a TRACE route that revisits a node (#2520) resolvePathWithContext excluded every node already on the path, so the second A of a TRACE route A -> B -> A was stored as null in observations.resolved_path. The firmware allows the revisit on purpose: Packet::calculatePacketHash mixes path_len into a TRACE hash ("TRACE packets can revisit same node on return path"), while every other packet's hash ignores the path, so wasSeen keeps a node from forwarding it twice. packetpath.PathMayRevisit(payloadType) is the shared rule (TRACE only). With it, resolvePathWithContext excludes only the previous hop (a radio does not hear its own transmission) and still anchors on it through the neighbour graph. Non-TRACE packets keep the one-visit exclusion. Co-Authored-By: Claude Opus 5.5 --- cmd/ingestor/db.go | 4 +- cmd/ingestor/path_resolver.go | 12 ++- cmd/ingestor/resolved_path_test.go | 8 +- cmd/ingestor/trace_revisit_test.go | 142 +++++++++++++++++++++++++++++ internal/packetpath/route.go | 10 ++ internal/packetpath/route_test.go | 11 +++ 6 files changed, 180 insertions(+), 7 deletions(-) create mode 100644 cmd/ingestor/trace_revisit_test.go diff --git a/cmd/ingestor/db.go b/cmd/ingestor/db.go index 2f09caf63..b6b1141bc 100644 --- a/cmd/ingestor/db.go +++ b/cmd/ingestor/db.go @@ -1265,7 +1265,8 @@ func (s *Store) InsertTransmission(data *PacketData) (bool, error) { // the ingestor now. Per #1560: use the context-aware resolver so // 1-byte prefix collisions are disambiguated via NeighborGraph // adjacency (anchored on from_pubkey for ADVERTs, previous hop - // otherwise). Empty resolved JSON → NULL via nilIfEmpty. + // otherwise). A TRACE route may revisit a node (#2520). Empty resolved + // JSON → NULL via nilIfEmpty. hops := parsePathArray(data.PathJSON) prefixIdx := s.prefixIdx.load() resolved := resolvePathWithContext( @@ -1273,6 +1274,7 @@ func (s *Store) InsertTransmission(data *PacketData) (bool, error) { strings.ToLower(data.FromPubkey), s.neighborGraph.load(), prefixIdx, + packetpath.PathMayRevisit(byte(data.PayloadType)), ) resolvedJSON := marshalResolvedPath(resolved) diff --git a/cmd/ingestor/path_resolver.go b/cmd/ingestor/path_resolver.go index 06cb92ac4..1414b5c8c 100644 --- a/cmd/ingestor/path_resolver.go +++ b/cmd/ingestor/path_resolver.go @@ -131,7 +131,7 @@ func loadNeighborGraph(db *sql.DB) (*NeighborGraph, error) { // // exclude is a set of pubkeys to discard from the candidate pool // (typically the prior hops already resolved on the path — a packet -// does not revisit a node). +// does not revisit a node, except a TRACE: see resolvePathWithContext). // // Behavior matrix: // @@ -186,7 +186,12 @@ func resolveHopWithContext(hop string, anchor string, graph *NeighborGraph, idx // excluded from later candidate pools so the walk doesn't revisit a // node. Returns a `[]*string` shape compatible with // marshalResolvedPath (and the all-nil clobber-guard from PR #1548). -func resolvePathWithContext(hops []string, fromPubkey string, graph *NeighborGraph, idx prefixIndex) []*string { +// +// allowRevisit (packetpath.PathMayRevisit: TRACE only, #2520) lifts the +// one-visit rule: only the previous hop is excluded, since a radio does +// not hear its own transmission and so a node is never its own next hop. +// Anchoring on the previous hop is unchanged. +func resolvePathWithContext(hops []string, fromPubkey string, graph *NeighborGraph, idx prefixIndex, allowRevisit bool) []*string { if len(hops) == 0 { return nil } @@ -202,6 +207,9 @@ func resolvePathWithContext(hops []string, fromPubkey string, graph *NeighborGra for i, hop := range hops { r := resolveHopWithContext(hop, prevAnchor, graph, idx, seen) out[i] = r + if allowRevisit { + clear(seen) + } if r != nil { lc := strings.ToLower(*r) seen[lc] = struct{}{} diff --git a/cmd/ingestor/resolved_path_test.go b/cmd/ingestor/resolved_path_test.go index 308868506..f1f98e28c 100644 --- a/cmd/ingestor/resolved_path_test.go +++ b/cmd/ingestor/resolved_path_test.go @@ -235,7 +235,7 @@ func TestResolvePathWithContext_TwoHopChainAnchoredOnFromNode(t *testing.T) { g.AddEdge(A, B) g.AddEdge(B, C) - got := resolvePathWithContext([]string{"5c", "5c"}, A, g, idx) + got := resolvePathWithContext([]string{"5c", "5c"}, A, g, idx, false) if len(got) != 2 { t.Fatalf("len(got)=%d, want 2 (raw=%v)", len(got), got) } @@ -274,7 +274,7 @@ func TestResolvePathWithContext_AdvertAnchoring(t *testing.T) { g := NewNeighborGraph() g.AddEdge(A, B) // only B is adjacent to A among the 5c candidates - got := resolvePathWithContext([]string{"5c"}, A, g, idx) + got := resolvePathWithContext([]string{"5c"}, A, g, idx, false) if len(got) != 1 { t.Fatalf("len(got)=%d, want 1", len(got)) } @@ -289,7 +289,7 @@ func TestResolvePathWithContext_AdvertAnchoring(t *testing.T) { func TestResolvePathWithContext_RegressionMultiByteStillWorks(t *testing.T) { idx, _, _, _, D, E := build5NodeAmbiguousIndex() // dd and ee are unique 1-byte prefixes — naive path still works. - got := resolvePathWithContext([]string{"dd", "ee"}, "", nil, idx) + got := resolvePathWithContext([]string{"dd", "ee"}, "", nil, idx, false) if len(got) != 2 { t.Fatalf("len(got)=%d, want 2", len(got)) } @@ -308,7 +308,7 @@ func TestResolvePathWithContext_RegressionMultiByteStillWorks(t *testing.T) { // → COALESCE preserves existing). func TestResolvePathWithContext_AllNilContractPreserved(t *testing.T) { // Empty index → every hop nil. - got := resolvePathWithContext([]string{"5c", "dd"}, "", nil, prefixIndex{}) + got := resolvePathWithContext([]string{"5c", "dd"}, "", nil, prefixIndex{}, false) if len(got) != 2 { t.Fatalf("len(got)=%d, want 2", len(got)) } diff --git a/cmd/ingestor/trace_revisit_test.go b/cmd/ingestor/trace_revisit_test.go new file mode 100644 index 000000000..47d31a062 --- /dev/null +++ b/cmd/ingestor/trace_revisit_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "database/sql" + "path/filepath" + "testing" + + "github.com/meshcore-analyzer/packetpath" +) + +// #2520: a TRACE route may list the same repeater more than once (A → B → A, +// out and back). The firmware allows it on purpose: Packet::calculatePacketHash +// mixes path_len into a TRACE hash ("TRACE packets can revisit same node on +// return path"), so the second visit is not a wasSeen duplicate. Every other +// packet's hash ignores the path, so a node forwards it once and the +// one-visit rule stays. + +func traceRevisitIndex() (idx prefixIndex, A, B string) { + A = "aa000000000000000000000000000000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + B = "bb000000000000000000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + return prefixIndex{"aa": {A}, "bb": {B}, A: {A}, B: {B}}, A, B +} + +func TestResolvePathWithContext_TraceRevisitResolvesBothVisits(t *testing.T) { + idx, A, B := traceRevisitIndex() + got := resolvePathWithContext([]string{"aa", "bb", "aa"}, "", nil, idx, true) + want := []string{A, B, A} + for i := range want { + if got[i] == nil || *got[i] != want[i] { + t.Errorf("TRACE hop[%d]: want %s, got %v", i, want[i], deref(got[i])) + } + } +} + +func TestResolvePathWithContext_NonTraceStillVisitsOnce(t *testing.T) { + idx, A, B := traceRevisitIndex() + got := resolvePathWithContext([]string{"aa", "bb", "aa"}, "", nil, idx, false) + if got[0] == nil || *got[0] != A || got[1] == nil || *got[1] != B { + t.Fatalf("hops 0,1: want %s,%s, got %v,%v", A, B, deref(got[0]), deref(got[1])) + } + if got[2] != nil { + t.Errorf("non-TRACE hop[2]: a node forwards a packet once, want , got %s", *got[2]) + } +} + +// A revisit with a colliding prefix still needs the neighbour graph: the +// previous hop anchors it exactly as for any other hop. +func TestResolvePathWithContext_TraceRevisitAnchorsOnPreviousHop(t *testing.T) { + idx, _, B, _, D, _ := build5NodeAmbiguousIndex() + g := NewNeighborGraph() + g.AddEdge(D, B) // B is D's only 5c neighbour + + got := resolvePathWithContext([]string{"dd", "5c", "dd", "5c"}, "", g, idx, true) + want := []string{D, B, D, B} + for i := range want { + if got[i] == nil || *got[i] != want[i] { + t.Errorf("TRACE hop[%d]: want %s, got %v", i, want[i], deref(got[i])) + } + } + + flood := resolvePathWithContext([]string{"dd", "5c", "dd", "5c"}, "", g, idx, false) + if flood[2] != nil || flood[3] != nil { + t.Errorf("non-TRACE revisits stay unresolved, got %v,%v", deref(flood[2]), deref(flood[3])) + } +} + +// A radio does not hear its own transmission, so a node is never its own +// next hop, TRACE or not. +func TestResolvePathWithContext_TraceNeverRepeatsTheAdjacentHop(t *testing.T) { + idx, A, _ := traceRevisitIndex() + got := resolvePathWithContext([]string{"aa", "aa"}, "", nil, idx, true) + if got[0] == nil || *got[0] != A { + t.Fatalf("hop[0]: want %s, got %v", A, deref(got[0])) + } + if got[1] != nil { + t.Errorf("hop[1]: A cannot relay to itself, want , got %s", *got[1]) + } +} + +// End to end through InsertTransmission: a TRACE stores both visits in +// observations.resolved_path, a non-TRACE packet with the same path does not. +func TestInsertTransmissionTraceRevisitWritesBothVisits(t *testing.T) { + store, err := OpenStore(filepath.Join(t.TempDir(), "ingest.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + defer store.Close() + + if _, err := store.db.Exec( + `INSERT INTO nodes (public_key, name) VALUES (?, ?), (?, ?)`, + "aaaaaaaaaa", "rpt-a", "bbbbbbbbbb", "rpt-b", + ); err != nil { + t.Fatal(err) + } + if err := store.UpsertObserver("obs-1", "observer-1", "", nil); err != nil { + t.Fatalf("UpsertObserver: %v", err) + } + if err := store.RefreshPrefixIndex(); err != nil { + t.Fatalf("RefreshPrefixIndex: %v", err) + } + + stored := func(hash string, payloadType int) []*string { + t.Helper() + pkt := &PacketData{ + RawHex: "deadbeef", + Timestamp: "2026-06-01T00:00:00Z", + ObserverID: "obs-1", + Hash: hash, + RouteType: packetpath.RouteDirect, + PayloadType: payloadType, + PathJSON: `["aa","bb","aa"]`, + DecodedJSON: "{}", + } + if _, err := store.InsertTransmission(pkt); err != nil { + t.Fatalf("InsertTransmission %s: %v", hash, err) + } + var rp sql.NullString + if err := store.db.QueryRow( + `SELECT resolved_path FROM observations WHERE transmission_id = (SELECT id FROM transmissions WHERE hash = ?)`, + hash, + ).Scan(&rp); err != nil { + t.Fatalf("query %s: %v", hash, err) + } + got := unmarshalResolvedPathLocal(rp.String) + if len(got) != 3 { + t.Fatalf("%s resolved_path: want 3 hops, got %q", hash, rp.String) + } + return got + } + + trace := stored("h-2520-trace", packetpath.PayloadTRACE) + for i, want := range []string{"aaaaaaaaaa", "bbbbbbbbbb", "aaaaaaaaaa"} { + if trace[i] == nil || *trace[i] != want { + t.Errorf("TRACE resolved_path[%d]: want %s, got %v", i, want, deref(trace[i])) + } + } + + txtMsg := stored("h-2520-txt", 0x02) + if txtMsg[2] != nil { + t.Errorf("non-TRACE resolved_path[2]: want null, got %s", *txtMsg[2]) + } +} diff --git a/internal/packetpath/route.go b/internal/packetpath/route.go index 87882ef16..b5dd04359 100644 --- a/internal/packetpath/route.go +++ b/internal/packetpath/route.go @@ -23,6 +23,16 @@ func PathBytesAreHops(payloadType byte) bool { return payloadType != PayloadTRACE } +// PathMayRevisit reports whether a packet's path can list the same node at +// more than one hop. Only a TRACE route can (A → B → A, out and back): +// Packet::calculatePacketHash mixes path_len into a TRACE hash ("TRACE packets +// can revisit same node on return path"), so a node's second visit is not a +// wasSeen duplicate. Every other packet's hash ignores the path, so a node +// forwards it once (firmware Mesh.cpp, wasSeen/markSeen). +func PathMayRevisit(payloadType byte) bool { + return payloadType == PayloadTRACE +} + // Payload types the route predicates below single out. const ( PayloadADVERT = 0x04 diff --git a/internal/packetpath/route_test.go b/internal/packetpath/route_test.go index 0bc46a5b5..72eab9884 100644 --- a/internal/packetpath/route_test.go +++ b/internal/packetpath/route_test.go @@ -72,3 +72,14 @@ func TestEmptyPathHeardOriginator(t *testing.T) { } } } + +func TestPathMayRevisit(t *testing.T) { + if !PathMayRevisit(PayloadTRACE) { + t.Error("PathMayRevisit(PayloadTRACE) should be true: a TRACE route can come back through a node") + } + for pt := byte(0); pt <= 0x0F; pt++ { + if pt != PayloadTRACE && PathMayRevisit(pt) { + t.Errorf("PathMayRevisit(0x%02X) should be false: a node forwards a non-TRACE packet once", pt) + } + } +} From 53cb489699e6bf1cd7ca7ce0062067b80a0daa84 Mon Sep 17 00:00:00 2001 From: zfouts Date: Tue, 1 Dec 2026 15:42:04 -0600 Subject: [PATCH 2/3] fix(hop-resolver): let inferPath place a node twice on a TRACE route (#2520) inferPath kept every node to one position, so on a TRACE route A -> B -> A the earlier A was left unassigned and flagged unreliable even when A is the only node with its prefix and 14 km from B. inferPath takes opts.allowRevisit: it skips the one-position bans and the cross-hop confidence bans, and the step cost forbids the same node only at the next hop. Geography and neighbour links still choose among nodes sharing a prefix; a revisit costs nothing extra. inferObservationPath takes the packet's payload_type and sets it for a TRACE (9); the packet detail pane and the map deep link pass it. Without the flag the behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 --- public/hop-resolver.js | 25 ++++++++++----- public/map.js | 2 +- public/packet-helpers.js | 5 ++- public/packets.js | 2 +- tests/unit/test-hop-path-detail.js | 21 +++++++++++++ tests/unit/test-hop-path-inference.js | 44 +++++++++++++++++++++++++++ 6 files changed, 88 insertions(+), 11 deletions(-) diff --git a/public/hop-resolver.js b/public/hop-resolver.js index 930b90b56..da9cdd957 100644 --- a/public/hop-resolver.js +++ b/public/hop-resolver.js @@ -331,7 +331,10 @@ window.HopResolver = (function() { // path as a whole instead, using two firmware facts (Mesh::routeRecvPacket, // wasSeen): a relayer appends its own hash, so the last hop is the one the // observer heard directly; and a node forwards a packet once, so it appears - // at most once in a path. + // at most once in a path. A TRACE is the exception (opts.allowRevisit): + // Packet::calculatePacketHash mixes path_len into its hash, so its route can + // come back through a node (A → B → A). Only the radio rule remains there: a + // node does not hear its own transmission, so it is never its own next hop. // // Each hop is either one of the located repeaters sharing its prefix, or // "unlisted": a node missing from the list or without GPS. With 1-byte @@ -399,18 +402,20 @@ window.HopResolver = (function() { } // steps[p][g][j * |C[p+g]| + l] = cost from candidate j at hop p to - // candidate l at hop p+g. Infinity for the same node twice. Computed once, + // candidate l at hop p+g. Infinity for the same node twice, or with + // allowRevisit for the same node at the next hop only. Computed once, // shared by every solve and the confidence pass. - function buildSteps(C) { + function buildSteps(C, allowRevisit) { const L = C.length; const steps = []; for (let p = 0; p < L; p++) { steps.push([null]); for (let g = 1; g <= MAX_GAP && p + g < L; g++) { const A = C[p], Bq = C[p + g], row = new Float64Array(A.length * Bq.length); + const sameBanned = !allowRevisit || g === 1; for (let j = 0; j < A.length; j++) { for (let l = 0; l < Bq.length; l++) { - row[j * Bq.length + l] = A[j].pubkey === Bq[l].pubkey ? Infinity : spanCost(A[j], Bq[l], g); + row[j * Bq.length + l] = sameBanned && A[j].pubkey === Bq[l].pubkey ? Infinity : spanCost(A[j], Bq[l], g); } } steps[p].push(row); @@ -544,6 +549,8 @@ window.HopResolver = (function() { * @param {{lat,lon}} [opts.origin] - the sender's position, when known * @param {Array} [opts.resolvedPath] - server-resolved pubkeys * aligned with hops; a non-null entry restricts that hop to that node + * @param {boolean} [opts.allowRevisit] - the path is a TRACE route, which + * may list a node at more than one hop (never at two adjacent hops) * @returns {Array} one entry per hop: { hop, name, pubkey, lat, lon, * located, unlisted, unreliable, ambiguous, confidence, candidates, * conflicts } — candidates sorted by confidence, located first; one the @@ -573,12 +580,14 @@ window.HopResolver = (function() { } // Keep each node to one position: when the best path uses a node twice, - // ban it from whichever of the two positions costs less to give up. + // ban it from whichever of the two positions costs less to give up. A + // TRACE route may revisit a node, so it skips this and the bans below. + const revisit = opts.allowRevisit === true; const bans = C.map(() => null); const banned = (i, pubkey) => bans.map((s, j) => j === i ? new Set([...(s || []), pubkey]) : s); - const steps = buildSteps(C); + const steps = buildSteps(C, revisit); let sol = solvePath(C, steps, start, end, bans); - for (let guard = 0; guard < L; guard++) { + for (let guard = 0; guard < L && !revisit; guard++) { const seenAt = new Map(); let dup = null; for (let i = 0; i < L && !dup; i++) { @@ -598,7 +607,7 @@ window.HopResolver = (function() { // For confidence, a node the path uses at one hop is no alternative at // another. The best path stays feasible, so the assignment is unchanged. const usedAt = new Map(); - sol.assign.forEach((k, i) => { if (k >= 0) usedAt.set(C[i][k].pubkey, i); }); + if (!revisit) sol.assign.forEach((k, i) => { if (k >= 0) usedAt.set(C[i][k].pubkey, i); }); const confidenceBans = C.map((c, i) => { const s = new Set(bans[i] || []); for (const pt of c) { diff --git a/public/map.js b/public/map.js index 47d9168b6..ca72fbc0d 100644 --- a/public/map.js +++ b/public/map.js @@ -1566,7 +1566,7 @@ const senderLat = decoded.lat != null ? decoded.lat : decoded.latitude; const senderLon = decoded.lon != null ? decoded.lon : decoded.longitude; const originPos = senderLat != null && senderLon != null ? { lat: senderLat, lon: senderLon } : null; - inferredHops = inferObservationPath(chosen, obsPos, originPos); + inferredHops = inferObservationPath(chosen, obsPos, originPos, pkt.payload_type); } catch (e) { console.warn('[deep-link] path inference failed', e); } diff --git a/public/packet-helpers.js b/public/packet-helpers.js index 64aea396b..3d3d72e2a 100644 --- a/public/packet-helpers.js +++ b/public/packet-helpers.js @@ -68,14 +68,17 @@ window.getParsedDecoded = function getParsedDecoded(p) { * @param {Object} obs - an observation (path_json, observer_id, resolved_path) * @param {{lat,lon}|null} observer - where its observer is, when known * @param {{lat,lon}|null} origin - where the sender is, when known + * @param {number} [payloadType] - the packet's payload_type; a TRACE (9) route + * may come back through a node (#2520), no other path visits one twice * @returns {Array} one inferPath entry per hop */ -window.inferObservationPath = function inferObservationPath(obs, observer, origin) { +window.inferObservationPath = function inferObservationPath(obs, observer, origin, payloadType) { return window.HopResolver.inferPath(window.getParsedPath(obs), { observer: observer, observerId: obs.observer_id, origin: origin, resolvedPath: window.getResolvedPath(obs), + allowRevisit: Number(payloadType) === 9, }); }; diff --git a/public/packets.js b/public/packets.js index 42a1d7c98..b922dcda3 100644 --- a/public/packets.js +++ b/public/packets.js @@ -3690,7 +3690,7 @@ const origin = senderLat != null && senderLon != null ? { lat: senderLat, lon: senderLon } : null; inferFor = o => { const [lat, lon] = observerPosition(o.observer_id); - return inferObservationPath(o, lat === null ? null : { lat, lon }, origin); + return inferObservationPath(o, lat === null ? null : { lat, lon }, origin, pkt.payload_type); }; pathEntries = inferFor(currentObs || pkt); if (observations.length > 1) aggregateEntries = inferFor(pkt); diff --git a/tests/unit/test-hop-path-detail.js b/tests/unit/test-hop-path-detail.js index e224538d6..2b6ae878a 100644 --- a/tests/unit/test-hop-path-detail.js +++ b/tests/unit/test-hop-path-detail.js @@ -338,6 +338,27 @@ const rowHtml = (html, dt) => { assert(route[2].resolved === false && route[2].gpsless === true && route[2].name === 'NO-GPS-66', 'an unplaced node stays named, without GPS'); } + console.log('\n=== a TRACE route may revisit a node (#2520) ==='); + { + const ctx = loadPage(); + // C-ONLY is the one "c7" node, ~13 km from B-MID. + const nodes = NODES.concat([{ public_key: pad('c700'), name: 'C-ONLY', role: 'repeater', lat: 40.25, lon: -99.85 }]); + ctx.HopResolver.init(nodes, { observers: OBSERVERS, iataCoords: {} }); + const obs = { observer_id: OBS, path_json: '["c7","b1b1","c7"]', resolved_path: null }; + const names = es => es.map(e => e.name || e.hop).join(' → '); + const trace = ctx.inferObservationPath(obs, { lat: 40.6, lon: -100 }, null, 9); + assert(trace[0].name === 'C-ONLY' && trace[2].name === 'C-ONLY' && !trace.some(e => e.unreliable), + 'inferObservationPath lets a TRACE (payload_type 9) visit a node twice (' + names(trace) + ')'); + const txt = ctx.inferObservationPath(obs, { lat: 40.6, lon: -100 }, null, 2); + assert(txt.filter(e => e.name === 'C-ONLY').length === 1 && txt.some(e => e.unreliable), + 'any other payload type keeps one visit per node (' + names(txt) + ')'); + + const src = fs.readFileSync(REPO_ROOT + '/public/packets.js', 'utf8'); + assert(/inferObservationPath\([^)]*pkt\.payload_type\)/.test(src), 'the packet detail passes the packet\'s payload type'); + const mapSrc = fs.readFileSync(REPO_ROOT + '/public/map.js', 'utf8'); + assert(/inferObservationPath\(chosen[^)]*pkt\.payload_type\)/.test(mapSrc), 'and so does the map deep link'); + } + console.log('\n=== map.js draws the inferred hops of the chosen observation ==='); { const src = fs.readFileSync(REPO_ROOT + '/public/map.js', 'utf8'); diff --git a/tests/unit/test-hop-path-inference.js b/tests/unit/test-hop-path-inference.js index 286dd06b4..87034ef30 100644 --- a/tests/unit/test-hop-path-inference.js +++ b/tests/unit/test-hop-path-inference.js @@ -173,6 +173,50 @@ console.log('\nTest 10: edge cases and output shape'); assert(HopResolver.inferPath(['78'], {})[0].unlisted, 'companions never appear as hops'); } +console.log('\nTest 10b: a TRACE route may come back through a node (#2520)'); +{ + // Firmware Packet::calculatePacketHash mixes path_len into a TRACE hash + // ("TRACE packets can revisit same node on return path"), so A → B → A is a + // real TRACE route. Every other packet visits a node once (Test 4). + const a = rpt('ac00' + '0'.repeat(60), 'A-ONLY', 40, -100); + const b = rpt('bc00' + '0'.repeat(60), 'B-14KM', 40.126, -100); // ~14 km north + HopResolver.init([a, b]); + HopResolver.setAffinity(null); + const obs = { observer: { lat: 39.95, lon: -100 } }; + + const flood = HopResolver.inferPath(['AC', 'BC', 'AC'], obs); + assert(flood.filter(e => pk(e) === a.public_key).length === 1, 'without allowRevisit, A takes one position'); + assert(flood.some(e => e.unlisted && e.unreliable), 'and the other is unreliable, as before'); + + const trace = HopResolver.inferPath(['AC', 'BC', 'AC'], Object.assign({ allowRevisit: true }, obs)); + assert(pk(trace[0]) === a.public_key && pk(trace[2]) === a.public_key, + 'with allowRevisit both AC hops are A — got ' + trace.map(e => e.name).join(',')); + assert(pk(trace[1]) === b.public_key, 'and the middle hop is B'); + assert(trace.every(e => !e.unlisted && !e.unreliable), 'no hop is unlisted or unreliable'); + assert(trace[0].confidence > 0.7 && trace[2].confidence > 0.7, + 'both visits are confident — ' + trace[0].confidence.toFixed(2) + ', ' + trace[2].confidence.toFixed(2)); + assert(trace[0].candidates.every(c => c.usedAt == null), 'and no candidate is marked as used elsewhere'); + + // A revisit costs nothing extra: geography still picks between nodes + // sharing the prefix, so a far-away AC does not win the return visit. + const far = rpt('ac11' + '0'.repeat(60), 'A-FAR', 42.7, -100); // ~300 km + HopResolver.init([a, b, far]); + const withFar = HopResolver.inferPath(['AC', 'BC', 'AC'], Object.assign({ allowRevisit: true }, obs)); + assert(pk(withFar[0]) === a.public_key && pk(withFar[2]) === a.public_key, + 'the nearby A beats a far AC on both visits — got ' + withFar.map(e => e.name).join(',')); + + // A radio does not hear its own transmission: a node is never its own next + // hop, but it may return after an unlisted hop. + HopResolver.init([a, b]); + const twice = HopResolver.inferPath(['AC', 'AC'], Object.assign({ allowRevisit: true }, obs)); + assert(twice.filter(e => pk(e) === a.public_key).length === 1, 'A is not its own next hop'); + const gap = HopResolver.inferPath(['AC', 'E9', 'AC'], Object.assign({ allowRevisit: true }, obs)); + assert(pk(gap[0]) === a.public_key && gap[1].unlisted && pk(gap[2]) === a.public_key, + 'A returns after an unlisted hop — got ' + gap.map(e => e.name || e.hop).join(',')); + const gapFlood = HopResolver.inferPath(['AC', 'E9', 'AC'], obs); + assert(gapFlood.filter(e => pk(e) === a.public_key).length === 1, 'without allowRevisit it does not'); +} + console.log('\nTest 11: performance — 64 hops × 16 candidates'); { // A vm sandbox routes every global lookup (Math, Infinity) through an From 976b1e028c40a4f0357b0912f1fa0259b565926d Mon Sep 17 00:00:00 2001 From: zfouts Date: Tue, 1 Dec 2026 18:41:09 -0600 Subject: [PATCH 3/3] refactor(packet-helpers): name the TRACE payload type in inferObservationPath Replace the bare 9 with TRACE_PAYLOAD_TYPE. PayloadLabels is not loaded by every unit test that loads this file, so the constant is local, with a comment pointing at PayloadLabels.enums.TRACE.enumId. Co-Authored-By: Claude Opus 5.5 --- public/packet-helpers.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/public/packet-helpers.js b/public/packet-helpers.js index 3d3d72e2a..79fc62712 100644 --- a/public/packet-helpers.js +++ b/public/packet-helpers.js @@ -60,6 +60,10 @@ window.getParsedDecoded = function getParsedDecoded(p) { return p._parsedDecoded; }; +// Firmware PAYLOAD_TYPE_TRACE; same value as PayloadLabels.enums.TRACE.enumId. +// Not read from PayloadLabels: unit tests load this file without it. +var TRACE_PAYLOAD_TYPE = 9; + /** * One observation's hops, inferred as a whole path (HopResolver.inferPath). * Shared by the packet detail pane and the map route view so both show the @@ -78,7 +82,7 @@ window.inferObservationPath = function inferObservationPath(obs, observer, origi observerId: obs.observer_id, origin: origin, resolvedPath: window.getResolvedPath(obs), - allowRevisit: Number(payloadType) === 9, + allowRevisit: Number(payloadType) === TRACE_PAYLOAD_TYPE, }); };