Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cmd/ingestor/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1265,14 +1265,16 @@ 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(
hops,
strings.ToLower(data.FromPubkey),
s.neighborGraph.load(),
prefixIdx,
packetpath.PathMayRevisit(byte(data.PayloadType)),
)
resolvedJSON := marshalResolvedPath(resolved)

Expand Down
12 changes: 10 additions & 2 deletions cmd/ingestor/path_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
//
Expand Down Expand Up @@ -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
}
Expand All @@ -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{}{}
Expand Down
8 changes: 4 additions & 4 deletions cmd/ingestor/resolved_path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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))
}
Expand All @@ -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))
}
Expand All @@ -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))
}
Expand Down
142 changes: 142 additions & 0 deletions cmd/ingestor/trace_revisit_test.go
Original file line number Diff line number Diff line change
@@ -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 <nil>, 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 <nil>, 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])
}
}
10 changes: 10 additions & 0 deletions internal/packetpath/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions internal/packetpath/route_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
25 changes: 17 additions & 8 deletions public/hop-resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -544,6 +549,8 @@ window.HopResolver = (function() {
* @param {{lat,lon}} [opts.origin] - the sender's position, when known
* @param {Array<string|null>} [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
Expand Down Expand Up @@ -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++) {
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion public/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
9 changes: 8 additions & 1 deletion public/packet-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -68,14 +72,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) === TRACE_PAYLOAD_TYPE,
});
};

Expand Down
2 changes: 1 addition & 1 deletion public/packets.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading