feat(dev): correlate telemetry recovery, safety stops and passive drive evidence
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
package node
|
||||
|
||||
// Explicit DEV sources. Read-only collectors never share the motor delivery loop.
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
)
|
||||
|
||||
func diagnosticSourceEnabled(value any, source string) bool {
|
||||
if source == "network" {
|
||||
return devOption(value, source)
|
||||
}
|
||||
options, _ := value.(map[string]any)
|
||||
return options[source] == true
|
||||
}
|
||||
func (s *roverStreamState) diagnosticCapture(source string) string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.devEnabled || !diagnosticSourceEnabled(s.devDesired["options"], source) {
|
||||
return ""
|
||||
}
|
||||
return s.devID
|
||||
}
|
||||
func (p *Pairing) roverEvidence(ctx context.Context, endpoint string, state *roverStreamState) {
|
||||
var workers sync.WaitGroup
|
||||
for _, source := range []string{"network", "system", "router"} {
|
||||
workers.Add(1)
|
||||
go func(source string) { defer workers.Done(); p.devEvidenceSource(ctx, endpoint, source, state) }(source)
|
||||
}
|
||||
workers.Wait()
|
||||
}
|
||||
func (p *Pairing) devEvidenceSource(ctx context.Context, endpoint, source string, state *roverStreamState) {
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
var capture string
|
||||
var sampled time.Time
|
||||
lastFingerprints := map[string]string{}
|
||||
var routerSequence uint64
|
||||
var cachedSequence uint64
|
||||
var host devHostSampler
|
||||
var uplink devUplinkSampler
|
||||
parsed, _ := url.Parse(endpoint)
|
||||
peer := ""
|
||||
if parsed != nil {
|
||||
peer = parsed.Hostname()
|
||||
}
|
||||
lastTick := time.Now()
|
||||
maxGap := time.Duration(0)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
now := time.Now()
|
||||
gap := now.Sub(lastTick)
|
||||
lastTick = now
|
||||
if gap > maxGap {
|
||||
maxGap = gap
|
||||
}
|
||||
id := state.diagnosticCapture(source)
|
||||
if id == "" {
|
||||
capture = ""
|
||||
sampled = time.Time{}
|
||||
maxGap = 0
|
||||
continue
|
||||
}
|
||||
state.mu.Lock()
|
||||
passive := devPassive(state.devDesired["options"])
|
||||
state.mu.Unlock()
|
||||
if capture != id {
|
||||
capture = id
|
||||
sampled = time.Time{}
|
||||
lastFingerprints = map[string]string{}
|
||||
routerSequence = 0
|
||||
cachedSequence = 0
|
||||
host = devHostSampler{}
|
||||
uplink = devUplinkSampler{}
|
||||
if source == "router" && passive && p.Routers != nil {
|
||||
cachedSequence = cachedRouterBaseline(p.Routers.Snapshot())
|
||||
}
|
||||
state.recordDevSource(id, source, "source_started", map[string]any{"collector": source, "node_version": p.version, "node_boot_id": devRead("/proc/sys/kernel/random/boot_id", 128), "relay_origin_utc": state.origin.UTC().Format(time.RFC3339Nano), "sample_interval_ms": 1000, "passive": passive, "cached_events_after": cachedSequence})
|
||||
}
|
||||
if source == "router" && p.Routers != nil && !passive {
|
||||
p.Routers.DiagnosticInterest()
|
||||
}
|
||||
if !sampled.IsZero() && now.Sub(sampled) < time.Second {
|
||||
continue
|
||||
}
|
||||
sampled = now
|
||||
switch source {
|
||||
case "system":
|
||||
row := host.sample("/", now)
|
||||
row["sampler_max_gap_ms"] = float64(maxGap.Microseconds()) / 1000
|
||||
interfaces, _ := row["interfaces"].([]map[string]any)
|
||||
delete(row, "interfaces")
|
||||
usb, _ := row["usb"].([]map[string]any)
|
||||
delete(row, "usb")
|
||||
row["usb_count"] = len(usb)
|
||||
names := []string{}
|
||||
for _, n := range interfaces {
|
||||
if name, ok := n["interface"].(string); ok {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
row["interface_names"] = names
|
||||
state.recordDevSource(id, source, "host_sample", row)
|
||||
for _, network := range interfaces {
|
||||
state.recordDevSource(id, source, "interface_sample", network)
|
||||
}
|
||||
for start := 0; start < len(usb); start += 8 {
|
||||
state.recordDevSource(id, source, "usb_inventory", map[string]any{"sampled_utc": row["sampled_utc"], "offset": start, "total": len(usb), "devices": usb[start:min(start+8, len(usb))]})
|
||||
}
|
||||
case "network":
|
||||
uplink.record(state, id, p.uplink)
|
||||
call, cancel := context.WithTimeout(ctx, 1800*time.Millisecond)
|
||||
row := devPathSample(call, peer, passive)
|
||||
cancel()
|
||||
row["collector_elapsed_ms"] = float64(time.Since(now).Microseconds()) / 1000
|
||||
state.recordDevSource(id, source, "network_path", row)
|
||||
case "router":
|
||||
if p.Routers == nil {
|
||||
if lastFingerprints["unavailable"] == "" {
|
||||
state.recordDevSource(id, source, "router_unavailable", map[string]any{"reason": "collector_unavailable"})
|
||||
lastFingerprints["unavailable"] = "unavailable"
|
||||
}
|
||||
continue
|
||||
}
|
||||
if passive {
|
||||
recordCachedRouter(state, id, p.Routers.Snapshot(), lastFingerprints, &cachedSequence)
|
||||
break
|
||||
}
|
||||
for _, row := range p.Routers.DiagnosticTail(routerSequence) {
|
||||
if row.Sequence > routerSequence {
|
||||
routerSequence = row.Sequence
|
||||
}
|
||||
state.recordDevSource(id, source, row.Event, map[string]any{"router_id": row.DeviceID, "router_sequence": row.Sequence, "observed_at": row.At, "data": row.Data})
|
||||
}
|
||||
snapshot := p.Routers.Snapshot()
|
||||
// The ordinary snapshot retains discovery, physical SIM mapping and API freshness.
|
||||
for _, device := range snapshot.Items {
|
||||
raw, _ := json.Marshal(map[string]any{"id": device.ID, "attached": device.Attached, "state": device.State, "observed_at": device.ObservedAt})
|
||||
fingerprint := string(raw)
|
||||
if fingerprint == lastFingerprints[device.ID] {
|
||||
continue
|
||||
}
|
||||
lastFingerprints[device.ID] = fingerprint
|
||||
state.recordDevSource(id, source, "router_presence", map[string]any{"router_id": device.ID, "attached": device.Attached, "state": device.State, "observed_at": device.ObservedAt, "interface": device.Interface, "slot_map": device.SlotMap, "model": device.ModelName})
|
||||
}
|
||||
}
|
||||
maxGap = 0
|
||||
}
|
||||
}
|
||||
|
||||
func cachedRouterBaseline(snapshot routers.Snapshot) uint64 {
|
||||
var sequence uint64
|
||||
for _, event := range snapshot.Events {
|
||||
sequence = max(sequence, event.Sequence)
|
||||
}
|
||||
return sequence
|
||||
}
|
||||
|
||||
// Only already-published discovery data. No interest, HTTP, DNS or modem commands.
|
||||
func recordCachedRouter(state *roverStreamState, capture string, snapshot routers.Snapshot, fingerprints map[string]string, cursor *uint64) {
|
||||
for _, d := range snapshot.Items {
|
||||
sample := map[string]any{"router_id": d.ID, "evidence_source": "regular_discovery_cache", "observed_at": d.ObservedAt, "attached": d.Attached, "state": d.State, "slot_map": d.SlotMap, "uptime": d.Uptime, "selected_mode": d.SelectedMode, "active_mode": d.ActiveMode, "persisted_mode": d.PersistedMode, "active_slots": d.ActiveSlots, "active_wan": d.ActiveWAN, "internet": d.Internet, "down_kbps": d.DownKbps, "up_kbps": d.UpKbps, "modems": d.Modems}
|
||||
raw, _ := json.Marshal(sample)
|
||||
if fingerprints[d.ID] != string(raw) {
|
||||
fingerprints[d.ID] = string(raw)
|
||||
state.recordDevSource(capture, "router", "router_cached_sample", sample)
|
||||
}
|
||||
}
|
||||
emitted := 0
|
||||
for _, event := range snapshot.Events {
|
||||
if event.Sequence <= *cursor {
|
||||
continue
|
||||
}
|
||||
if emitted >= 32 {
|
||||
break
|
||||
}
|
||||
emitted++
|
||||
*cursor = event.Sequence
|
||||
state.recordDevSource(capture, "router", "router_cached_event", map[string]any{"evidence_source": "regular_discovery_cache", "vendor_event": event})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDiagnosticSourcesSeparateFromNetworkAndLateCapture(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
id := strings.Repeat("a", 32)
|
||||
options := map[string]any{"live": false, "core_trace": false, "motor_samples": false, "network": false, "router": true, "system": true, "live_kbps": 16, "core_kbps": 16}
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "options": options})
|
||||
s.recordDev("telemetry", nil)
|
||||
s.recordDevSource(id, "system", "host_sample", nil)
|
||||
s.recordDevSource(id, "router", "router_sample", nil)
|
||||
s.recordDevSource(strings.Repeat("b", 32), "system", "late", nil)
|
||||
if len(s.devEvents) != 2 || s.command != nil {
|
||||
t.Fatal("capture gating or motion authority changed")
|
||||
}
|
||||
legacy := s.devRequest()["options"].(map[string]any)
|
||||
if len(legacy) != 6 || legacy["router"] != nil || legacy["network"] != false {
|
||||
t.Fatal("new Node options reached legacy motor plugin")
|
||||
}
|
||||
if s.devPayload()["options"].(map[string]any)["router"] != true {
|
||||
t.Fatal("new options lost in status")
|
||||
}
|
||||
s.setDev(map[string]any{"id": id, "enabled": false, "options": options})
|
||||
s.recordDevSource(id, "system", "late", nil)
|
||||
if len(s.devEvents) != 2 {
|
||||
t.Fatal("source persisted after stop")
|
||||
}
|
||||
}
|
||||
func TestDiagnosticDiskBatchIsBoundedAndIndependentFromWAN(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
s.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": true})
|
||||
for i := 0; i < 100; i++ {
|
||||
s.recordDev("sample", nil)
|
||||
}
|
||||
rows := s.devRequest()["relay_events"].([]map[string]any)
|
||||
if len(rows) != 64 {
|
||||
t.Fatal(len(rows))
|
||||
}
|
||||
ack := rows[63]["record_sequence"].(int64)
|
||||
s.devPacket = map[string]any{"storage": map[string]any{"external_ack": map[string]any{"node": float64(ack)}}}
|
||||
if len(s.devRequest()["relay_events"].([]map[string]any)) != 36 {
|
||||
t.Fatal("disk cursor failed")
|
||||
}
|
||||
s.recordDev("huge", map[string]any{"value": strings.Repeat("x", 9000)})
|
||||
if s.devEvents[len(s.devEvents)-1]["event"] != "diagnostic_record_omitted" {
|
||||
t.Fatal("oversize must be visible")
|
||||
}
|
||||
}
|
||||
func TestVPNProjectionCannotExportKeysOtherPeersOrCredentials(t *testing.T) {
|
||||
raw := []byte(`{"daemonStatus":"Connected","publicKey":"SECRET","peers":{"details":[{"netbirdIp":"100.64.0.2","status":"Connected","connectionType":"P2P","publicKey":"SECRET","fqdn":"PRIVATE","bytesRx":123,"iceCandidateEndpoint":{"remote":"192.0.2.20:5000","local":"192.168.1.20:5000"}},{"netbirdIp":"100.64.0.3","status":"OTHER"}]}}`)
|
||||
projected := devVPNPeer(raw, "100.64.0.2")
|
||||
data, _ := json.Marshal(projected)
|
||||
if strings.Contains(string(data), "SECRET") || strings.Contains(string(data), "PRIVATE") || strings.Contains(string(data), "OTHER") || projected["remote_candidate_ip"] != "192.0.2.20" {
|
||||
t.Fatal(string(data))
|
||||
}
|
||||
if devVPNPeer(raw, "100.64.0.4")["peer_found"] != false {
|
||||
t.Fatal("wrong peer matched")
|
||||
}
|
||||
}
|
||||
func TestHostEvidenceMissingValuesAndCounterDeltas(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
write := func(name, value string) {
|
||||
p := filepath.Join(root, name)
|
||||
os.MkdirAll(filepath.Dir(p), 0700)
|
||||
os.WriteFile(p, []byte(value), 0600)
|
||||
}
|
||||
write("proc/stat", "cpu 10 0 10 80 0 0 0 0\nctxt 20\n")
|
||||
write("proc/meminfo", "MemTotal: 1000 kB\nMemAvailable: 700 kB\n")
|
||||
write("sys/class/net/eth0/carrier", "1")
|
||||
write("sys/class/net/eth0/statistics/rx_errors", "7")
|
||||
write("sys/bus/usb/devices/1-1/idVendor", "1234")
|
||||
write("sys/bus/usb/devices/1-1/idProduct", "5678")
|
||||
write("sys/bus/usb/devices/1-1/serial", "PRIVATE")
|
||||
h := devHostSampler{}
|
||||
first := h.sample(root, time.Now())
|
||||
if first["cpu_percent"] != nil {
|
||||
t.Fatal("invented first rate")
|
||||
}
|
||||
write("proc/stat", "cpu 20 0 20 160 0 0 0 0\nctxt 50\n")
|
||||
second := h.sample(root, time.Now())
|
||||
if got := second["cpu_percent"].(float64); got < 19.9 || got > 20.1 {
|
||||
t.Fatal(got)
|
||||
}
|
||||
data, _ := json.Marshal(second)
|
||||
if strings.Contains(string(data), "PRIVATE") {
|
||||
t.Fatal("device serial leaked")
|
||||
}
|
||||
iface := second["interfaces"].([]map[string]any)[0]
|
||||
if iface["speed_mbps"] != nil {
|
||||
t.Fatal("missing speed replaced by zero")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayedVPNProjectionKeepsEndpointAndTransferCounters(t *testing.T) {
|
||||
raw := []byte(`{"daemonStatus":"Connected","peers":{"details":[{"netbirdIp":"100.64.0.2","connectionType":"Relayed","relayAddress":"rels://relay.example.test:8443","transferReceived":1234,"transferSent":5678}]}}`)
|
||||
p := devVPNPeer(raw, "100.64.0.2")
|
||||
if p["relay_host"] != "relay.example.test" || p["relay_port"] != "8443" || p["transferReceived"] != float64(1234) {
|
||||
t.Fatal(p)
|
||||
}
|
||||
bad := strings.ReplaceAll(string(raw), "rels://relay.example.test:8443", "rels://user:SECRET@relay.example.test:8443?token=SECRET")
|
||||
p = devVPNPeer([]byte(bad), "100.64.0.2")
|
||||
if _, exists := p["relay_host"]; exists {
|
||||
t.Fatal("credentials accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Fixed kernel files only; no journals, process arguments, serials or credentials.
|
||||
func devRead(path string, limit int64) string {
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
b, e := io.ReadAll(io.LimitReader(f, limit+1))
|
||||
if e != nil || int64(len(b)) > limit {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
func devNumber(path string) any {
|
||||
s := devRead(path, 128)
|
||||
v, e := strconv.ParseInt(s, 10, 64)
|
||||
if e != nil {
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
func devCounters(text string, wanted map[string]bool) map[string]any {
|
||||
out := map[string]any{}
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 2 {
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSuffix(f[0], ":")
|
||||
if !wanted[key] {
|
||||
continue
|
||||
}
|
||||
v, e := strconv.ParseUint(f[1], 10, 64)
|
||||
if e == nil {
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type devHostSampler struct {
|
||||
cpuTotal, cpuIdle uint64
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (h *devHostSampler) sample(root string, now time.Time) map[string]any {
|
||||
path := func(v string) string { return filepath.Join(root, v) }
|
||||
out := map[string]any{"sampled_utc": now.UTC().Format(time.RFC3339Nano), "goroutines": runtime.NumGoroutine(), "cpu_percent": nil}
|
||||
stat := devRead(path("proc/stat"), 65536)
|
||||
fields := strings.Fields(strings.SplitN(stat, "\n", 2)[0])
|
||||
var total, idle uint64
|
||||
if len(fields) >= 5 && fields[0] == "cpu" {
|
||||
for i, v := range fields[1:min(len(fields), 9)] {
|
||||
n, _ := strconv.ParseUint(v, 10, 64)
|
||||
total += n
|
||||
if i == 3 || i == 4 {
|
||||
idle += n
|
||||
}
|
||||
}
|
||||
if h.cpuTotal > 0 && total > h.cpuTotal && idle >= h.cpuIdle {
|
||||
out["cpu_percent"] = 100 * (1 - float64(idle-h.cpuIdle)/float64(total-h.cpuTotal))
|
||||
}
|
||||
h.cpuTotal, h.cpuIdle = total, idle
|
||||
}
|
||||
out["kernel_counters"] = devCounters(stat, map[string]bool{"ctxt": true, "processes": true, "procs_running": true, "procs_blocked": true})
|
||||
out["memory_kib"] = devCounters(devRead(path("proc/meminfo"), 16384), map[string]bool{"MemTotal": true, "MemAvailable": true, "SwapTotal": true, "SwapFree": true, "Dirty": true, "Writeback": true})
|
||||
load := strings.Fields(devRead(path("proc/loadavg"), 128))
|
||||
if len(load) >= 3 {
|
||||
out["load_average"] = load[:3]
|
||||
}
|
||||
pressure := map[string]any{}
|
||||
for _, name := range []string{"cpu", "memory", "io"} {
|
||||
p := devRead(path("proc/pressure/"+name), 1024)
|
||||
if p != "" {
|
||||
pressure[name] = p
|
||||
}
|
||||
}
|
||||
out["pressure"] = pressure
|
||||
out["interfaces"] = devInterfaces(root)
|
||||
usb := []map[string]any{}
|
||||
entries, err := os.ReadDir(path("sys/bus/usb/devices"))
|
||||
out["usb_readable"] = err == nil
|
||||
for _, e := range entries {
|
||||
if len(usb) >= 64 {
|
||||
break
|
||||
}
|
||||
base := path("sys/bus/usb/devices/" + e.Name())
|
||||
vendor := devRead(filepath.Join(base, "idVendor"), 8)
|
||||
if vendor == "" {
|
||||
continue
|
||||
}
|
||||
usb = append(usb, map[string]any{"port": e.Name(), "vendor_id": vendor, "product_id": devRead(filepath.Join(base, "idProduct"), 8), "speed_mbps": devNumber(filepath.Join(base, "speed"))})
|
||||
}
|
||||
out["usb"] = usb
|
||||
temperatures := []map[string]any{}
|
||||
entries, _ = os.ReadDir(path("sys/class/thermal"))
|
||||
for _, e := range entries {
|
||||
if !strings.HasPrefix(e.Name(), "thermal_zone") || len(temperatures) >= 16 {
|
||||
continue
|
||||
}
|
||||
base := path("sys/class/thermal/" + e.Name())
|
||||
temperatures = append(temperatures, map[string]any{"zone": e.Name(), "type": devRead(filepath.Join(base, "type"), 64), "millidegrees_c": devNumber(filepath.Join(base, "temp"))})
|
||||
}
|
||||
out["temperatures"] = temperatures
|
||||
h.at = now
|
||||
return out
|
||||
}
|
||||
func devInterfaces(root string) []map[string]any {
|
||||
out := []map[string]any{}
|
||||
entries, _ := os.ReadDir(filepath.Join(root, "sys/class/net"))
|
||||
wireless := map[string]string{}
|
||||
scan := bufio.NewScanner(strings.NewReader(devRead(filepath.Join(root, "proc/net/wireless"), 4096)))
|
||||
for scan.Scan() {
|
||||
name, value, ok := strings.Cut(scan.Text(), ":")
|
||||
if ok {
|
||||
wireless[strings.TrimSpace(name)] = strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name() == "lo" || len(out) >= 16 {
|
||||
continue
|
||||
}
|
||||
base := filepath.Join(root, "sys/class/net", e.Name())
|
||||
row := map[string]any{"interface": e.Name(), "operstate": devRead(filepath.Join(base, "operstate"), 32), "carrier": devNumber(filepath.Join(base, "carrier")), "mtu": devNumber(filepath.Join(base, "mtu")), "speed_mbps": devNumber(filepath.Join(base, "speed"))}
|
||||
stats := map[string]any{}
|
||||
for _, k := range []string{"rx_bytes", "tx_bytes", "rx_packets", "tx_packets", "rx_errors", "tx_errors", "rx_dropped", "tx_dropped", "collisions", "carrier_changes"} {
|
||||
p := filepath.Join(base, "statistics", k)
|
||||
if k == "carrier_changes" {
|
||||
p = filepath.Join(base, k)
|
||||
}
|
||||
stats[k] = devNumber(p)
|
||||
}
|
||||
row["counters"] = stats
|
||||
if v, ok := wireless[e.Name()]; ok {
|
||||
row["wireless_link"] = v
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
)
|
||||
|
||||
func TestPassiveLaneHasNoSteadyRequestsAndExplicitStopWakes(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil, "diagnostics_pending": false})
|
||||
}))
|
||||
defer server.Close()
|
||||
s := newRoverStreamState(time.Now())
|
||||
s.diagnosticLane = true
|
||||
s.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": true, "options": map[string]any{"passive": true, "live": false, "core_trace": false}})
|
||||
idle := false
|
||||
s.diagnosticPending = &idle
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1100*time.Millisecond)
|
||||
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, s)
|
||||
cancel()
|
||||
if calls.Load() != 0 {
|
||||
t.Fatal("passive capture sent periodic status", calls.Load())
|
||||
}
|
||||
wake := true
|
||||
s.diagnosticPending = &wake
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 1500*time.Millisecond)
|
||||
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, s)
|
||||
cancel()
|
||||
if calls.Load() != 1 {
|
||||
t.Fatal("explicit wake was not acknowledged once", calls.Load())
|
||||
}
|
||||
if s.command != nil || s.watch || !s.stopPending {
|
||||
t.Fatal("DEV changed motion/watch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassivePathCannotInvokeDNSPingOrVPNProbe(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
marker := filepath.Join(dir, "unexpected")
|
||||
for _, name := range []string{"netbird", "ping"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\necho called >> '"+marker+"'\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "ip"), []byte("#!/bin/sh\nprintf '[{\"dev\":\"eth-fixture\",\"gateway\":\"192.0.2.1\"}]'\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", dir)
|
||||
row := devPathSample(context.Background(), "192.0.2.10", true)
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatal("active diagnostic executed")
|
||||
}
|
||||
if row["relay_lookup"] != "disabled_passive" || row["gateway_probe"].(map[string]any)["state"] != "disabled_passive" {
|
||||
t.Fatal(row)
|
||||
}
|
||||
route := row["core_route"].(map[string]any)
|
||||
if route["state"] == "ok" && route["dev"] != "eth-fixture" {
|
||||
t.Fatal("invalid local route evidence", route)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassiveRouterRecordsExistingSamplesWithoutRepeatingTheirTime(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
id := strings.Repeat("b", 32)
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "options": map[string]any{"passive": true, "router": true}})
|
||||
snap := routers.Snapshot{Items: []routers.Device{{ID: "router-fixture", ObservedAt: 123, ActiveMode: "direct", ActiveWAN: "wan3", Modems: []routers.Modem{{Slot: 3, Operator: "Fixture"}}}}, Events: []routers.Event{{Sequence: 1, At: 120, Code: "mode_changed"}}}
|
||||
fingerprints := map[string]string{}
|
||||
cursor := uint64(0)
|
||||
recordCachedRouter(s, id, snap, fingerprints, &cursor)
|
||||
recordCachedRouter(s, id, snap, fingerprints, &cursor)
|
||||
if len(s.devEvents) != 2 {
|
||||
t.Fatal("duplicated cached evidence", len(s.devEvents))
|
||||
}
|
||||
if s.devEvents[0]["source"] != "node" || s.devEvents[1]["event"] != "router_cached_event" || s.devEvents[1]["vendor_event"] == nil {
|
||||
t.Fatal("cached router evidence overwrote the envelope", s.devEvents)
|
||||
}
|
||||
if s.devEvents[0]["observed_at"] != int64(123) {
|
||||
t.Fatal("cached data claimed fresh")
|
||||
}
|
||||
snap.Items[0].Attached = false
|
||||
snap.Items[0].State = "unreachable"
|
||||
recordCachedRouter(s, id, snap, fingerprints, &cursor)
|
||||
if len(s.devEvents) != 3 {
|
||||
t.Fatal("lost disappearance")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassiveRouterBaselineDoesNotFloodLocalQueueWithPriorHistory(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
id := strings.Repeat("c", 32)
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "options": map[string]any{"passive": true, "router": true}})
|
||||
snap := routers.Snapshot{}
|
||||
for i := uint64(1); i <= 512; i++ {
|
||||
snap.Events = append(snap.Events, routers.Event{Sequence: i, Code: "prior"})
|
||||
}
|
||||
cursor := cachedRouterBaseline(snap)
|
||||
recordCachedRouter(s, id, snap, map[string]string{}, &cursor)
|
||||
if len(s.devEvents) != 0 {
|
||||
t.Fatal("replayed historical cache into fresh capture")
|
||||
}
|
||||
for i := uint64(513); i <= 600; i++ {
|
||||
snap.Events = append(snap.Events, routers.Event{Sequence: i, Code: "new"})
|
||||
}
|
||||
recordCachedRouter(s, id, snap, map[string]string{}, &cursor)
|
||||
if len(s.devEvents) != 32 || cursor != 544 {
|
||||
t.Fatal("unbounded catchup", len(s.devEvents), cursor)
|
||||
}
|
||||
recordCachedRouter(s, id, snap, map[string]string{}, &cursor)
|
||||
if len(s.devEvents) != 64 || cursor != 576 {
|
||||
t.Fatal("cursor did not continue", len(s.devEvents), cursor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A bounded read-only command, without shell expansion or raw error logging.
|
||||
func devCommand(ctx context.Context, timeout time.Duration, name string, args ...string) ([]byte, string) {
|
||||
call, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(call, name, args...)
|
||||
cmd.WaitDelay = 100 * time.Millisecond
|
||||
var out networkOutput
|
||||
cmd.Stdout = &out
|
||||
if err := cmd.Run(); err != nil {
|
||||
if call.Err() != nil {
|
||||
return nil, "timeout"
|
||||
}
|
||||
if _, ok := err.(*exec.Error); ok {
|
||||
return nil, "not_installed"
|
||||
}
|
||||
return nil, "unavailable"
|
||||
}
|
||||
return []byte(out.String()), "ok"
|
||||
}
|
||||
func devRoute(ctx context.Context, target string) map[string]any {
|
||||
out := map[string]any{"target": target, "state": "unsupported_address"}
|
||||
if net.ParseIP(target) == nil {
|
||||
return out
|
||||
}
|
||||
raw, state := devCommand(ctx, 350*time.Millisecond, "ip", "-j", "route", "get", target)
|
||||
out["state"] = state
|
||||
if state != "ok" {
|
||||
return out
|
||||
}
|
||||
var rows []map[string]any
|
||||
if json.Unmarshal(raw, &rows) != nil || len(rows) != 1 {
|
||||
out["state"] = "unavailable"
|
||||
return out
|
||||
}
|
||||
for _, key := range []string{"dev", "gateway", "prefsrc", "src", "table", "metric", "protocol", "type"} {
|
||||
if v, ok := rows[0][key]; ok {
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func devIP(value string) string {
|
||||
if net.ParseIP(value) != nil {
|
||||
return value
|
||||
}
|
||||
if host, _, e := net.SplitHostPort(value); e == nil && net.ParseIP(host) != nil {
|
||||
return host
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func devVPNPeer(raw []byte, peer string) map[string]any {
|
||||
var value struct {
|
||||
Daemon string `json:"daemonStatus"`
|
||||
Version string `json:"daemonVersion"`
|
||||
Peers struct {
|
||||
Details []map[string]any `json:"details"`
|
||||
} `json:"peers"`
|
||||
}
|
||||
if json.Unmarshal(raw, &value) != nil {
|
||||
return map[string]any{"state": "invalid_response"}
|
||||
}
|
||||
out := map[string]any{"provider": "netbird", "state": value.Daemon, "version": value.Version, "peer_found": false}
|
||||
for _, p := range value.Peers.Details {
|
||||
if p["netbirdIp"] != peer {
|
||||
continue
|
||||
}
|
||||
out["peer_found"] = true
|
||||
for _, key := range []string{"status", "connectionType", "latency", "lastStatusUpdate", "lastWireguardHandshake", "bytesRx", "bytesTx", "rxBytes", "txBytes", "transferReceived", "transferSent"} {
|
||||
switch v := p[key].(type) {
|
||||
case string:
|
||||
if len(v) <= 128 {
|
||||
out[key] = v
|
||||
}
|
||||
case float64, bool:
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
if endpoints, ok := p["iceCandidateEndpoint"].(map[string]any); ok {
|
||||
for _, side := range []string{"local", "remote"} {
|
||||
if v, ok := endpoints[side].(string); ok {
|
||||
if ip := devIP(v); ip != "" {
|
||||
out[side+"_candidate_ip"] = ip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if address, ok := p["relayAddress"].(string); ok {
|
||||
if u, err := url.Parse(address); err == nil && u.User == nil && u.RawQuery == "" && len(u.Hostname()) <= 253 && u.Hostname() != "" {
|
||||
out["relay_host"] = u.Hostname()
|
||||
out["relay_port"] = u.Port()
|
||||
}
|
||||
}
|
||||
// A reported ICE candidate is not asserted to be the kernel's current endpoint.
|
||||
out["endpoint_source"] = "vpn_reported_candidate"
|
||||
break
|
||||
}
|
||||
return out
|
||||
}
|
||||
func devPathSample(ctx context.Context, peer string, passive bool) map[string]any {
|
||||
started := time.Now()
|
||||
route := devRoute(ctx, peer)
|
||||
out := map[string]any{"sampled_utc": started.UTC().Format(time.RFC3339Nano), "core_route": route, "core_health_source": "authenticated_command_and_telemetry_records"}
|
||||
if passive {
|
||||
out["recording_mode"] = "passive"
|
||||
out["gateway_probe"] = map[string]any{"state": "disabled_passive"}
|
||||
out["relay_lookup"] = "disabled_passive"
|
||||
return out
|
||||
}
|
||||
raw, status := devCommand(ctx, 650*time.Millisecond, "netbird", "status", "--json")
|
||||
vpn := map[string]any{"provider": "netbird", "state": status}
|
||||
if status == "ok" {
|
||||
vpn = devVPNPeer(raw, peer)
|
||||
}
|
||||
out["vpn"] = vpn
|
||||
physical := route
|
||||
// This is a route lookup for the endpoint reported by the VPN. DNS results
|
||||
// are explicit; they are not presented as captured kernel socket traffic.
|
||||
if host, ok := vpn["relay_host"].(string); ok && vpn["connectionType"] == "Relayed" {
|
||||
lookup, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
addresses, err := net.DefaultResolver.LookupIPAddr(lookup, host)
|
||||
cancel()
|
||||
if err == nil {
|
||||
for _, address := range addresses {
|
||||
if address.IP.To4() == nil {
|
||||
continue
|
||||
}
|
||||
physical = devRoute(ctx, address.IP.String())
|
||||
out["relay_underlay_route"] = physical
|
||||
out["relay_route_source"] = "dns_resolved_vpn_reported_relay"
|
||||
break
|
||||
}
|
||||
} else {
|
||||
out["relay_lookup"] = "unavailable"
|
||||
}
|
||||
}
|
||||
if remote, ok := vpn["remote_candidate_ip"].(string); ok {
|
||||
physical = devRoute(ctx, remote)
|
||||
out["candidate_underlay_route"] = physical
|
||||
}
|
||||
// Only the gateway selected by the OS for the bound Core or its reported peer.
|
||||
gateway, _ := physical["gateway"].(string)
|
||||
iface, _ := physical["dev"].(string)
|
||||
if net.ParseIP(gateway) != nil && iface != "" && !strings.HasPrefix(iface, "-") && len(iface) <= 64 {
|
||||
at := time.Now()
|
||||
_, result := devCommand(ctx, 500*time.Millisecond, "ping", "-n", "-c", "1", "-W", "1", "-I", iface, gateway)
|
||||
out["gateway_probe"] = map[string]any{"kind": "icmp", "interface": iface, "gateway": gateway, "state": result, "elapsed_ms": float64(time.Since(at).Microseconds()) / 1000, "failure_is_not_proof_of_outage": true}
|
||||
} else {
|
||||
out["gateway_probe"] = map[string]any{"state": "no_identified_gateway"}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package node
|
||||
|
||||
import "time"
|
||||
|
||||
// Copies the existing local helper cache. No IPC, DNS, VPN probe or WAN request.
|
||||
type devUplinkSampler struct {
|
||||
started bool
|
||||
sequence float64
|
||||
}
|
||||
|
||||
func (d *devUplinkSampler) record(s *roverStreamState, capture string, u *uplinkController) {
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
u.mu.Lock()
|
||||
raw, _ := u.value["diagnostic"].(map[string]any)
|
||||
observed := u.observed
|
||||
u.mu.Unlock()
|
||||
row := map[string]any{"evidence_source": "local_uplink_controller_cache", "state": "unavailable"}
|
||||
if raw == nil {
|
||||
s.recordDevSource(capture, "network", "uplink_sample", row)
|
||||
return
|
||||
}
|
||||
for k, v := range raw {
|
||||
if k != "events" {
|
||||
row[k] = v
|
||||
}
|
||||
}
|
||||
row["state"] = "cached"
|
||||
row["cache_age_ms"] = float64(time.Since(observed).Microseconds()) / 1000
|
||||
row["cache_fresh"] = time.Since(observed) <= 20*time.Second
|
||||
s.recordDevSource(capture, "network", "uplink_sample", row)
|
||||
events, _ := raw["events"].([]any)
|
||||
for _, value := range events {
|
||||
event, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
sequence, _ := event["sequence"].(float64)
|
||||
if d.started && sequence > d.sequence {
|
||||
if sequence > d.sequence+1 {
|
||||
s.recordDevSource(capture, "network", "uplink_evidence_gap", map[string]any{"after": d.sequence, "before": sequence})
|
||||
}
|
||||
s.recordDevSource(capture, "network", "uplink_transition", map[string]any{"transition": event})
|
||||
}
|
||||
if sequence > d.sequence {
|
||||
d.sequence = sequence
|
||||
}
|
||||
}
|
||||
d.started = true
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUplinkEvidenceIsLocalPassiveBoundedAndPreservesOriginalTime(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
id := strings.Repeat("a", 32)
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "options": map[string]any{"passive": true, "network": true}})
|
||||
u := &uplinkController{observed: time.Now(), call: func(map[string]any) (uplinkState, error) { t.Fatal("DEV must not call helper"); return nil, nil }}
|
||||
load := func(seq int, phase string) {
|
||||
raw, _ := json.Marshal(map[string]any{"supported": true, "diagnostic": map[string]any{
|
||||
"helper_instance": "fixture", "interface": "eth-fixture", "path_proven": false, "phase": phase,
|
||||
"events": []any{map[string]any{"sequence": seq, "at": 123, "state": map[string]any{"phase": phase}}}}})
|
||||
json.Unmarshal(raw, &u.value)
|
||||
}
|
||||
var sampler devUplinkSampler
|
||||
load(1, "applied")
|
||||
sampler.record(s, id, u)
|
||||
load(2, "rolling_back")
|
||||
sampler.record(s, id, u)
|
||||
sampler.record(s, id, u)
|
||||
load(5, "recovering")
|
||||
sampler.record(s, id, u)
|
||||
var transitions, gaps int
|
||||
for _, row := range s.devEvents {
|
||||
if row["event"] == "uplink_transition" {
|
||||
transitions++
|
||||
if row["transition"].(map[string]any)["at"] != float64(123) {
|
||||
t.Fatal("invented transition time")
|
||||
}
|
||||
}
|
||||
if row["event"] == "uplink_evidence_gap" {
|
||||
gaps++
|
||||
}
|
||||
}
|
||||
if transitions != 2 || gaps != 1 {
|
||||
t.Fatal(transitions, gaps)
|
||||
}
|
||||
if _, ok := u.snapshot()["diagnostic"]; ok {
|
||||
t.Fatal("local evidence leaked into WAN heartbeat")
|
||||
}
|
||||
if s.command != nil || s.watch {
|
||||
t.Fatal("diagnostics changed control")
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
@@ -54,6 +55,7 @@ type Pairing struct {
|
||||
network *NetworkProfile
|
||||
uplink *uplinkController
|
||||
mu sync.Mutex
|
||||
roverAuthority atomic.Pointer[CoreBinding]
|
||||
path string
|
||||
store *Store
|
||||
state PairState
|
||||
@@ -104,6 +106,7 @@ func OpenPairing(store *Store, dir, version string, inventory func() Inventory)
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
p.publishRoverBinding()
|
||||
return p, nil
|
||||
}
|
||||
func savePrivateJSON(path string, value any) error {
|
||||
@@ -142,6 +145,7 @@ func (p *Pairing) save(next PairState) error {
|
||||
return e
|
||||
}
|
||||
p.state = next
|
||||
p.publishRoverBinding()
|
||||
return nil
|
||||
}
|
||||
func digest(value string) string { h := sha256.Sum256([]byte(value)); return hex.EncodeToString(h[:]) }
|
||||
@@ -152,11 +156,14 @@ func (p *Pairing) expire() error {
|
||||
return nil
|
||||
}
|
||||
func (p *Pairing) status() map[string]any {
|
||||
// Inventory may wait on an OS device. It is not pairing state and must not
|
||||
// extend the pairing transaction (or block its liveness/authority readers).
|
||||
addresses := p.addresses()
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_ = p.expire()
|
||||
id, _ := p.store.Public()
|
||||
out := map[string]any{"network_profile": p.networkViewLocked(), "phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)}
|
||||
out := map[string]any{"network_profile": p.networkViewLocked(), "phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": addresses, "pending_revocations": len(p.state.Revocations)}
|
||||
if i := p.state.Invitation; i != nil {
|
||||
out["invitation"] = map[string]any{"id": i.ID, "endpoint": i.Endpoint, "expires_at": i.ExpiresAt}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverBindingDoesNotWaitForBackgroundPairingWork(t *testing.T) {
|
||||
p, _ := testPairing(t)
|
||||
b := CoreBinding{BindingID: "control", Endpoint: "https://core.test", ClientPEM: "certificate"}
|
||||
if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.mu.Lock() // A slow inventory/configuration operation owns this lock.
|
||||
finished := make(chan *CoreBinding, 1)
|
||||
go func() { finished <- p.roverBinding() }()
|
||||
select {
|
||||
case got := <-finished:
|
||||
p.mu.Unlock()
|
||||
if !sameRoverBinding(&b, got) {
|
||||
t.Fatal("lost committed binding")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
p.mu.Unlock()
|
||||
<-finished
|
||||
t.Fatal("motor delivery waits for background pairing work")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverLocalLoopDeliversWhileBackgroundWorkIsBlocked(t *testing.T) {
|
||||
sensors, model, state, origin := localDeliveryFixture(t)
|
||||
p, _ := testPairing(t)
|
||||
p.Sensors = sensors
|
||||
b := CoreBinding{BindingID: "control", Endpoint: "https://core.test"}
|
||||
if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requests := make(chan map[string]any, 32)
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
requests <- body
|
||||
return testSensorReply(map[string]any{"state": "driving"}), nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); p.runLocalRover(ctx, b, model, state, "test") }()
|
||||
defer func() { cancel(); <-done }()
|
||||
p.mu.Lock()
|
||||
// Reproduce the recorded 630 ms background pause, with fresh intents
|
||||
// continuing to arrive. Only the fake driver is reachable in this test.
|
||||
for sequence := 1332; sequence < 1348; sequence++ {
|
||||
now := 10000 + float64(time.Since(origin).Microseconds())/1000
|
||||
state.accept(streamIntent(sequence, now, now+400))
|
||||
timer := time.NewTimer(150 * time.Millisecond)
|
||||
matched := false
|
||||
for !matched {
|
||||
select {
|
||||
case request := <-requests:
|
||||
command, ok := request["command"].(map[string]any)
|
||||
matched = ok && command["sequence"] == float64(sequence)
|
||||
if matched && (command["ttl_ms"].(float64) <= 0 || command["ttl_ms"].(float64) > 400) {
|
||||
p.mu.Unlock()
|
||||
timer.Stop()
|
||||
t.Fatal("command deadline changed")
|
||||
}
|
||||
case <-timer.C:
|
||||
p.mu.Unlock()
|
||||
t.Fatal("fresh intent blocked behind background transaction")
|
||||
}
|
||||
}
|
||||
timer.Stop()
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if err := p.cancel(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(150 * time.Millisecond):
|
||||
t.Fatal("revocation did not stop local loop")
|
||||
}
|
||||
var last map[string]any
|
||||
for len(requests) > 0 {
|
||||
last = <-requests
|
||||
}
|
||||
if last == nil || last["watch"] != false || last["command"] != nil {
|
||||
t.Fatal("revocation did not send stop", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverBindingPublicationTracksDurableAuthority(t *testing.T) {
|
||||
p, _ := testPairing(t)
|
||||
b := CoreBinding{BindingID: "control", Endpoint: "https://core.test", ClientPEM: "certificate"}
|
||||
next := PairState{Schema: PairSchema, Phase: "paired", Binding: &b}
|
||||
if err := p.save(next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := p.roverBinding()
|
||||
got.Endpoint = "caller mutation"
|
||||
if !sameRoverBinding(&b, p.roverBinding()) {
|
||||
t.Fatal("mutable binding escaped")
|
||||
}
|
||||
restored, err := OpenPairing(p.store, filepath.Dir(p.path), "test", p.inventory)
|
||||
if err != nil || !sameRoverBinding(&b, restored.roverBinding()) {
|
||||
t.Fatal("restart lost binding", err)
|
||||
}
|
||||
oldPath := p.path
|
||||
p.path = filepath.Join(oldPath, "missing", "binding.json")
|
||||
next.Phase = "revoked"
|
||||
if p.save(next) == nil || !sameRoverBinding(&b, p.roverBinding()) {
|
||||
t.Fatal("failed save changed published authority")
|
||||
}
|
||||
p.path = oldPath
|
||||
if err := p.save(next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.roverBinding() != nil {
|
||||
t.Fatal("revoked binding retained control authority")
|
||||
}
|
||||
next.Phase = "paired"
|
||||
b.EndpointRevision++
|
||||
b.Endpoint = "https://replacement.test"
|
||||
if err := p.save(next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !sameRoverBinding(&b, p.roverBinding()) {
|
||||
t.Fatal("endpoint change not published")
|
||||
}
|
||||
if err := p.cancel(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.roverBinding() != nil {
|
||||
t.Fatal("unpaired binding retained authority")
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,28 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *Pairing) roverBinding() *CoreBinding {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
// Publish only after a successful durable pairing transaction, or initial load.
|
||||
// The control loop reads an immutable value, never the background-work mutex.
|
||||
func (p *Pairing) publishRoverBinding() {
|
||||
if p.state.Phase != "paired" || p.state.Binding == nil {
|
||||
return nil
|
||||
p.roverAuthority.Store(nil)
|
||||
return
|
||||
}
|
||||
b := *p.state.Binding
|
||||
p.roverAuthority.Store(&b)
|
||||
}
|
||||
func (p *Pairing) roverBinding() *CoreBinding {
|
||||
current := p.roverAuthority.Load()
|
||||
if current == nil {
|
||||
return nil
|
||||
}
|
||||
b := *current
|
||||
return &b
|
||||
}
|
||||
func sameRoverBinding(a, b *CoreBinding) bool {
|
||||
@@ -57,7 +65,9 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
return
|
||||
}
|
||||
transport := func() *http.Transport { return newRoverHTTPTransport(config) }
|
||||
telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }}
|
||||
telemetryTransport := transport()
|
||||
telemetryTransport.MaxConnsPerHost, telemetryTransport.MaxIdleConnsPerHost = 2, 2
|
||||
telemetry := &http.Client{Transport: telemetryTransport, Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }}
|
||||
stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
|
||||
defer telemetry.CloseIdleConnections()
|
||||
defer stream.CloseIdleConnections()
|
||||
@@ -74,12 +84,13 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
var workers sync.WaitGroup
|
||||
defer func() { cancel(); workers.Wait() }()
|
||||
workers.Add(3)
|
||||
workers.Add(4)
|
||||
optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
|
||||
defer optional.CloseIdleConnections()
|
||||
go func() { defer workers.Done(); roverDiagnosticsLane(ctx, optional, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); p.roverEvidence(ctx, b.Endpoint, state) }()
|
||||
var model *sensorModel
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
@@ -92,16 +103,24 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
}
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); p.roverDev(ctx, model, state) }()
|
||||
p.runLocalRover(ctx, b, model, state, relay)
|
||||
}
|
||||
|
||||
func (p *Pairing) runLocalRover(ctx context.Context, b CoreBinding, model *sensorModel, state *roverStreamState, relay string) {
|
||||
diagnostic := roverDiagnostics{lane: "local", epoch: relay, started: state.origin}
|
||||
var delivery roverLocalDelivery
|
||||
var timing roverCycleTiming
|
||||
for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) {
|
||||
select {
|
||||
case <-state.wake:
|
||||
default:
|
||||
}
|
||||
started := time.Now()
|
||||
timing.begin(state, started)
|
||||
frame := delivery.run(ctx, p.Sensors, model, state, relay, started)
|
||||
delivered := time.Now()
|
||||
diagnostic.record(started, frame)
|
||||
timing.finish(started, delivered, time.Now())
|
||||
// New intent and stop signals bypass the periodic watchdog tick. The
|
||||
// buffered wake channel coalesces arrivals; it never queues commands.
|
||||
timer := time.NewTimer(max(0, 50*time.Millisecond-time.Since(started)))
|
||||
@@ -117,128 +136,6 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
_, _ = p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": false, "command": nil, "relay_id": relay})
|
||||
done()
|
||||
}
|
||||
func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
epoch, _ := base["relay_id"].(string)
|
||||
diagnostic := roverDiagnostics{lane: "telemetry", epoch: epoch, started: state.origin}
|
||||
var budgetAt time.Time
|
||||
var metadata roverMetadataEncoder
|
||||
connected := false
|
||||
for ctx.Err() == nil {
|
||||
if !connected {
|
||||
connected = roverConnectTelemetry(ctx, client, endpoint, base, state)
|
||||
budgetAt = time.Time{}
|
||||
metadata.reset()
|
||||
if !connected {
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Keep transport liveness separate from sample freshness. A stamped
|
||||
// observation ages in transit; waiting for its reply cannot renew motion.
|
||||
started := time.Now()
|
||||
snapshot, sampleClock := state.telemetryView()
|
||||
payload := make(map[string]any, len(base)+1)
|
||||
for k, v := range base {
|
||||
payload[k] = v
|
||||
}
|
||||
payload["rover"] = snapshot
|
||||
state.mu.Lock()
|
||||
budgetInterval := state.budgetInterval
|
||||
compact := state.roverDetails
|
||||
state.mu.Unlock()
|
||||
if compact {
|
||||
live, details := metadata.encode(snapshot, started)
|
||||
if details != nil {
|
||||
payload["rover"], payload["rover_details_v1"] = live, details
|
||||
}
|
||||
}
|
||||
if state.budget != nil && (!budgetInterval || budgetAt.IsZero() || started.Sub(budgetAt) >= time.Second) {
|
||||
payload["link_budget"] = state.budget.Snapshot()
|
||||
budgetAt = started
|
||||
}
|
||||
requestClient := *client
|
||||
if sampleClock != nil {
|
||||
payload["sample_clock"] = sampleClock
|
||||
requestClient.Timeout = 2 * time.Second
|
||||
}
|
||||
state.mu.Lock()
|
||||
dedicated := state.diagnosticLane
|
||||
state.mu.Unlock()
|
||||
payload["diagnostic_lane_v1"] = dedicated
|
||||
payload["diagnostic_options_v1"] = true
|
||||
if !dedicated {
|
||||
if dev := state.devPayload(); dev != nil {
|
||||
payload["diagnostics"] = dev
|
||||
payload["diagnostic_relay_ack_v1"] = true
|
||||
}
|
||||
}
|
||||
marshalAt := time.Now()
|
||||
raw, _ := json.Marshal(payload)
|
||||
marshalMS := float64(time.Since(marshalAt).Microseconds()) / 1000
|
||||
state.budget.ObserveCriticalBytes(len(raw))
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
var trace *roverHTTPTrace
|
||||
if state.devTraceEnabled() {
|
||||
trace = newRoverHTTPTrace(started, len(raw))
|
||||
req = req.WithContext(trace.context(req.Context()))
|
||||
}
|
||||
frame := roverFrame{MarshalMS: marshalMS, RequestBytes: len(raw), ReleaseConfirmed: roverReleaseEvidence(snapshot)}
|
||||
frame.State, _ = snapshot["state"].(string)
|
||||
if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" {
|
||||
frame.Session, _ = snapshot["session_id"].(string)
|
||||
}
|
||||
processingMS := 0.0
|
||||
response, err := requestClient.Do(req)
|
||||
if err != nil {
|
||||
frame.Stage = "telemetry_transport"
|
||||
} else {
|
||||
frame.Status = response.StatusCode
|
||||
var out roverStreamReply
|
||||
readErr := json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&out)
|
||||
response.Body.Close()
|
||||
if readErr != nil || response.StatusCode != 200 {
|
||||
frame.Stage = "telemetry_response"
|
||||
} else if !state.sampleClock(out.Clock, started, time.Now()) {
|
||||
frame.Stage = "clock_invalid"
|
||||
state.stopStream()
|
||||
} else {
|
||||
processingMS = out.CoreProcessingMS
|
||||
state.mu.Lock()
|
||||
state.diagnosticPending = out.DiagnosticsPending
|
||||
hasIntent := state.command != nil
|
||||
state.mu.Unlock()
|
||||
state.budget.SetControl(roverControlActive(snapshot, hasIntent, out.ControlActive))
|
||||
state.setWatch(out.Watch)
|
||||
state.setDev(out.Diagnostics)
|
||||
}
|
||||
}
|
||||
if frame.Stage != "" {
|
||||
connected = false
|
||||
}
|
||||
frame.CoreProcessingMS = processingMS
|
||||
frame.CoreMS = time.Since(started).Milliseconds()
|
||||
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
|
||||
state.budget.ObserveExchange(time.Since(started), processingMS, frame.Stage == "")
|
||||
}
|
||||
details := map[string]any{"elapsed_ms": frame.CoreMS, "http_status": frame.Status, "error_stage": frame.Stage, "reason": roverErrorKind(err), "marshal_ms": marshalMS, "request_bytes": len(raw), "core_processing_ms": processingMS, "epoch": epoch, "sample_mono_ms": float64(started.Sub(state.origin).Microseconds()) / 1000}
|
||||
if trace != nil {
|
||||
details["transport"] = trace.snapshot()
|
||||
}
|
||||
state.recordDev("telemetry", details)
|
||||
diagnostic.record(started, frame)
|
||||
_, watch := state.view()
|
||||
delay := 500 * time.Millisecond
|
||||
if watch {
|
||||
delay = 100 * time.Millisecond
|
||||
}
|
||||
if !roverWait(ctx, delay-time.Since(started)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
defer state.budget.DisableDatagramFeedback()
|
||||
for ctx.Err() == nil {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package node
|
||||
|
||||
import "time"
|
||||
|
||||
// Separate scheduling gaps from local delivery and diagnostics. This evidence
|
||||
// stays in the existing passive DEV recorder; it creates no network request.
|
||||
type roverCycleTiming struct {
|
||||
last time.Time
|
||||
work, delivery, diagnostics time.Duration
|
||||
}
|
||||
|
||||
func (t *roverCycleTiming) begin(state *roverStreamState, now time.Time) {
|
||||
if !t.last.IsZero() && now.Sub(t.last) >= 100*time.Millisecond {
|
||||
state.recordDev("local_cycle_gap", map[string]any{
|
||||
"gap_ms": float64(now.Sub(t.last).Microseconds()) / 1000,
|
||||
"previous_cycle_ms": float64(t.work.Microseconds()) / 1000,
|
||||
"previous_delivery_ms": float64(t.delivery.Microseconds()) / 1000,
|
||||
"previous_diagnostics_ms": float64(t.diagnostics.Microseconds()) / 1000,
|
||||
"outside_cycle_ms": float64((now.Sub(t.last) - t.work).Microseconds()) / 1000,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (t *roverCycleTiming) finish(started, delivered, finished time.Time) {
|
||||
t.last, t.work = started, finished.Sub(started)
|
||||
t.delivery, t.diagnostics = delivered.Sub(started), finished.Sub(delivered)
|
||||
}
|
||||
@@ -86,6 +86,11 @@ func (s *roverStreamState) setDev(value map[string]any) {
|
||||
}
|
||||
s.devAfter = value["after"]
|
||||
}
|
||||
func devPassive(options any) bool {
|
||||
value, _ := options.(map[string]any)
|
||||
return value["passive"] == true
|
||||
}
|
||||
|
||||
func devOption(options any, key string) bool {
|
||||
if value, ok := options.(map[string]any); ok {
|
||||
if flag, ok := value[key].(bool); ok {
|
||||
@@ -96,21 +101,32 @@ func devOption(options any, key string) bool {
|
||||
}
|
||||
|
||||
func (s *roverStreamState) recordDev(event string, data map[string]any) {
|
||||
s.recordDevSource("", "network", event, data)
|
||||
}
|
||||
|
||||
// Source admission and capture identity are checked again after each slow read.
|
||||
func (s *roverStreamState) recordDevSource(capture, source, event string, data map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.devID == "" || !s.devEnabled || !devOption(s.devDesired["options"], "network") {
|
||||
if s.devID == "" || !s.devEnabled || (capture != "" && capture != s.devID) || !diagnosticSourceEnabled(s.devDesired["options"], source) {
|
||||
return
|
||||
}
|
||||
// UTC microseconds fit exactly in JSON and keep sequence unique across relay restarts.
|
||||
s.devSequence = max(s.devSequence+1, time.Now().UnixMicro())
|
||||
row := map[string]any{"source": "node", "event": event, "record_sequence": s.devSequence,
|
||||
"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "monotonic_ms": float64(time.Since(s.origin).Microseconds()) / 1000}
|
||||
"capture_id": s.devID, "at_utc": time.Now().UTC().Format(time.RFC3339Nano), "monotonic_ms": float64(time.Since(s.origin).Microseconds()) / 1000}
|
||||
for k, v := range data {
|
||||
row[k] = v
|
||||
if _, reserved := row[k]; !reserved {
|
||||
row[k] = v
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(row)
|
||||
if err != nil || len(raw) > 8000 {
|
||||
row = map[string]any{"source": "node", "event": "diagnostic_record_omitted", "collector": source, "capture_id": s.devID, "record_sequence": s.devSequence, "at_utc": time.Now().UTC().Format(time.RFC3339Nano), "reason": "record_size_bound", "bytes": len(raw)}
|
||||
}
|
||||
s.devEvents = append(s.devEvents, row)
|
||||
if len(s.devEvents) > 64 {
|
||||
s.devEvents = s.devEvents[len(s.devEvents)-64:]
|
||||
if len(s.devEvents) > 256 {
|
||||
s.devEvents = s.devEvents[len(s.devEvents)-256:]
|
||||
}
|
||||
}
|
||||
func (s *roverStreamState) devRequest() map[string]any {
|
||||
@@ -128,7 +144,29 @@ func (s *roverStreamState) devRequest() map[string]any {
|
||||
for k, v := range s.devDesired {
|
||||
result[k] = v
|
||||
}
|
||||
result["relay_events"] = append([]map[string]any{}, s.devEvents...)
|
||||
// The motor plugin owns only its original six options. Node owns new sources.
|
||||
if options, ok := result["options"].(map[string]any); ok {
|
||||
legacy := map[string]any{}
|
||||
for _, key := range []string{"live", "core_trace", "motor_samples", "network", "live_kbps", "core_kbps"} {
|
||||
legacy[key] = options[key]
|
||||
}
|
||||
result["options"] = legacy
|
||||
}
|
||||
// Each native exchange accepts at most 64 records. Disk ACK, not WAN ACK,
|
||||
// advances this cursor, so a disconnected Core cannot discard local evidence.
|
||||
ack := float64(0)
|
||||
if storage, ok := s.devPacket["storage"].(map[string]any); ok {
|
||||
if external, ok := storage["external_ack"].(map[string]any); ok {
|
||||
ack, _ = external["node"].(float64)
|
||||
}
|
||||
}
|
||||
pending := []map[string]any{}
|
||||
for _, row := range s.devEvents {
|
||||
if seq, ok := row["record_sequence"].(int64); ok && float64(seq) > ack && len(pending) < 64 {
|
||||
pending = append(pending, row)
|
||||
}
|
||||
}
|
||||
result["relay_events"] = pending
|
||||
return result
|
||||
}
|
||||
func (s *roverStreamState) devPayload() map[string]any {
|
||||
@@ -146,6 +184,7 @@ func (s *roverStreamState) devPayload() map[string]any {
|
||||
return map[string]any{"id": s.devID, "active": false, "storage": storage, "frames": []any{}}
|
||||
}
|
||||
}
|
||||
result["options"] = s.devDesired["options"]
|
||||
pending := []map[string]any{}
|
||||
for _, event := range s.devEvents {
|
||||
if seq, ok := event["record_sequence"].(int64); ok && seq > s.devRelayAfter {
|
||||
|
||||
@@ -39,10 +39,10 @@ func TestDevDoesNotExtendMotionLease(t *testing.T) {
|
||||
if s.command != nil || s.stopRevision != before || !s.stopPending {
|
||||
t.Fatal("DEV changed motion authority")
|
||||
}
|
||||
for i := 0; i < 100; i++ {
|
||||
for i := 0; i < 400; i++ {
|
||||
s.recordDev("sample", nil)
|
||||
}
|
||||
if len(s.devEvents) != 64 {
|
||||
if len(s.devEvents) != 256 {
|
||||
t.Fatal("unbounded relay RAM")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// One bounded writer for the process, not a goroutine per tick or per relay.
|
||||
// A stalled journal can lose explicitly counted diagnostic batches; it cannot
|
||||
// stall motor delivery or telemetry. Command and DEV queues are separate.
|
||||
type roverDiagnosticSink struct {
|
||||
queue chan []byte
|
||||
dropped atomic.Uint64
|
||||
}
|
||||
|
||||
func (s *roverDiagnosticSink) offer(raw []byte) {
|
||||
select {
|
||||
case s.queue <- raw:
|
||||
default:
|
||||
s.dropped.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *roverDiagnosticSink) run(write func([]byte)) {
|
||||
for raw := range s.queue {
|
||||
write(raw)
|
||||
}
|
||||
}
|
||||
|
||||
var roverJournal = sync.OnceValue(func() *roverDiagnosticSink {
|
||||
s := &roverDiagnosticSink{queue: make(chan []byte, 16)}
|
||||
go s.run(func(raw []byte) { log.Printf("%s", raw) })
|
||||
return s
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverDiagnosticWriterCannotBlockProducer(t *testing.T) {
|
||||
s := &roverDiagnosticSink{queue: make(chan []byte, 16)}
|
||||
entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
first := true
|
||||
s.run(func([]byte) {
|
||||
if first {
|
||||
first = false
|
||||
close(entered)
|
||||
<-release
|
||||
}
|
||||
})
|
||||
}()
|
||||
defer func() { close(release); close(s.queue); <-done }()
|
||||
s.offer([]byte("first"))
|
||||
<-entered
|
||||
offered := make(chan struct{})
|
||||
go func() {
|
||||
for i := 0; i < 100; i++ {
|
||||
s.offer([]byte("bounded"))
|
||||
}
|
||||
close(offered)
|
||||
}()
|
||||
select {
|
||||
case <-offered:
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("journal stalled critical producer")
|
||||
}
|
||||
if len(s.queue) != 16 || s.dropped.Load() != 84 {
|
||||
t.Fatal("overflow not bounded or counted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverCycleEvidenceSeparatesWorkFromScheduling(t *testing.T) {
|
||||
at := time.Now()
|
||||
s := newRoverStreamState(at)
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": true, "options": map[string]any{"network": true, "passive": true}})
|
||||
var timing roverCycleTiming
|
||||
timing.finish(at, at.Add(2*time.Millisecond), at.Add(3*time.Millisecond))
|
||||
timing.begin(s, at.Add(630*time.Millisecond))
|
||||
if len(s.devEvents) != 1 {
|
||||
t.Fatal("gap missing")
|
||||
}
|
||||
row := s.devEvents[0]
|
||||
if row["gap_ms"] != float64(630) || row["previous_delivery_ms"] != float64(2) || row["previous_diagnostics_ms"] != float64(1) || row["outside_cycle_ms"] != float64(627) {
|
||||
t.Fatal(row)
|
||||
}
|
||||
s.devEnabled = false
|
||||
timing.begin(s, at.Add(time.Second))
|
||||
if len(s.devEvents) != 1 {
|
||||
t.Fatal("DEV-off retained evidence")
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package node
|
||||
// Both lanes use the relay epoch and one origin. Reporting never renews a lease.
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -119,12 +118,13 @@ func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
|
||||
Reason string `json:"reason"`
|
||||
ControlSession string `json:"control_session,omitempty"`
|
||||
Frames []roverFrame `json:"frames"`
|
||||
JournalDropped uint64 `json:"journal_dropped_batches"`
|
||||
}{"rover-channel", "missioncore.rover-timeline/v1", d.epoch, d.lane,
|
||||
d.started.UTC().Format(time.RFC3339Nano), reason, d.controlSession, d.frames[first:]})
|
||||
d.started.UTC().Format(time.RFC3339Nano), reason, d.controlSession, d.frames[first:], roverJournal().dropped.Load()})
|
||||
if d.emit != nil {
|
||||
d.emit(raw)
|
||||
} else {
|
||||
log.Printf("%s", raw)
|
||||
roverJournal().offer(raw)
|
||||
}
|
||||
d.lastEmit, d.emitted = at, d.index
|
||||
d.pendingReason = ""
|
||||
|
||||
@@ -92,7 +92,7 @@ func boundedDevPacket(packet map[string]any) map[string]any {
|
||||
// old row must not permanently block newer evidence; full rows stay on disk.
|
||||
for i := len(rows) - 1; i >= 0; i-- {
|
||||
raw, _ := json.Marshal(rows[i])
|
||||
if used+len(raw)+1 > allowance {
|
||||
if used+len(raw)+1 > allowance || len(kept) >= 64 {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, rows[i])
|
||||
@@ -144,7 +144,7 @@ func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint str
|
||||
lastExport := ""
|
||||
for ctx.Err() == nil {
|
||||
state.mu.Lock()
|
||||
enabled := state.diagnosticLane && (state.diagnosticPending == nil || *state.diagnosticPending || state.devEnabled)
|
||||
enabled := state.diagnosticLane && (state.diagnosticPending == nil || *state.diagnosticPending || (state.devEnabled && !devPassive(state.devDesired["options"])))
|
||||
state.mu.Unlock()
|
||||
if !enabled {
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
@@ -162,6 +162,7 @@ func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint str
|
||||
delete(packet, "export")
|
||||
}
|
||||
payload["diagnostic_export_v2"] = true
|
||||
payload["diagnostic_passive_v1"] = true
|
||||
payload["diagnostics"] = boundedDevPacket(packet)
|
||||
raw, _ := json.Marshal(payload)
|
||||
// On capable peers idle DEV sleeps until the existing telemetry reply
|
||||
@@ -176,11 +177,17 @@ func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint str
|
||||
if err == nil {
|
||||
var reply struct {
|
||||
Diagnostics map[string]any `json:"diagnostics"`
|
||||
Pending *bool `json:"diagnostics_pending"`
|
||||
}
|
||||
err = json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&reply)
|
||||
response.Body.Close()
|
||||
if err == nil && response.StatusCode == 200 {
|
||||
state.setDev(reply.Diagnostics)
|
||||
if reply.Pending != nil {
|
||||
state.mu.Lock()
|
||||
state.diagnosticPending = reply.Pending
|
||||
state.mu.Unlock()
|
||||
}
|
||||
if exportKey != "" {
|
||||
lastExport = exportKey
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) bool {
|
||||
func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState, diagnostic *roverLinkDiagnostic) bool {
|
||||
started := time.Now()
|
||||
raw, _ := json.Marshal(base)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-link", bytes.NewReader(raw))
|
||||
@@ -30,28 +30,37 @@ func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint st
|
||||
if err == nil {
|
||||
status = response.StatusCode
|
||||
var reply struct {
|
||||
LatestDatagram bool `json:"latest_datagram_v1"`
|
||||
RoverDetails bool `json:"rover_details_v1"`
|
||||
BudgetInterval bool `json:"budget_interval_v1"`
|
||||
DiagnosticLane bool `json:"diagnostic_lane_v1"`
|
||||
Connected bool `json:"connected"`
|
||||
SampleClock bool `json:"sample_clock_v1"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
LatestDatagram bool `json:"latest_datagram_v1"`
|
||||
RoverDetails bool `json:"rover_details_v1"`
|
||||
BudgetInterval bool `json:"budget_interval_v1"`
|
||||
DiagnosticLane bool `json:"diagnostic_lane_v1"`
|
||||
Connected bool `json:"connected"`
|
||||
TelemetryOverlap bool `json:"telemetry_overlap_v1"`
|
||||
SampleClock bool `json:"sample_clock_v1"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
}
|
||||
err = json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&reply)
|
||||
response.Body.Close()
|
||||
ok = err == nil && status == 200 && reply.Connected
|
||||
state.mu.Lock()
|
||||
previousClock := state.clockID
|
||||
state.mu.Unlock()
|
||||
stamped := ok && reply.SampleClock
|
||||
if stamped {
|
||||
ok = state.sampleClock(reply.Clock, started, time.Now())
|
||||
}
|
||||
state.mu.Lock()
|
||||
state.telemetryStamped = stamped && ok
|
||||
state.telemetryOverlap = ok && reply.TelemetryOverlap
|
||||
state.diagnosticLane = ok && reply.DiagnosticLane
|
||||
state.budgetInterval = ok && reply.BudgetInterval
|
||||
state.roverDetails = ok && reply.RoverDetails
|
||||
state.latestDatagram = state.latestDatagram || (ok && reply.LatestDatagram)
|
||||
state.diagnosticPending = nil // One discovery exchange on every authenticated reconnect.
|
||||
// Passive captures do not create status exchanges on ordinary reconnects.
|
||||
// A new Core instance needs one recovery handshake for the retained file.
|
||||
if ok && (!devPassive(state.devDesired["options"]) || previousClock != reply.Clock.Instance) {
|
||||
state.diagnosticPending = nil
|
||||
}
|
||||
state.mu.Unlock()
|
||||
}
|
||||
if !ok && status == 0 {
|
||||
@@ -62,5 +71,8 @@ func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint st
|
||||
details["transport"] = trace.snapshot()
|
||||
}
|
||||
state.recordDev("link_connect", details)
|
||||
if ctx.Err() == nil {
|
||||
diagnostic.record(time.Now(), ok, status, roverErrorKind(err), time.Since(started))
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Local evidence survives a failed connection even when DEV could not start.
|
||||
// Only the telemetry goroutine owns this state. No payloads, extra probes,
|
||||
// credentials, synchronous journal IO or control authority are added.
|
||||
type roverLinkDiagnostic struct {
|
||||
failures uint64
|
||||
last time.Time
|
||||
emit func([]byte)
|
||||
}
|
||||
|
||||
func (d *roverLinkDiagnostic) record(now time.Time, ok bool, status int, reason string, elapsed time.Duration) {
|
||||
if ok && d.failures == 0 {
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
d.failures++
|
||||
if !d.last.IsZero() && now.Sub(d.last) < 30*time.Second {
|
||||
return
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{
|
||||
"event": "rover-link-health", "at_utc": now.UTC().Format(time.RFC3339Nano),
|
||||
"connected": ok, "http_status": status, "reason": reason,
|
||||
"elapsed_ms": elapsed.Milliseconds(), "failed_attempts": d.failures,
|
||||
})
|
||||
if d.emit != nil {
|
||||
d.emit(raw)
|
||||
} else {
|
||||
roverJournal().offer(raw)
|
||||
}
|
||||
d.last = now
|
||||
if ok {
|
||||
d.failures = 0
|
||||
d.last = time.Time{}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverLinkDiagnosticBoundsOutageAndRecordsRecoveryWithoutDEV(t *testing.T) {
|
||||
var rows []map[string]any
|
||||
d := roverLinkDiagnostic{emit: func(raw []byte) {
|
||||
var row map[string]any
|
||||
if err := json.Unmarshal(raw, &row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}}
|
||||
now := time.Now()
|
||||
d.record(now, true, 200, "", time.Millisecond)
|
||||
for i := 0; i < 120; i++ {
|
||||
d.record(now.Add(time.Duration(i)*250*time.Millisecond), false, 503, "", time.Second)
|
||||
}
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("unbounded outage logging: %d", len(rows))
|
||||
}
|
||||
d.record(now.Add(30*time.Second), false, 0, "network_timeout", 2500*time.Millisecond)
|
||||
d.record(now.Add(31*time.Second), true, 200, "", 20*time.Millisecond)
|
||||
if len(rows) != 3 || rows[2]["connected"] != true || rows[2]["failed_attempts"] != float64(121) {
|
||||
t.Fatalf("missing recovery evidence: %v", rows)
|
||||
}
|
||||
d.record(now.Add(32*time.Second), true, 200, "", time.Millisecond)
|
||||
if len(rows) != 3 {
|
||||
t.Fatal("healthy link generates journal traffic")
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func TestSampleTimeUsesConservativeLowerClockSeparateFromCommandUpper(t *testing
|
||||
captured := origin.Add(450 * time.Millisecond)
|
||||
s.deliveredAt(map[string]any{}, 0, captured)
|
||||
_, clock := s.telemetryView()
|
||||
if clock == nil || clock.MonotonicMS > 10050 || clock.MonotonicMS < 10040 {
|
||||
if clock == nil || clock.MonotonicMS != 10000 {
|
||||
t.Fatalf("incorrect capture bound: %+v", clock)
|
||||
}
|
||||
if s.upperMS < 10000 {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Core send precedes Node receipt, which must precede measurement capture.
|
||||
// The exact Core value is therefore a causal lower bound: no clock-rate model,
|
||||
// wall-clock synchronisation, RTT/2 or advance of a remembered extremum.
|
||||
type observationClockAnchor struct {
|
||||
clock roverClock
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func (s *roverStreamState) observeLowerClock(c roverClock, received time.Time) {
|
||||
if c.Instance != s.clockID || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 {
|
||||
return
|
||||
}
|
||||
s.observationClocks = append(s.observationClocks, observationClockAnchor{c, received})
|
||||
if len(s.observationClocks) > 64 {
|
||||
copy(s.observationClocks, s.observationClocks[len(s.observationClocks)-64:])
|
||||
s.observationClocks = s.observationClocks[:64]
|
||||
}
|
||||
}
|
||||
|
||||
// Called under mu exactly once for each new local snapshot. Replaying an old
|
||||
// snapshot or receiving a newer response cannot renew its original timestamp.
|
||||
func (s *roverStreamState) observationClockAt(sampled time.Time) roverClock {
|
||||
bound := roverClock{Instance: s.clockID}
|
||||
for _, a := range s.observationClocks {
|
||||
if a.clock.Instance == s.clockID && !a.at.After(sampled) && sampled.Sub(a.at) <= 2*time.Second && a.clock.MonotonicMS > bound.MonotonicMS {
|
||||
bound = a.clock
|
||||
}
|
||||
}
|
||||
return bound
|
||||
}
|
||||
|
||||
// Authenticated rejection recovery changes observation calibration only.
|
||||
// A different Core epoch still requires the ordinary negotiated handshake.
|
||||
func (s *roverStreamState) resetObservationClock(c roverClock, received time.Time) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if c.Instance != s.clockID || c.Instance == "" || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 {
|
||||
return false
|
||||
}
|
||||
s.observationClocks = nil
|
||||
s.snapshotClock = roverClock{Instance: s.clockID}
|
||||
s.observeLowerClock(c, received)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestObservationClockCausalAcrossRateChangesAndAsymmetricDelays(t *testing.T) {
|
||||
for _, ppm := range []float64{-10000, -1500, 0, 1500, 10000} {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.telemetryStamped = true
|
||||
core := func(localMS float64) float64 { return 100000 + localMS*(1+ppm/1e6) }
|
||||
for i := 0; i < 6000; i++ {
|
||||
localMS := float64(i * 100)
|
||||
receipt := origin.Add(time.Duration(localMS) * time.Millisecond)
|
||||
// Core reply was created 20..70 ms before receipt. Some old replies
|
||||
// arrive after a newer datagram, just like the captured incident.
|
||||
c := roverClock{testClockID, core(localMS - float64(20+i%51))}
|
||||
s.sampleClock(c, receipt.Add(-100*time.Millisecond), receipt)
|
||||
if i%7 == 0 {
|
||||
s.sampleClock(roverClock{testClockID, core(localMS - 900)}, receipt.Add(-time.Second), receipt.Add(time.Millisecond))
|
||||
}
|
||||
captureMS := localMS + 10
|
||||
s.deliveredAt(map[string]any{}, 0, origin.Add(time.Duration(captureMS)*time.Millisecond))
|
||||
_, bound := s.telemetryView()
|
||||
if bound == nil || bound.MonotonicMS > core(captureMS) || core(captureMS)-bound.MonotonicMS > 100 {
|
||||
t.Fatalf("ppm=%v i=%d invalid observation bound: %+v", ppm, i, bound)
|
||||
}
|
||||
if len(s.observationClocks) > 64 || s.command != nil {
|
||||
t.Fatal("unbounded anchors or renewed authority")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestObservationCannotUseResponseReceivedDuringOrAfterCapture(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.telemetryStamped = true
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 10200}}, origin.Add(250*time.Millisecond))
|
||||
s.deliveredAt(map[string]any{}, 0, origin.Add(100*time.Millisecond))
|
||||
_, before := s.telemetryView()
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 999999}}, origin.Add(time.Second))
|
||||
_, after := s.telemetryView()
|
||||
if before.MonotonicMS != 10000 || *after != *before {
|
||||
t.Fatal("response rejuvenated an earlier measurement", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObservationMissingExpiredOrResetAnchorFailsClosed(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.telemetryStamped = true
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
s.deliveredAt(map[string]any{}, 0, origin.Add(3*time.Second))
|
||||
_, missing := s.telemetryView()
|
||||
if missing == nil || missing.MonotonicMS != 0 {
|
||||
t.Fatal("expired anchor used")
|
||||
}
|
||||
upper, seen, stop := s.upperMS, s.clockSeen, s.stopRevision
|
||||
if !s.resetObservationClock(roverClock{testClockID, 13000}, origin.Add(3*time.Second)) {
|
||||
t.Fatal("reset failed")
|
||||
}
|
||||
_, old := s.telemetryView()
|
||||
if old == nil || old.MonotonicMS != 0 || s.upperMS != upper || s.clockSeen != seen || s.stopRevision != stop {
|
||||
t.Fatal("recovery renewed sample or command authority")
|
||||
}
|
||||
s.deliveredAt(map[string]any{}, 0, origin.Add(3100*time.Millisecond))
|
||||
_, fresh := s.telemetryView()
|
||||
if fresh.MonotonicMS != 13000 {
|
||||
t.Fatal("new capture did not recover", fresh)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypedObservationRecoveryDoesNotResetTransportOrRenewAuthority(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
s.clockID = testClockID
|
||||
r := roverTelemetryResult{finished: time.Now(), frame: roverFrame{Status: 400, Stage: "telemetry_response"}, reply: roverStreamReply{ErrorCode: "sample_clock", Clock: roverClock{testClockID, 10000}}}
|
||||
if !recoverTelemetryRejection(r, s) || !s.clockSeen.IsZero() || s.command != nil {
|
||||
t.Fatal("clock recovery touched authority")
|
||||
}
|
||||
r.reply.ErrorCode = "metadata_refresh"
|
||||
if !recoverTelemetryRejection(r, s) {
|
||||
t.Fatal("metadata recovery reconnects")
|
||||
}
|
||||
r.reply.ErrorCode = "arbitrary secret"
|
||||
if recoverTelemetryRejection(r, s) || telemetryRejectionCode(r.reply.ErrorCode) != "unclassified_rejection" {
|
||||
t.Fatal("untrusted reason")
|
||||
}
|
||||
r.reply.ErrorCode = "sample_clock"
|
||||
r.reply.Clock.Instance = "cccccccccccccccccccccccccccccccc"
|
||||
if recoverTelemetryRejection(r, s) {
|
||||
t.Fatal("foreign epoch admitted")
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type roverClock struct {
|
||||
MonotonicMS float64 `json:"monotonic_ms"`
|
||||
}
|
||||
type roverStreamReply struct {
|
||||
ErrorCode string `json:"error_code"`
|
||||
CoreProcessingMS float64 `json:"core_processing_ms"`
|
||||
ControlActive *bool `json:"control_active"`
|
||||
DiagnosticsPending *bool `json:"diagnostics_pending"`
|
||||
@@ -25,41 +26,42 @@ type roverStreamReply struct {
|
||||
// clocks. Server time was sampled after that send, so it gives an upper bound
|
||||
// on server-minus-local monotonic offset even on an asymmetric network.
|
||||
type roverStreamState struct {
|
||||
budget *LinkBudget
|
||||
latestDatagram bool
|
||||
roverDetails bool
|
||||
diagnosticLane bool
|
||||
budgetInterval bool
|
||||
diagnosticPending *bool
|
||||
devID string
|
||||
devEnabled bool
|
||||
devDesired map[string]any
|
||||
devAfter any
|
||||
devRelayAfter int64
|
||||
devSequence int64
|
||||
devEvents []map[string]any
|
||||
devPacket map[string]any
|
||||
devBudgetAt time.Time
|
||||
mu sync.Mutex
|
||||
origin time.Time
|
||||
clockID string
|
||||
upperMS float64
|
||||
anchored time.Time
|
||||
clockSeen time.Time
|
||||
streamReceived time.Time
|
||||
stopCause string
|
||||
command map[string]any
|
||||
watch bool
|
||||
stopPending bool
|
||||
stopRevision uint64
|
||||
snapshotAt time.Time
|
||||
telemetryStamped bool
|
||||
lowerClockMS float64
|
||||
lowerClockAt time.Time
|
||||
snapshot map[string]any
|
||||
retired map[string]bool
|
||||
inhibited bool
|
||||
wake chan struct{}
|
||||
budget *LinkBudget
|
||||
latestDatagram bool
|
||||
roverDetails bool
|
||||
diagnosticLane bool
|
||||
budgetInterval bool
|
||||
diagnosticPending *bool
|
||||
devID string
|
||||
devEnabled bool
|
||||
devDesired map[string]any
|
||||
devAfter any
|
||||
devRelayAfter int64
|
||||
devSequence int64
|
||||
devEvents []map[string]any
|
||||
devPacket map[string]any
|
||||
devBudgetAt time.Time
|
||||
mu sync.Mutex
|
||||
origin time.Time
|
||||
clockID string
|
||||
upperMS float64
|
||||
anchored time.Time
|
||||
clockSeen time.Time
|
||||
streamReceived time.Time
|
||||
stopCause string
|
||||
command map[string]any
|
||||
watch bool
|
||||
stopPending bool
|
||||
stopRevision uint64
|
||||
snapshotAt time.Time
|
||||
telemetryStamped bool
|
||||
telemetryOverlap bool
|
||||
observationClocks []observationClockAnchor
|
||||
snapshotClock roverClock
|
||||
snapshot map[string]any
|
||||
retired map[string]bool
|
||||
inhibited bool
|
||||
wake chan struct{}
|
||||
}
|
||||
|
||||
func newRoverStreamState(now time.Time) *roverStreamState {
|
||||
@@ -85,7 +87,7 @@ func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) b
|
||||
if c.Instance != s.clockID {
|
||||
s.invalidateCause("core_clock_changed")
|
||||
s.clockID = c.Instance
|
||||
s.lowerClockAt = time.Time{}
|
||||
s.observationClocks = nil
|
||||
s.upperMS = upper
|
||||
s.anchored = received
|
||||
} else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 {
|
||||
@@ -97,27 +99,6 @@ func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) b
|
||||
return true
|
||||
}
|
||||
|
||||
// Called with s.mu held. Every authenticated Core clock is a lower bound at
|
||||
// local receipt. A slow response cannot erase a tighter bound already learned
|
||||
// from another exchange or the command stream. Advance the old bound with the
|
||||
// same conservative 1000 ppm drift allowance as telemetryView; never use RTT/2.
|
||||
// This only timestamps observations. It does not touch the command-clock upper
|
||||
// bound, clockSeen, original expiry, stop barrier or any motion authority.
|
||||
func (s *roverStreamState) observeLowerClock(c roverClock, received time.Time) {
|
||||
if c.Instance != s.clockID || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 {
|
||||
return
|
||||
}
|
||||
lower := c.MonotonicMS
|
||||
if !s.lowerClockAt.IsZero() {
|
||||
delta := float64(received.Sub(s.lowerClockAt).Microseconds()) / 1000
|
||||
if delta < 0 {
|
||||
return
|
||||
}
|
||||
lower = math.Max(lower, s.lowerClockMS+delta-delta*.001)
|
||||
}
|
||||
s.lowerClockMS, s.lowerClockAt = lower, received
|
||||
}
|
||||
|
||||
func (s *roverStreamState) accept(reply roverStreamReply) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -244,6 +225,7 @@ func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sam
|
||||
defer s.mu.Unlock()
|
||||
s.snapshotAt = sampled
|
||||
s.snapshot = snapshot
|
||||
s.snapshotClock = s.observationClockAt(sampled)
|
||||
if stop != 0 && stop == s.stopRevision {
|
||||
s.stopPending = false
|
||||
}
|
||||
@@ -255,19 +237,17 @@ func (s *roverStreamState) view() (map[string]any, bool) {
|
||||
}
|
||||
func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() }
|
||||
|
||||
// Conservative capture time in the Core epoch: the reply clock was sampled
|
||||
// before local receipt. Subtract drift/quantization margin, never RTT/2.
|
||||
// This is observation age only; command authority still uses its upper bound.
|
||||
// Frozen causal bound from capture, never extrapolated between host clocks.
|
||||
// No anchor yields epoch/zero, not an unstamped (receipt-time) observation.
|
||||
func (s *roverStreamState) telemetryView() (map[string]any, *roverClock) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.telemetryStamped || s.lowerClockAt.IsZero() || s.snapshotAt.IsZero() {
|
||||
if !s.telemetryStamped {
|
||||
return s.snapshot, nil
|
||||
}
|
||||
delta := float64(s.snapshotAt.Sub(s.lowerClockAt).Microseconds()) / 1000
|
||||
stamp := s.lowerClockMS + delta - 5 - math.Abs(delta)*.001
|
||||
if stamp < 0 {
|
||||
stamp = 0
|
||||
stamp := s.snapshotClock
|
||||
if stamp.Instance != s.clockID {
|
||||
stamp = roverClock{Instance: s.clockID}
|
||||
}
|
||||
return s.snapshot, &roverClock{s.clockID, stamp}
|
||||
return s.snapshot, &stamp
|
||||
}
|
||||
|
||||
@@ -245,7 +245,7 @@ func TestDelayedHTTPClockCannotMakeNewTelemetryArtificiallyStale(t *testing.T) {
|
||||
s.deliveredAt(map[string]any{"state": "observing"}, 0, origin.Add(850*time.Millisecond))
|
||||
s.sampleClock(roverClock{testClockID, 10050}, origin.Add(50*time.Millisecond), origin.Add(900*time.Millisecond))
|
||||
_, stamp := s.telemetryView()
|
||||
if stamp == nil || stamp.MonotonicMS < 10790 || stamp.MonotonicMS > 10850 {
|
||||
if stamp == nil || stamp.MonotonicMS != 10750 {
|
||||
t.Fatal("late response rolled the observation clock backwards", stamp)
|
||||
}
|
||||
// No new measurement: advancing the bounds cannot rejuvenate the sample.
|
||||
@@ -263,7 +263,7 @@ func TestObservationClockEpochAndInvalidSamplesCannotReuseOldBound(t *testing.T)
|
||||
s.telemetryStamped = true
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{"foreign", 99999}}, origin.Add(time.Millisecond))
|
||||
if s.lowerClockMS != 10000 {
|
||||
if len(s.observationClocks) != 1 || s.observationClocks[0].clock.MonotonicMS != 10000 {
|
||||
t.Fatal("foreign clock changed lower bound")
|
||||
}
|
||||
next := "cccccccccccccccccccccccccccccccc"
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package node
|
||||
|
||||
// Bounded latest-snapshot publication. A delayed reply may occupy one slot,
|
||||
// never the next sampling tick. No queue, replay, or command authority here.
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roverTelemetryResult struct {
|
||||
sequence uint64
|
||||
revision uint64
|
||||
started time.Time
|
||||
finished time.Time
|
||||
snapshot map[string]any
|
||||
clock *roverClock
|
||||
reply roverStreamReply
|
||||
frame roverFrame
|
||||
trace *roverHTTPTrace
|
||||
err error
|
||||
}
|
||||
|
||||
func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var workers sync.WaitGroup
|
||||
defer func() { cancel(); workers.Wait() }()
|
||||
epoch, _ := base["relay_id"].(string)
|
||||
diagnostic := roverDiagnostics{lane: "telemetry", epoch: epoch, started: state.origin}
|
||||
var connectionDiagnostic roverLinkDiagnostic
|
||||
results := make(chan roverTelemetryResult, 2)
|
||||
var metadata roverMetadataEncoder
|
||||
var budgetAt time.Time
|
||||
var sequence, applied, acknowledgedRevision uint64
|
||||
var retryAfter time.Time
|
||||
failures := 0
|
||||
pending := 0
|
||||
connected := false
|
||||
next := time.Now()
|
||||
for ctx.Err() == nil {
|
||||
if !connected && pending == 0 {
|
||||
if wait := time.Until(retryAfter); wait > 0 && !roverWait(ctx, wait) {
|
||||
return
|
||||
}
|
||||
connected = roverConnectTelemetry(ctx, client, endpoint, base, state, &connectionDiagnostic)
|
||||
metadata.reset()
|
||||
acknowledgedRevision = 0
|
||||
budgetAt = time.Time{}
|
||||
if !connected {
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
next = time.Now()
|
||||
}
|
||||
timer := time.NewTimer(max(0, time.Until(next)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case result := <-results:
|
||||
timer.Stop()
|
||||
pending--
|
||||
if result.frame.Stage == "" && result.sequence > applied && !state.sampleClock(result.reply.Clock, result.started, result.finished) {
|
||||
result.frame.Stage = "clock_invalid"
|
||||
state.stopStream()
|
||||
}
|
||||
frame := result.frame
|
||||
state.recordDev("telemetry", roverTelemetryEvidence(result, state, epoch))
|
||||
diagnostic.record(result.started, frame)
|
||||
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
|
||||
state.budget.ObserveExchange(time.Duration(frame.CoreMS)*time.Millisecond, frame.CoreProcessingMS, frame.Stage == "")
|
||||
}
|
||||
if frame.Stage != "" {
|
||||
// An older failed request cannot invalidate a newer successful exchange.
|
||||
if result.sequence > applied {
|
||||
metadata.reset()
|
||||
acknowledgedRevision = 0
|
||||
connected = recoverTelemetryRejection(result, state)
|
||||
failures = min(failures+1, 4)
|
||||
retryAfter = time.Now().Add(time.Duration(1<<failures) * 100 * time.Millisecond)
|
||||
next = retryAfter
|
||||
}
|
||||
continue
|
||||
}
|
||||
acknowledgedRevision = max(acknowledgedRevision, result.revision)
|
||||
if result.sequence <= applied {
|
||||
continue
|
||||
}
|
||||
applied = result.sequence
|
||||
failures = 0
|
||||
retryAfter = time.Time{}
|
||||
connected = true
|
||||
state.mu.Lock()
|
||||
state.diagnosticPending = result.reply.DiagnosticsPending
|
||||
hasIntent := state.command != nil
|
||||
state.mu.Unlock()
|
||||
state.budget.SetControl(roverControlActive(result.snapshot, hasIntent, result.reply.ControlActive))
|
||||
state.setWatch(result.reply.Watch)
|
||||
state.setDev(result.reply.Diagnostics)
|
||||
case <-timer.C:
|
||||
_, watch := state.view()
|
||||
interval := 500 * time.Millisecond
|
||||
if watch {
|
||||
interval = 100 * time.Millisecond
|
||||
}
|
||||
next = time.Now().Add(interval)
|
||||
state.mu.Lock()
|
||||
overlap := state.telemetryStamped && state.telemetryOverlap
|
||||
state.mu.Unlock()
|
||||
limit := 1
|
||||
if overlap {
|
||||
limit = 2
|
||||
}
|
||||
if !connected || pending >= limit {
|
||||
state.recordDev("telemetry_sample_skipped", map[string]any{"reason": "publication_slots_busy", "pending": pending})
|
||||
continue
|
||||
}
|
||||
started := time.Now()
|
||||
snapshot, sampleClock := state.telemetryView()
|
||||
payload := make(map[string]any, len(base)+8)
|
||||
for k, v := range base {
|
||||
payload[k] = v
|
||||
}
|
||||
payload["rover"] = snapshot
|
||||
state.mu.Lock()
|
||||
compact, budgetInterval, dedicated := state.roverDetails, state.budgetInterval, state.diagnosticLane
|
||||
state.mu.Unlock()
|
||||
revision := uint64(0)
|
||||
if compact {
|
||||
live, details := metadata.encode(snapshot, started)
|
||||
if details != nil {
|
||||
revision = metadata.revision
|
||||
if revision > acknowledgedRevision {
|
||||
metadata.reset()
|
||||
live, details = metadata.encode(snapshot, started)
|
||||
}
|
||||
payload["rover"], payload["rover_details_v1"] = live, details
|
||||
}
|
||||
}
|
||||
if state.budget != nil && (!budgetInterval || budgetAt.IsZero() || started.Sub(budgetAt) >= time.Second) {
|
||||
payload["link_budget"] = state.budget.Snapshot()
|
||||
budgetAt = started
|
||||
}
|
||||
sequence++
|
||||
if overlap {
|
||||
payload["observation_id"] = sequence
|
||||
}
|
||||
if sampleClock != nil {
|
||||
payload["sample_clock"] = sampleClock
|
||||
}
|
||||
payload["diagnostic_lane_v1"], payload["diagnostic_options_v1"], payload["diagnostic_sources_v1"], payload["diagnostic_passive_v1"] = dedicated, true, true, true
|
||||
if !dedicated {
|
||||
if dev := state.devPayload(); dev != nil {
|
||||
payload["diagnostics"] = dev
|
||||
payload["diagnostic_relay_ack_v1"] = true
|
||||
}
|
||||
}
|
||||
// Capture at the actual publication opportunity, not while waiting for a slot.
|
||||
result := roverTelemetryResult{sequence: sequence, revision: revision, started: started, snapshot: snapshot, clock: sampleClock}
|
||||
pending++
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
results <- sendRoverTelemetry(ctx, client, endpoint, payload, result, state)
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sendRoverTelemetry(ctx context.Context, client *http.Client, endpoint string, payload map[string]any, result roverTelemetryResult, state *roverStreamState) roverTelemetryResult {
|
||||
marshalAt := time.Now()
|
||||
raw, _ := json.Marshal(payload)
|
||||
frame := roverFrame{MarshalMS: float64(time.Since(marshalAt).Microseconds()) / 1000, RequestBytes: len(raw), ReleaseConfirmed: roverReleaseEvidence(result.snapshot)}
|
||||
frame.State, _ = result.snapshot["state"].(string)
|
||||
if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" {
|
||||
frame.Session, _ = result.snapshot["session_id"].(string)
|
||||
}
|
||||
state.budget.ObserveCriticalBytes(len(raw))
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if state.devTraceEnabled() {
|
||||
result.trace = newRoverHTTPTrace(result.started, len(raw))
|
||||
req = req.WithContext(result.trace.context(req.Context()))
|
||||
}
|
||||
requestClient := *client
|
||||
if result.clock != nil {
|
||||
requestClient.Timeout = 2 * time.Second
|
||||
}
|
||||
response, err := requestClient.Do(req)
|
||||
if err != nil {
|
||||
frame.Stage = "telemetry_transport"
|
||||
} else {
|
||||
frame.Status = response.StatusCode
|
||||
readErr := json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&result.reply)
|
||||
response.Body.Close()
|
||||
if readErr != nil || response.StatusCode != 200 {
|
||||
frame.Stage = "telemetry_response"
|
||||
err = readErr
|
||||
} else {
|
||||
frame.CoreProcessingMS = result.reply.CoreProcessingMS
|
||||
}
|
||||
}
|
||||
result.finished = time.Now()
|
||||
frame.CoreMS = result.finished.Sub(result.started).Milliseconds()
|
||||
result.frame, result.err = frame, err
|
||||
return result
|
||||
}
|
||||
|
||||
func roverTelemetryEvidence(r roverTelemetryResult, state *roverStreamState, epoch string) map[string]any {
|
||||
f := r.frame
|
||||
d := map[string]any{"elapsed_ms": f.CoreMS, "http_status": f.Status, "error_stage": f.Stage, "reason": roverErrorKind(r.err), "marshal_ms": f.MarshalMS, "request_bytes": f.RequestBytes, "core_processing_ms": f.CoreProcessingMS, "epoch": epoch, "sample_mono_ms": float64(r.started.Sub(state.origin).Microseconds()) / 1000, "observation_id": r.sequence, "reply_core_mono_ms": r.reply.Clock.MonotonicMS}
|
||||
if f.Stage == "telemetry_response" {
|
||||
d["rejection_code"] = telemetryRejectionCode(r.reply.ErrorCode)
|
||||
}
|
||||
if r.clock != nil {
|
||||
d["sample_core_mono_ms"] = r.clock.MonotonicMS
|
||||
d["observation_clock_model"] = "causal-core-anchor/v1"
|
||||
}
|
||||
if r.trace != nil {
|
||||
d["transport"] = r.trace.snapshot()
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package node
|
||||
|
||||
// Only an authenticated, structured application rejection is recoverable here.
|
||||
// Transport/authentication/unknown errors keep the normal negotiated handshake.
|
||||
func recoverTelemetryRejection(r roverTelemetryResult, s *roverStreamState) bool {
|
||||
if r.frame.Status != 400 || r.frame.Stage != "telemetry_response" || r.err != nil {
|
||||
return false
|
||||
}
|
||||
switch r.reply.ErrorCode {
|
||||
case "sample_clock":
|
||||
return s.resetObservationClock(r.reply.Clock, r.finished)
|
||||
case "metadata_refresh", "metadata_revision", "metadata_roster":
|
||||
return true // Caller resets only the compact metadata encoder.
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func telemetryRejectionCode(code string) string {
|
||||
switch code {
|
||||
case "sample_clock", "metadata_refresh", "metadata_revision", "metadata_roster", "metadata_envelope", "metadata_shape", "device_metadata", "compact_sample", "exchange_shape", "observation_identity", "invalid_observation":
|
||||
return code
|
||||
}
|
||||
return "unclassified_rejection"
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTelemetryOverlapPublishesLatestWhileReplyStalls(t *testing.T) {
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.delivered(map[string]any{"instance": "driver", "devices": []any{}, "generation": 1}, 0)
|
||||
state.setWatch(true)
|
||||
origin := time.Now()
|
||||
clock := func() roverClock {
|
||||
return roverClock{testClockID, 10000 + float64(time.Since(origin).Microseconds())/1000}
|
||||
}
|
||||
gate := make(chan struct{})
|
||||
first := make(chan struct{}, 1)
|
||||
latest := make(chan map[string]any, 20)
|
||||
var active, peak atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/node/rover-link" {
|
||||
json.NewEncoder(w).Encode(map[string]any{"connected": true, "sample_clock_v1": true, "telemetry_overlap_v1": true, "rover_details_v1": true, "control_clock": clock()})
|
||||
return
|
||||
}
|
||||
n := active.Add(1)
|
||||
defer active.Add(-1)
|
||||
for old := peak.Load(); n > old; old = peak.Load() {
|
||||
if peak.CompareAndSwap(old, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
id := body["observation_id"].(float64)
|
||||
if id == 1 {
|
||||
first <- struct{}{}
|
||||
select {
|
||||
case <-gate:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(roverStreamReply{Watch: false, Clock: clock()})
|
||||
return
|
||||
}
|
||||
select {
|
||||
case latest <- body:
|
||||
default:
|
||||
}
|
||||
json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: clock()})
|
||||
}))
|
||||
defer server.Close()
|
||||
transport := &http.Transport{MaxConnsPerHost: 2, MaxIdleConnsPerHost: 2}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
roverTelemetry(ctx, client, server.URL, map[string]any{"relay_id": "epoch"}, state)
|
||||
}()
|
||||
select {
|
||||
case <-first:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("first snapshot absent")
|
||||
}
|
||||
state.delivered(map[string]any{"instance": "driver", "devices": []any{}, "generation": 2}, 0)
|
||||
select {
|
||||
case body := <-latest:
|
||||
if body["rover"].(map[string]any)["generation"] != float64(2) {
|
||||
t.Fatal("queued stale snapshot")
|
||||
}
|
||||
if body["sample_clock"] == nil {
|
||||
t.Fatal("missing original sample time")
|
||||
}
|
||||
if body["rover_details_v1"].(map[string]any)["details"] == nil {
|
||||
t.Fatal("metadata reference before acknowledged revision")
|
||||
}
|
||||
case <-time.After(700 * time.Millisecond):
|
||||
t.Fatal("slow reply blocked next sample")
|
||||
}
|
||||
close(gate)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
_, watch := state.view()
|
||||
if !watch {
|
||||
t.Fatal("old reply overwrote newer watch")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("worker leaked")
|
||||
}
|
||||
if peak.Load() != 2 {
|
||||
t.Fatalf("expected bounded overlap, peak=%d", peak.Load())
|
||||
}
|
||||
if client.Timeout != 75*time.Millisecond {
|
||||
t.Fatal("shared client changed")
|
||||
}
|
||||
if state.command != nil {
|
||||
t.Fatal("telemetry created authority")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelemetryTypedRejectionsRecoverWithoutReconnectStorm(t *testing.T) {
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.setWatch(true)
|
||||
origin := time.Now()
|
||||
clock := func() roverClock {
|
||||
return roverClock{testClockID, 10000 + float64(time.Since(origin).Microseconds())/1000}
|
||||
}
|
||||
var probes, observations atomic.Int32
|
||||
accepted := make(chan struct{}, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/node/rover-link" {
|
||||
probes.Add(1)
|
||||
json.NewEncoder(w).Encode(map[string]any{"connected": true, "sample_clock_v1": true, "control_clock": clock()})
|
||||
return
|
||||
}
|
||||
n := observations.Add(1)
|
||||
if n <= 2 {
|
||||
code := "sample_clock"
|
||||
if n == 2 {
|
||||
code = "metadata_refresh"
|
||||
}
|
||||
w.WriteHeader(400)
|
||||
json.NewEncoder(w).Encode(roverStreamReply{ErrorCode: code, Clock: clock()})
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: clock()})
|
||||
select {
|
||||
case accepted <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
roverTelemetry(ctx, server.Client(), server.URL, map[string]any{"relay_id": "epoch"}, state)
|
||||
}()
|
||||
select {
|
||||
case <-accepted:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("observation recovery stuck")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("worker leaked")
|
||||
}
|
||||
if probes.Load() != 1 || observations.Load() < 3 || state.command != nil {
|
||||
t.Fatal("rejection caused reconnect or authority", probes.Load(), observations.Load())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user