Explorar el Código

fix(topology): anchor fleet uplinks from raw switch FDB, not device attribution (#1051) (#1058)

The #1047 anchoring only worked when fleet units also showed up as
devices, because the evidence came from device attribution. Use the FDB
maps from the pollers directly: each fleet unit's bridge MAC learned on
another member's port says where it hangs, with or without a device
record. Device attribution (attachTo/overrides) still wins when it
exists. Deterministic: sorted router ids, first parent candidate wins.

Verified live: home fleet (no managed SNMP switches) keeps gateway
uplinks unchanged.
Nacho hace 2 meses
padre
commit
bba4be19e7

+ 1 - 1
server-go/internal/adapters/demo.go

@@ -225,7 +225,7 @@ func (d *Demo) buildOverview() *Overview {
 		Alerts:            d.alertsCopy(),
 		UnreadAlerts:      d.engine.UnreadCount(),
 		DistributionNodes: dists,
-		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists, ""), // SPEC-65 D65-3
+		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists, "", nil), // SPEC-65 D65-3
 		VM:                ViewModelVersion,                                    // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}

+ 5 - 1
server-go/internal/adapters/live.go

@@ -2993,6 +2993,10 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	if len(top) > 5 {
 		top = top[:5]
 	}
+	// #1051: evidencia FDB directa para anclar uplinks de flota sin depender
+	// de que la unidad aparezca como device (la MAC bridge de cada router
+	// aprendida en el FDB de otro miembro dice dónde cuelga).
+	fdbEvidence := fleetFdbEvidence(polled)
 	// El motor de alertas es el dueño de la lista y del read-state
 	// (SPEC-ALERTAS §3-4): UnreadAlerts = no leídas que pasaron config.
 	alertsCopy := l.engine.List()
@@ -3009,7 +3013,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
 		DistributionNodes: distNodes,
-		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway), // SPEC-65 D65-3 + #1042
+		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway, fdbEvidence), // SPEC-65 D65-3 + #1042/#1051
 		Devices:           devices,
 		Usteer:            &UsteerOverview{Available: usteerAvailable},
 		DawnDeprecated:    dawnDetected,

+ 57 - 4
server-go/internal/adapters/topo_semantics.go

@@ -16,7 +16,10 @@
 //     generan enlace (la app los agrupa en su chip "+N" de peers).
 package adapters
 
-import "strings"
+import (
+	"sort"
+	"strings"
+)
 
 // Capacidad de los anillos canónicos de model.ts (GATEWAY_RINGS 8+12+16+24,
 // AP_RINGS 8+14+18): el límite de chips visibles por anillo que aplica la app.
@@ -34,7 +37,49 @@ const maxTopoPeerChips = 4
 
 // BuildTopoSemantics deriva enlaces, anillos y peers ocultos del mismo bundle
 // que hoy consume la app (routers, devices, wireguard, distributionNodes).
-func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode, wanGateway string) *TopoSemantics {
+// topoParent (#1047/#1051): padre de uplink de una unidad de flota derivado
+// de evidencia FDB (en qué equipo se aprendió su MAC y en qué puerto).
+type topoParent struct {
+	parent string
+	port   string
+}
+
+// fleetFdbEvidence (#1051): para cada router de la flota, ¿en qué OTRO miembro
+// se aprendió su MAC bridge y en qué puerto? Fuente directa del FDB de cada
+// poller, sin pasar por la atribución a devices (que no existe en redes donde
+// las unidades no aparecen como clientes). Orden determinista: ids ordenados,
+// primer padre candidato gana.
+func fleetFdbEvidence(polled map[string]*routerPolled) map[string]topoParent {
+	macs := map[string]string{} // MAC bridge (upper) → router propietario
+	ids := make([]string, 0, len(polled))
+	for id, p := range polled {
+		if p == nil || p.brMac == "" {
+			continue
+		}
+		macs[strings.ToUpper(p.brMac)] = id
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	out := map[string]topoParent{}
+	for _, sid := range ids {
+		p := polled[sid]
+		if p == nil {
+			continue
+		}
+		for mac, port := range p.fdb {
+			rid, ok := macs[strings.ToUpper(mac)]
+			if !ok || rid == sid {
+				continue
+			}
+			if _, seen := out[rid]; !seen {
+				out[rid] = topoParent{parent: sid, port: port}
+			}
+		}
+	}
+	return out
+}
+
+func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode, wanGateway string, fdbEvidence map[string]topoParent) *TopoSemantics {
 	sem := &TopoSemantics{Links: []TopoLink{}, Rings: map[string][]string{}}
 	if len(routers) == 0 {
 		return sem
@@ -90,13 +135,13 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 			routerMacs[strings.ToUpper(r.MAC)] = r.ID
 		}
 	}
-	uplinkEvidence := map[string]struct{ parent, port string }{}
+	uplinkEvidence := map[string]topoParent{}
 	filtered := online[:0]
 	for _, d := range online {
 		if rid, ok := routerMacs[strings.ToUpper(d.MAC)]; ok {
 			if rid != d.RouterID {
 				if _, seen := uplinkEvidence[rid]; !seen {
-					uplinkEvidence[rid] = struct{ parent, port string }{d.RouterID, d.Port}
+					uplinkEvidence[rid] = topoParent{parent: d.RouterID, port: d.Port}
 				}
 			}
 			continue
@@ -104,6 +149,14 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 		filtered = append(filtered, d)
 	}
 	online = filtered
+	// #1051: la evidencia FDB directa del poller cubre las redes donde las
+	// unidades de flota NO aparecen como devices; la atribución de device
+	// (attachTo/override) manda cuando existe.
+	for rid, ev := range fdbEvidence {
+		if _, ok := uplinkEvidence[rid]; !ok {
+			uplinkEvidence[rid] = ev
+		}
+	}
 	// #1042: el equipo aguas arriba del gateway (módem/ONT del ISP) se
 	// descubre por ARP como un cliente más, pero vive en el lado WAN: si su
 	// IP coincide con la puerta de enlace WAN se representa bajo el nodo

+ 80 - 8
server-go/internal/adapters/topo_semantics_test.go

@@ -23,7 +23,7 @@ import (
 //   - hiddenPeers ausente: todos los anillos bajo el límite de chips visibles
 //     de la app (gateway 13, AP 20)
 func TestTopoSemanticsGoldenCanon(t *testing.T) {
-	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
+	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "", nil)
 
 	wantLinks := []TopoLink{
 		{From: "internet", To: "flint2", Kind: "wan"},
@@ -109,7 +109,7 @@ func TestTopoSemanticsHiddenPeers(t *testing.T) {
 			RouterID: "ap", Band: "2.4 GHz", Online: true,
 		})
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	want := map[string]int{"gw": 2, "ap": 2} // 62-60 y 42-40
 	if !reflect.DeepEqual(sem.HiddenPeers, want) {
 		t.Fatalf("hiddenPeers: got %+v want %+v", sem.HiddenPeers, want)
@@ -133,7 +133,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 		t.Fatal("overview.Topology ausente en demo")
 	}
 	// Mismo resultado que el builder puro sobre el canon.
-	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
+	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "", nil)
 	if !reflect.DeepEqual(ov.Topology, want) {
 		t.Fatalf("overview.Topology != builder canon:\n got: %+v\nwant: %+v", ov.Topology, want)
 	}
@@ -141,7 +141,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 
 // Sin routers: semántica vacía pero no nil (la app cae a su cálculo propio).
 func TestTopoSemanticsSinRouters(t *testing.T) {
-	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil, "", nil)
 	if sem == nil || sem.Links == nil || sem.Rings == nil {
 		t.Fatalf("semántica vacía debe tener links/rings no-nil: %+v", sem)
 	}
@@ -161,7 +161,7 @@ func TestTopoSemanticsDeviceHubBajoDistnode(t *testing.T) {
 	}
 	routers := []Router{{ID: "gateway", Name: "gateway", RoleBadge: "Principal", Status: "online"}}
 	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred", RouterID: "gateway", Port: "lan1"}}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "", nil)
 
 	var toHost []TopoLink
 	for _, l := range sem.Links {
@@ -201,7 +201,7 @@ func TestTopoSemanticsWanPeer(t *testing.T) {
 		{ID: "modem", MAC: "AA:BB:CC:00:00:01", RouterID: "gw", Band: "cable", Online: true, IP: "100.64.0.1"},
 		{ID: "nas", MAC: "AA:BB:CC:00:00:02", RouterID: "gw", Band: "cable", Online: true, IP: "192.168.1.10"},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "100.64.0.1")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "100.64.0.1", nil)
 	if sem.WanPeer != "modem" {
 		t.Fatalf("WanPeer = %q, want modem", sem.WanPeer)
 	}
@@ -223,7 +223,7 @@ func TestTopoSemanticsWanPeer(t *testing.T) {
 		t.Fatal("falta el enlace internet→modem (wan-peer)")
 	}
 	// Sin gateway WAN no hay wan peer aunque haya dispositivos.
-	sem2 := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem2 := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	if sem2.WanPeer != "" {
 		t.Fatalf("WanPeer sin gateway WAN = %q, want vacío", sem2.WanPeer)
 	}
@@ -244,7 +244,7 @@ func TestTopoSemanticsFdbUplinkParent(t *testing.T) {
 		{ID: "dev-ap1", MAC: "AA:BB:CC:00:00:03", RouterID: "sw1", Band: "cable", Online: true, Port: "5"},
 		{ID: "nas", MAC: "AA:BB:CC:00:00:09", RouterID: "gw", Band: "cable", Online: true, Port: "2"},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	links := map[string]TopoLink{}
 	for _, l := range sem.Links {
 		if l.Kind == "uplink" {
@@ -266,3 +266,75 @@ func TestTopoSemanticsFdbUplinkParent(t *testing.T) {
 		}
 	}
 }
+
+// #1051: el anclaje FDB no debe depender de que las unidades de flota
+// aparezcan como devices: la evidencia directa del poller basta.
+func TestTopoSemanticsFdbEvidenceSinDevices(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "sw1", Name: "sw1", MAC: "AA:BB:CC:00:00:02"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	devices := []Device{
+		{ID: "nas", MAC: "AA:BB:CC:00:00:09", RouterID: "gw", Band: "cable", Online: true, Port: "2"},
+	}
+	ev := map[string]topoParent{
+		"sw1": {parent: "gw", port: "1"},
+		"ap1": {parent: "sw1", port: "5"},
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", ev)
+	links := map[string]TopoLink{}
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" {
+			links[l.To] = l
+		}
+	}
+	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" {
+		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5", got)
+	}
+	if got := links["sw1"]; got.From != "gw" || got.Port != "1" {
+		t.Fatalf("uplink sw1: %+v, want from gw puerto 1", got)
+	}
+}
+
+// #1051: la evidencia de device (attachTo/atribución) manda sobre la FDB
+// directa cuando ambas existen.
+func TestTopoSemanticsDeviceEvidenceManda(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	devices := []Device{
+		{ID: "dev-ap1", MAC: "AA:BB:CC:00:00:03", RouterID: "gw", Band: "cable", Online: true, Port: "4"},
+	}
+	ev := map[string]topoParent{"ap1": {parent: "swX", port: "9"}}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", ev)
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" && l.To == "ap1" {
+			if l.From != "gw" || l.Port != "4" {
+				t.Fatalf("la evidencia de device debe mandar: %+v", l)
+			}
+			return
+		}
+	}
+	t.Fatal("falta el uplink de ap1")
+}
+
+// #1051: fleetFdbEvidence deriva el padre del FDB crudo de cada poller.
+func TestFleetFdbEvidence(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"gw":  {brMac: "aa:bb:cc:00:00:01", fdb: map[string]string{"AA:BB:CC:00:00:02": "1"}},
+		"sw1": {brMac: "AA:BB:CC:00:00:02", fdb: map[string]string{"AA:BB:CC:00:00:03": "5"}},
+		"ap1": {brMac: "AA:BB:CC:00:00:03", fdb: map[string]string{}},
+	}
+	ev := fleetFdbEvidence(polled)
+	if got := ev["sw1"]; got.parent != "gw" || got.port != "1" {
+		t.Fatalf("sw1: %+v, want gw/1", got)
+	}
+	if got := ev["ap1"]; got.parent != "sw1" || got.port != "5" {
+		t.Fatalf("ap1: %+v, want sw1/5", got)
+	}
+	if _, ok := ev["gw"]; ok {
+		t.Fatal("gw no debe tener padre (cuelga de internet)")
+	}
+}

+ 1 - 1
server-go/internal/adapters/topology_lldp_test.go

@@ -225,7 +225,7 @@ func TestTopoSemanticsCadenaLldp(t *testing.T) {
 		{RouterID: "flint2", Band: "cable", Port: "lan3", ID: "pc1", MAC: "04:D4:C4:8B:30:A7", AttachTo: "dist-flint2-lan3", Online: true},
 		{RouterID: "swA", Band: "cable", Port: "ge5", ID: "pc2", MAC: "DC:A6:32:4F:77:02", AttachTo: "dist-swA-ge5", Online: true},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "", nil)
 
 	var gotDist []TopoLink
 	for _, l := range sem.Links {