fix(transport): recover rover feedback and retained WireGuard routes

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:24 +03:00
parent f4cdf3744a
commit 1e77b198cb
12 changed files with 833 additions and 30 deletions
@@ -168,6 +168,7 @@ func (b *LinkBudget) tryLocked(class string, size int) (bool, time.Duration) {
}
if h := &b.runtime.feedback; h.enabled && h.sent-h.acknowledged+uint64(cost) > h.window {
c.deferred++
h.deferred = now
return false, 10 * time.Millisecond
}
if b.tokens >= cost && c.tokens >= cost {
@@ -180,6 +181,9 @@ func (b *LinkBudget) tryLocked(class string, size int) (bool, time.Duration) {
return true, 0
}
c.deferred++
if b.runtime.feedback.enabled {
b.runtime.feedback.deferred = now
}
return false, 10 * time.Millisecond
}
@@ -2,14 +2,28 @@ package node
// Independently bound optional egress when command UDP remains healthy but the
// return path is congested. Probes never wait for permits; no authority lives here.
import "time"
import (
"math"
"time"
)
const feedbackMinWindow = uint64(linkPacket + linkOverhead)
const feedbackMaxWindow = uint64(128 * 1024)
// Credit covers one probe period (or the measured path RTT when larger).
// A fixed 128 KiB window imposed a 10.49 Mbit/s ceiling regardless of the
// existing adaptive send budget. Bound credit by that budget instead; this
// neither measures physical capacity nor relaxes silence/command guards.
func (b *LinkBudget) feedbackMaxWindow() uint64 {
period := max(100*time.Millisecond, b.baseline)
return max(uint64(linkClassBurst), uint64(math.Min(b.effective, b.ceiling())*125*period.Seconds()))
}
type linkDatagramFeedback struct {
enabled bool
seen, adjusted, healthy, delayed time.Time
deferred time.Time
recoverUntil time.Time
recoverWindow uint64
sent, acknowledged, window uint64
rtt time.Duration
limited bool
@@ -76,6 +90,10 @@ func (b *LinkBudget) feedbackLimited(now time.Time) bool {
return false
}
if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
if !h.limited {
h.recoverWindow = h.window
h.recoverUntil = h.seen.Add(5 * time.Second)
}
h.recordPressure(now, "feedback_silence", now.Sub(h.seen), h.rtt, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
// A silent return path invalidates the previously grown send window.
// Latch pressure before updating seen: one fresh ACK after a blackout
@@ -110,6 +128,7 @@ func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float
b.feedbackLimited(now)
outstanding := h.sent - h.acknowledged
gap := now.Sub(h.seen)
freshBytes := mark - h.acknowledged
h.acknowledged = mark
h.seen = now
if coreMS >= 0 && coreMS <= float64(elapsed.Microseconds())/1000 {
@@ -120,6 +139,13 @@ func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float
if h.delayed.IsZero() {
h.delayed = now
}
// The first echo after a short gap may itself have queued during the
// outage. It still suspends payload below, but is not sustained evidence
// that the previously working window is unusable. Preserve only the
// existing expiring recovery target; fresh useful ACKs must earn growth.
if now.Sub(h.delayed) >= 200*time.Millisecond {
h.recoverWindow = 0
}
// Moderate jitter shrinks outstanding optional bytes without turning a
// viable video stream off. Full suspension is reserved for severe delay
// or silence; neither condition changes command authority or watchdogs.
@@ -155,10 +181,27 @@ func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float
}
h.limited = false
}
// Grow only when useful demand used the window, at most once per probe
// period. ACK bursts after a stall cannot manufacture a large new window.
if elapsed <= b.baseline+25*time.Millisecond && outstanding >= h.window/2 && (h.adjusted.IsZero() || now.Sub(h.adjusted) >= 100*time.Millisecond) {
h.window = min(feedbackMaxWindow, h.window+linkPacket)
// A quiet primary camera can use much less than its priority allocation.
// Requiring half the window to be spent then traps waiting cloud packets
// below that allocation forever. Recent denied *real packets* may also
// probe upward when aggregate demand exceeds this window's rate. An idle
// producer declaration alone never grows credit or generates probe payload.
period := max(100*time.Millisecond, b.baseline)
waiting := !h.deferred.IsZero() && now.Sub(h.deferred) <= 100*time.Millisecond &&
b.demand(now) > float64(h.window)*8/period.Seconds()
// Retain the healthy-echo and once-per-period gates. ACK bursts after a
// stall cannot mint a large window or override command pressure.
if elapsed <= b.baseline+25*time.Millisecond && !b.commandLimited(now) &&
(outstanding >= h.window/2 || waiting) && (h.adjusted.IsZero() || now.Sub(h.adjusted) >= 100*time.Millisecond) {
growth := max(uint64(linkPacket), h.window/8)
// A recently working path may regain its previous window from fresh
// useful ACKs. Never restore tokens or jump straight to stale credit:
// at most one current window per healthy period, below both ceilings.
if now.Before(h.recoverUntil) && h.window < h.recoverWindow {
growth = max(growth, min(freshBytes, h.window, h.recoverWindow-h.window))
}
h.window = min(b.feedbackMaxWindow(), h.window+growth)
h.adjusted = now
h.deferred = time.Time{}
}
}
@@ -5,6 +5,76 @@ import (
"time"
)
func TestHealthyFeedbackRecoversWhenPriorityLeavesCloudStarved(t *testing.T) {
b, now := testBudget(t)
b.effective = 50000
b.SetControl(false)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
b.runtime.feedback.window = 64000
primary, cloud := "11111111111111111111111111111111", "33333333333333333333333333333333"
for tick := 0; tick < 300; tick++ {
*now = now.Add(10 * time.Millisecond)
if tick%50 == 0 {
b.allocateRole(primary, "video", true, 5000000, true)
b.allocateRole(cloud, "cloud", true, 8000000, false)
}
// A quiet primary image uses little of its declared bitrate. Real cloud
// packets keep waiting behind its priority share after a window collapse.
b.Try("cloud", 1000)
if tick%10 == 0 {
b.SetControl(false)
b.Try("video", 1100)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.DatagramFeedbackMark())
}
}
if b.classes["cloud"].bytes < 270000 || b.classRates(*now)["cloud"] < 800000 {
t.Fatal("healthy unsent cloud demand could not grow past the quiet primary share", b.Snapshot())
}
if b.runtime.feedback.window > b.feedbackMaxWindow() {
t.Fatal("pending demand bypassed adaptive ceiling")
}
}
func TestDeclaredDemandWithoutWaitingPacketsDoesNotGrowFeedback(t *testing.T) {
b, now := testBudget(t)
b.effective = 50000
b.SetControl(false)
b.EnableDatagramFeedback()
b.allocateRole("33333333333333333333333333333333", "cloud", true, 8000000, false)
initial := b.runtime.feedback.window
for i := 0; i < 10; i++ {
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
}
if b.runtime.feedback.window != initial {
t.Fatal("idle declaration manufactured feedback credit", b.runtime.feedback.window)
}
}
func TestHealthyFeedbackWindowFollowsAdaptiveBudgetNotFixedTenMbps(t *testing.T) {
b, now := testBudget(t)
b.effective = 50000
b.EnableDatagramFeedback()
for i := 0; i < 80; i++ {
*now = now.Add(100 * time.Millisecond)
b.SetControl(false)
b.runtime.feedback.sent += b.runtime.feedback.window
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.runtime.feedback.sent)
}
if b.runtime.feedback.window <= 128*1024 || b.optional(*now) <= 10486 {
t.Fatal("healthy useful traffic retained fixed window ceiling", b.runtime.feedback.window, b.optional(*now))
}
if b.runtime.feedback.window > b.feedbackMaxWindow() {
t.Fatal("feedback credit escaped adaptive budget")
}
*now = now.Add(300 * time.Millisecond)
b.ObserveCommandFrame(50*time.Millisecond, 10*time.Millisecond)
if b.optional(*now) != 0 {
t.Fatal("larger healthy window bypassed return-path silence")
}
}
func TestDatagramFeedbackBoundsOptionalBytesDespiteHealthyDownlink(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
@@ -64,7 +134,7 @@ func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) {
b, now := testBudget(t)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
b.runtime.feedback.window = feedbackMaxWindow
b.runtime.feedback.window = b.feedbackMaxWindow()
b.tokens = linkBurst
b.classes["video"].tokens = linkClassBurst
*now = now.Add(time.Second)
@@ -155,3 +225,77 @@ func TestDatagramFeedbackRetainsInitiatingPressureAcrossRecovery(t *testing.T) {
t.Fatal("new transport would inherit old diagnostic identity")
}
}
func TestShortFeedbackGapRecoversUsefulCloudFromFreshAcknowledgements(t *testing.T) {
b, now := testBudget(t)
b.effective = 35000
b.SetControl(false)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
b.runtime.feedback.window = 240000
*now = now.Add(300 * time.Millisecond)
b.Snapshot()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
for tick := 0; tick < 300; tick++ {
*now = now.Add(10 * time.Millisecond)
if tick%10 == 0 {
b.SetControl(false)
b.allocateRole("11111111111111111111111111111111", "video", true, 5000000, true)
b.allocateRole("33333333333333333333333333333333", "cloud", true, 8000000, false)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.DatagramFeedbackMark())
}
b.Try("video", 300)
b.Try("cloud", 1000)
}
if b.classes["cloud"].bytes < 150000 {
t.Fatal("healthy recovery kept cloud starved for three seconds", b.classes["cloud"].bytes, b.runtime.feedback.window)
}
if b.runtime.feedback.window > b.feedbackMaxWindow() {
t.Fatal("recovery bypassed adaptive ceiling")
}
}
func TestFeedbackRecoveryNeverRestoresStaleCredit(t *testing.T) {
for _, scenario := range []string{"no-new-bytes", "expired", "command-pressure", "delayed"} {
t.Run(scenario, func(t *testing.T) {
b, now := testBudget(t)
b.effective = 35000
b.EnableDatagramFeedback()
b.SetControl(false)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
h := &b.runtime.feedback
h.window = 240000
*now = now.Add(300 * time.Millisecond)
b.Snapshot()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
*now = now.Add(201 * time.Millisecond)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
h.window = 8000
h.adjusted = *now
h.sent += 8000
mark := h.sent
if scenario == "no-new-bytes" {
h.acknowledged = mark
}
if scenario == "expired" {
h.recoverUntil = *now
}
*now = now.Add(100 * time.Millisecond)
if scenario == "command-pressure" {
b.SetControl(true)
b.ObserveCommandFrame(400*time.Millisecond, 0)
}
elapsed := 15 * time.Millisecond
if scenario == "delayed" {
elapsed = 300 * time.Millisecond
}
b.ObserveDatagramFeedback(elapsed, 0, mark)
if h.window > 10048 {
t.Fatal("stale or pressured path gained recovery credit", h.window)
}
if b.tokens != 0 {
t.Fatal("recovery manufactured burst tokens", b.tokens)
}
})
}
}
@@ -0,0 +1,65 @@
package node
import (
"testing"
"time"
)
// The first returning probe can have spent the short outage in the network.
// Only later healthy acknowledgements justify recovery of useful traffic.
func TestFeedbackRecoveryAfterDelayedFirstEcho(t *testing.T) {
for _, firstRTT := range []time.Duration{15 * time.Millisecond, 300 * time.Millisecond} {
t.Run(firstRTT.String(), func(t *testing.T) {
b, now := testBudget(t)
b.effective = 35000
b.SetControl(false)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
b.runtime.feedback.window = 240000
*now = now.Add(300 * time.Millisecond)
b.Snapshot()
b.ObserveDatagramFeedback(firstRTT, 0, b.DatagramFeedbackMark())
if ok, _ := b.Try("video", 1000); ok {
t.Fatal("first returning echo reopened payload without stable feedback")
}
for tick := 0; tick < 200; tick++ {
*now = now.Add(10 * time.Millisecond)
if tick%10 == 0 {
b.SetControl(false)
b.allocateRole("11111111111111111111111111111111", "video", true, 5000000, true)
b.allocateRole("33333333333333333333333333333333", "cloud", true, 8000000, false)
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.DatagramFeedbackMark())
}
for packet := 0; packet < 8; packet++ {
b.Try("video", 1000)
b.Try("cloud", 1000)
}
}
t.Logf("window=%d video=%d cloud=%d", b.runtime.feedback.window, b.classes["video"].bytes, b.classes["cloud"].bytes)
if b.runtime.feedback.window < 128000 || b.classes["cloud"].bytes < 100000 {
t.Fatal("a delayed first echo stranded the recovered path at a low rate", b.Snapshot())
}
})
}
}
func TestFeedbackRecoveryTargetRetiresOnSustainedDelay(t *testing.T) {
b, now := testBudget(t)
b.SetControl(false)
b.EnableDatagramFeedback()
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
b.runtime.feedback.window = 240000
*now = now.Add(300 * time.Millisecond)
b.Snapshot()
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
for i := 0; i < 3; i++ {
*now = now.Add(100 * time.Millisecond)
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
if ok, _ := b.Try("video", 1000); ok {
t.Fatal("sustained delay admitted optional payload")
}
}
if b.runtime.feedback.recoverWindow != 0 || !b.runtime.feedback.limited {
t.Fatal("sustained delay retained short-gap recovery credit")
}
}
@@ -40,6 +40,81 @@ func TestExplicitOperatorViewPrecedesResidualTraffic(t *testing.T) {
}
}
func TestSecondaryVideosShareResidualWithFullCloudDemand(t *testing.T) {
b, now := testBudget(t)
b.SetControl(false)
b.effective = 10500
primary := "11111111111111111111111111111111"
b.allocateRole(primary, "video", true, 5000000, true)
b.allocateRole("22222222222222222222222222222222", "video", true, 5000000, false)
b.allocateRole("33333333333333333333333333333333", "video", true, 5000000, false)
b.allocateRole("44444444444444444444444444444444", "cloud", true, 12000000, false)
rates := b.classRates(*now)
a, _ := b.allocateRole(primary, "video", true, 5000000, true)
if a["allocation_bps"] != 5000000 || rates["cloud"] <= 500000 || rates["video"] <= 5000000 {
t.Fatal("secondary cameras inherited priority or cloud could not use residual", a, rates)
}
if rates["cloud"]+rates["video"] > b.optional(*now)*1000 {
t.Fatal("residual traffic exceeded shared budget", rates)
}
// A healthy larger allocation satisfies real demand, without a cloud ceiling.
b.effective = 50000
rates = b.classRates(*now)
if rates["cloud"] != 12000000 || rates["video"] != 15000000 {
t.Fatal("unused healthy capacity did not satisfy media demand", rates)
}
b.SetControl(true)
b.effective = b.reserve(*now) + 3000
if b.classRates(*now)["cloud"] != 0 {
t.Fatal("cloud displaced primary camera during control")
}
}
func TestObservedPrimaryAllowsBoundedCloudWithoutBorrowingControl(t *testing.T) {
b, now := testBudget(t)
primary, cloud := "11111111111111111111111111111111", "33333333333333333333333333333333"
b.SetControl(false)
b.allocateRole(primary, "video", true, 5000000, true)
b.allocateRole(cloud, "cloud", true, 256000, false)
rates := b.classRates(*now)
if rates["cloud"] != 128000 || rates["video"] <= rates["cloud"] {
t.Fatal("observing cloud starved or displaced primary video", rates)
}
if rates["cloud"]+rates["video"] > b.optional(*now)*1000 {
t.Fatal("preview floor exceeded aggregate budget", rates)
}
// Preview credit passes through the same packet gate; no separate lane.
*now = now.Add(100 * time.Millisecond)
if ok, _ := b.Try("cloud", 1000); !ok {
t.Fatal("allocated cloud could not progress through packet admission")
}
b.SetControl(true)
if b.classRates(*now)["cloud"] != 0 {
t.Fatal("cloud floor escaped active-control priority")
}
if ok, _ := b.Try("cloud", 1000); ok {
t.Fatal("old cloud credit survived protected transition")
}
b.SetControl(false)
*now = now.Add(2100 * time.Millisecond)
if b.classRates(*now)["cloud"] != 0 {
t.Fatal("cloud floor escaped stale-control priority")
}
b.SetControl(false)
b.effective = b.reserve(*now) + 128
rates = b.classRates(*now)
if rates["cloud"] <= 0 || rates["cloud"] > b.optional(*now)*1000*2/11 {
t.Fatal("weak-link cloud exceeded ordinary class share", rates)
}
b.allocateRole(cloud, "cloud", false, 256000, false)
*now = now.Add(2100 * time.Millisecond)
b.SetControl(false)
b.allocateRole(primary, "video", true, 5000000, true)
if b.classRates(*now)["cloud"] != 0 {
t.Fatal("closed preview retained a reserved floor")
}
}
func TestSelectedViewHasBoundedModerateJitterProfileAndEmergencyYield(t *testing.T) {
b, now := testBudget(t)
primary := "11111111111111111111111111111111"
+19 -8
View File
@@ -302,22 +302,33 @@ func (b *LinkBudget) classRates(now time.Time) map[string]float64 {
if b.primaryVideo(now) == "" {
return waterfill(total, linkWeights, demands)
}
// During observation, explicitly requested recording transfer must make
// bounded progress even when the selected camera demands all capacity.
// Its floor is at most the ordinary 1/11 share and 32 kbit/s, taken from
// the SAME optional budget. Active/stale control and command pressure
// retain strict primary-video priority; exports never borrow its reserve.
// During observation, requested cloud preview and recording transfer must
// make bounded progress even when the selected camera demands all capacity.
// Use their ordinary class shares, capped at 128/32 kbit/s, from the SAME
// optional budget. Active/stale control and command pressure retain strict
// primary-video priority; background traffic never borrows its reserve.
rates := map[string]float64{}
if !b.protected(now) {
rates["cloud"] = math.Min(demands["cloud"], math.Min(128000, total*2/11))
rates["bulk"] = math.Min(demands["bulk"], math.Min(32000, total/11))
total -= rates["bulk"]
total -= rates["cloud"] + rates["bulk"]
demands["cloud"] -= rates["cloud"]
demands["bulk"] -= rates["bulk"]
}
rates["inventory"] = math.Min(total, math.Min(32000, demands["inventory"]))
total -= rates["inventory"]
rates["video"] = math.Min(total, demands["video"])
// The floor guarantees progress when the camera consumes the link; it is
// not a ceiling on finite signalling/blueprint receipts. Admit the rest
// from residual capacity after the selected operator camera is satisfied.
demands["inventory"] -= rates["inventory"]
// Only the selected operator camera owns priority. Other cameras/viewers
// share residual capacity with cloud/export instead of inheriting that
// priority merely because they use the same video packet class.
primary := b.producers[b.primaryVideo(now)]
rates["video"] = math.Min(total, float64(primary.demand))
total -= rates["video"]
for key, value := range waterfill(total, map[string]float64{"cloud": 1, "bulk": 1}, demands) {
demands["video"] -= rates["video"]
for key, value := range waterfill(total, linkWeights, demands) {
rates[key] += value
}
return rates
@@ -101,3 +101,28 @@ func TestSmallInventoryDoesNotReserveAnUnlimitedStream(t *testing.T) {
t.Fatal("small metadata held camera bandwidth", rates)
}
}
// A 42 KiB compressed spatial profile formerly took >10 s on an otherwise
// healthy 35 Mbit/s path because inventory was pinned to its 32 kbit/s floor.
func TestInventoryUsesResidualCapacityWithoutTakingCameraPriority(t *testing.T) {
b, now := testBudget(t)
b.effective = 35000
b.SetControl(false)
b.allocateRole("11111111111111111111111111111111", "video", true, 5000000, true)
b.RequestDemand("inventory", 42*1024)
b.Try("inventory", 1000)
rates := b.classRates(*now)
if rates["inventory"] < 340000 || rates["video"] != 5000000 {
t.Fatal("finite signalling stuck at floor on healthy link", rates)
}
b.effective = 1000
rates = b.classRates(*now)
if rates["inventory"] != 32000 || rates["video"] != b.optional(*now)*1000-32000 {
t.Fatal("signalling borrowed selected camera capacity", rates)
}
b.SetControl(true)
b.ObserveCommandFrame(800*time.Millisecond, 800*time.Millisecond)
if b.classRates(*now)["inventory"] != 0 {
t.Fatal("signalling escaped command pressure")
}
}
@@ -0,0 +1,94 @@
"""Package the feedback recovery fix over the exact qualified Node 98.
Only the rebuilt static Linux/amd64 Node executable (including its UI) and its
source provenance change. Installer, OS dependencies and model payloads are
preserved byte-for-byte. No board source or runtime is edited during install.
"""
import argparse
import hashlib
import io
import json
import subprocess
import sys
import tarfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
NODE = REPO / 'apps/node-agent'
sys.path.insert(0, str(REPO / 'scripts/packaging'))
from debian import package # noqa: E402
BASE = '671d0d6324873ba6ec994624d8cdd63fffe7d4d741d18bbf3966418f012286d5'
VERSION = '0.8.53-110'
BINARY = 'usr/lib/mission-core-node/node-agent'
PROVENANCE = 'usr/share/doc/mission-core-node/provenance.json'
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--binary', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if args.output.exists():
raise FileExistsError("Published Node packages are immutable; select a new version")
base = NODE / 'build/qualified-0.8.53-98/mission-core-node_0.8.53-98_amd64.deb'
qualification = json.loads((base.parent / "qualification.json").read_text())
assert qualification["state"] == "complete"
assert qualification["artifacts"][base.name]["sha256"] == BASE
raw = base.read_bytes()
assert sha(raw) == BASE
stream = io.BytesIO(raw)
assert stream.read(8) == b'!<arch>\n'
entries = {}
while header := stream.read(60):
size = int(header[48:58]); name = header[:16].decode().strip().rstrip('/')
entries[name] = stream.read(size)
if size % 2:
stream.read(1)
def files(name):
with tarfile.open(fileobj=io.BytesIO(entries[name]), mode='r:gz') as archive:
result = []
for item in archive:
if item.isdir():
continue
assert item.isfile() and item.uid == item.gid == 0
result.append((item.name, archive.extractfile(item).read(), item.mode))
return result
controls, payload = files('control.tar.gz'), files('data.tar.gz')
old = {name: data for name, data, _ in payload}
assert BINARY in old and PROVENANCE in old
binary = args.binary.read_bytes()
assert binary[:6] == b'\x7fELF\x02\x01' and binary[18:20] == b'\x3e\x00'
source_roots = [NODE/'internal', NODE/'cmd', NODE/'web', NODE/'ui/src',
REPO/'packages/sensor-ui/src', REPO/'packages/spatial-ui/src',
REPO/'plugins/xgrids-k1/frontend/src', REPO/'plugins/vesc/frontend/src']
sources = [p for root in source_roots for p in root.rglob('*') if p.is_file()]
sources += [NODE/'go.mod', NODE/'ui/package-lock.json', Path(__file__)]
compiler = NODE/'build/_toolchain/go/bin/go'
proof = {
'schema': 'missioncore.node.packaging-revision/v1', 'version': VERSION,
'qualified_base_sha256': BASE, 'qualified_base_provenance': json.loads(old[PROVENANCE]),
'binary_sha256': sha(binary), 'binary_build_info': subprocess.check_output([str(compiler),'version','-m',str(args.binary)],text=True),
'source_files': {str(p.relative_to(REPO)):sha(p.read_bytes()) for p in sorted(set(sources))},
'scope': 'Preserve the expiring feedback recovery target across the first delayed echo after a short gap; preserve command guards, K1 dialogue, UI, installed dependencies and service lifecycle',
}
changes = {BINARY:binary,PROVENANCE:(json.dumps(proof,indent=2)+'\n').encode()}
control = next(data for name,data,_ in controls if name == 'control')
assert control.count(b'Version: 0.8.53-98\n') == 1
controls = [(name,data.replace(b'Version: 0.8.53-98\n',f'Version: {VERSION}\n'.encode()) if name=='control' else data,mode) for name,data,mode in controls]
payload = [(name,changes.get(name,data),mode) for name,data,mode in payload]
result = package(controls,payload)
args.output.parent.mkdir(parents=True,exist_ok=True)
args.output.write_bytes(result)
receipt = {'version':VERSION,'sha256':sha(result),'bytes':len(result),'base_sha256':BASE,
'changed_payloads':{name:sha(value) for name,value in changes.items()},'installer_unchanged':True}
(args.output.parent/'package-result.json').write_text(json.dumps(receipt,indent=2)+'\n')
print(json.dumps(receipt))
if __name__ == '__main__':
main()
+65 -9
View File
@@ -94,6 +94,8 @@ class Manager:
self.path = self.root / "profiles.json"
self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {}
self.children = {}
self.next_physical_route_check = 0.0
self.restore_retry = {}
def persist(self):
save(self.path, self.profiles)
@@ -146,14 +148,47 @@ class Manager:
return
# A migrated VPS has a new destination, so it needs a new /32 even when
# this profile owns a route to its previous VPS. Reboots may remove routes.
record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface}
if is_host and prior == record:
return # Stable DHCP state: no route rewrite or tunnel reconfiguration.
command = "change" if is_host and prior else "add"
run("/sbin/route", "-n", command, "-host", endpoint, gateway, "-ifa", source)
record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface}
owned[endpoint] = record
row["host_route"] = record
row["physical_endpoint"] = endpoint
self.persist()
def refresh_physical_routes(self):
"""Repair only our explicit VPS /32 after the selected Mac LAN changes.
WireGuard keepalives cannot repair a macOS route whose cached source is
an expired DHCP address. Leave peer keys, tunnel state, default routes,
foreign routes and the selected physical interface unchanged.
"""
if not DARWIN:
return
with self.lock:
now = time.monotonic()
if now < self.next_physical_route_check:
return
self.next_physical_route_check = now + 5
for row in self.profiles.values():
config = row.get("config")
endpoint = row.get("physical_endpoint")
if not config or not config.get("interface") or row.get("pending") or not endpoint:
continue
owned = row.get("host_routes", {})
legacy = row.get("host_route") or {}
if endpoint not in owned and legacy.get("endpoint") != endpoint:
continue
try:
self.physical_route(config, endpoint, row)
except (OSError, ValueError, IndexError, subprocess.SubprocessError):
# No DHCP lease, a foreign route or a transient failure must
# not disable the tunnel or prevent another profile's check.
# Retry on the next bounded pass without touching the VPN.
continue
def retire_physical_routes(self, row):
if not DARWIN:
return
@@ -238,7 +273,17 @@ class Manager:
if DARWIN:
result = run("/sbin/route", "-n", "get", route[:-3], check=False).stdout.decode()
fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line)
exists = "HOST" in fields.get("flags", "")
flags = fields.get("flags", "")
# A scoped cache created from another VPN's default route is
# not an administrator's explicit host route. Retire only this
# exact cached fleet destination before adding our /32.
if "HOST" in flags and "WASCLONED" in flags:
cached_interface = fields.get("interface", "").strip()
if not re.fullmatch(r"(?:utun|en)[0-9]+", cached_interface):
raise ValueError("Unrecognized cached route interface")
run("/sbin/route", "-n", "delete", "-host", route[:-3], "-ifscope", cached_interface, check=False)
flags = ""
exists = "HOST" in flags
own = exists and fields.get("interface", "").strip() == name
else:
entries = json.loads(run("/usr/sbin/ip", "-j", "route", "show", "exact", route).stdout)
@@ -348,14 +393,24 @@ class Manager:
def restore(self, startup=False):
with self.lock:
for row in self.profiles.values():
for identity, row in self.profiles.items():
pending = row.get("pending")
if pending and (startup or pending["deadline"] <= time.time()):
self.apply(row, pending["previous"])
row["pending"] = None
self.persist()
elif startup and row.get("config"):
self.apply(row, row["config"])
rollback = pending and (startup or pending["deadline"] <= time.time())
if not (rollback or (row.get("config") and (startup or identity in self.restore_retry))):
continue
if not startup and time.monotonic() < self.restore_retry.get(identity, 0):
continue
try:
self.apply(row, pending["previous"] if rollback else row["config"])
if rollback:
row["pending"] = None
self.persist()
except Exception:
# A late DHCP lease or transient route failure at boot must
# not leave an apparently running helper permanently partial.
self.restore_retry[identity] = time.monotonic() + 5
else:
self.restore_retry.pop(identity, None)
class Handler(socketserver.StreamRequestHandler):
@@ -405,6 +460,7 @@ def main():
manager.restore()
except Exception:
pass
manager.refresh_physical_routes()
if __name__ == "__main__":
@@ -0,0 +1,223 @@
"""Synthetic DHCP/route regression; never calls the host network tools."""
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import pytest
@pytest.fixture
def network(tmp_path, monkeypatch):
spec = importlib.util.spec_from_file_location("route_recovery_helper", Path(__file__).with_name("helper.py"))
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
monkeypatch.setattr(helper, "DARWIN", True)
manager = helper.Manager(tmp_path)
endpoint = "203.0.113.7"
old = dict(endpoint=endpoint, gateway="192.168.90.1", source="192.168.90.10", interface="en0")
row = dict(config={"interface": "en0"}, pending=None, physical_endpoint=endpoint,
host_route=dict(old), host_routes={endpoint: dict(old)}, interface="utun42")
manager.profiles["fleet"] = row
state = dict(source="192.168.90.20", gateway="192.168.90.1", actual=dict(old), now=100.0, lease=True)
calls = []
monkeypatch.setattr(helper.time, "monotonic", lambda: state["now"])
def run(*args, **kwargs):
calls.append(args)
if args[0] == "/usr/sbin/ipconfig":
if not state["lease"]:
raise helper.subprocess.CalledProcessError(1, args)
value = state["source"] if args[1] == "getifaddr" else state["gateway"]
elif args[:3] == ("/sbin/route", "-n", "get"):
actual = state["actual"]
value = ("flags: <UP,GATEWAY,HOST,STATIC>\ngateway: " + actual["gateway"] +
"\ninterface: " + actual["interface"] + "\n") if actual else "flags: <UP,GATEWAY>\n"
elif args[:3] in (("/sbin/route", "-n", "change"), ("/sbin/route", "-n", "add")):
assert args[3:5] == ("-host", endpoint)
state["actual"] = dict(endpoint=endpoint, gateway=args[5], source=args[7], interface="en0")
value = ""
else:
raise AssertionError("Unexpected system operation: " + repr(args))
return SimpleNamespace(stdout=value.encode(), returncode=0)
monkeypatch.setattr(helper, "run", run)
return SimpleNamespace(helper=helper, manager=manager, row=row, state=state, calls=calls, endpoint=endpoint)
def mutations(n):
return [c for c in n.calls if c[:3] in (("/sbin/route", "-n", "change"), ("/sbin/route", "-n", "add"))]
def test_dhcp_source_change_repairs_owned_host_route_without_resetting_tunnel(network):
n = network
n.manager.refresh_physical_routes()
assert mutations(n) == [("/sbin/route", "-n", "change", "-host", n.endpoint,
"192.168.90.1", "-ifa", "192.168.90.20")]
assert n.row["host_route"]["source"] == "192.168.90.20"
assert n.row["interface"] == "utun42"
assert not any("wg" in c[0] or "ifconfig" in c[0] for c in n.calls)
# Another periodic pass with stable DHCP makes no network mutation.
n.state["now"] += 6
n.manager.refresh_physical_routes()
assert len(mutations(n)) == 1
def test_checks_are_rate_limited_and_do_not_rewrite_stable_routes(network):
n = network
n.state["source"] = "192.168.90.10"
n.manager.refresh_physical_routes()
first = len(n.calls)
for _ in range(20):
n.manager.refresh_physical_routes()
assert len(n.calls) == first
assert not mutations(n)
def test_gateway_change_updates_only_the_previously_owned_host_route(network):
n = network
n.state.update(gateway="192.168.91.1", source="192.168.91.20")
n.manager.refresh_physical_routes()
assert mutations(n)[0][3:] == ("-host", n.endpoint, "192.168.91.1", "-ifa", "192.168.91.20")
def test_removed_owned_route_is_recreated_without_changing_default_route(network):
n = network
n.state["actual"] = None
n.manager.refresh_physical_routes()
assert mutations(n)[0][2:5] == ("add", "-host", n.endpoint)
def test_missing_wifi_lease_is_retried_after_reconnection(network):
n = network
n.state["lease"] = False
n.manager.refresh_physical_routes()
assert not mutations(n)
assert n.row["config"] == {"interface": "en0"}
n.state.update(lease=True, now=106.0)
n.manager.refresh_physical_routes()
assert len(mutations(n)) == 1
def test_foreign_replacement_is_preserved_and_a_later_pass_can_recover(network):
n = network
own = dict(n.state["actual"])
n.state["actual"] = dict(own, gateway="100.64.0.1", interface="utun9")
n.manager.refresh_physical_routes()
assert not mutations(n)
n.state.update(actual=own, now=106.0)
n.manager.refresh_physical_routes()
assert len(mutations(n)) == 1
@pytest.mark.parametrize("change", [
{"pending": {"id": "transaction"}}, {"config": None},
{"config": {}}, {"physical_endpoint": None}, {"host_route": None, "host_routes": {}},
])
def test_inactive_pending_and_unowned_profiles_are_not_changed(network, change):
n = network
n.row.update(change)
n.manager.refresh_physical_routes()
assert n.calls == []
def test_linux_underlay_is_not_managed_by_macos_recovery(network, monkeypatch):
n = network
monkeypatch.setattr(n.helper, "DARWIN", False)
n.manager.refresh_physical_routes()
assert n.calls == []
def test_legacy_owned_route_record_remains_recoverable(network):
n = network
n.row.pop("host_routes")
n.manager.refresh_physical_routes()
assert n.row["host_routes"][n.endpoint]["source"] == "192.168.90.20"
def test_one_unavailable_network_does_not_block_another_profile(network, monkeypatch):
n = network
second = dict(n.row)
n.manager.profiles["other"] = second
calls = []
def refresh(config, endpoint, row):
calls.append(row)
if row is n.row:
raise OSError("No DHCP lease")
monkeypatch.setattr(n.manager, "physical_route", refresh)
n.manager.refresh_physical_routes()
assert len(calls) == 2 and calls[1] is second
@pytest.mark.parametrize("cached", [True, False])
def test_peer_route_cache_from_another_vpn_is_distinct_from_a_foreign_static_route(tmp_path, monkeypatch, cached):
spec = importlib.util.spec_from_file_location("peer_route_helper", Path(__file__).with_name("helper.py"))
h = importlib.util.module_from_spec(spec)
spec.loader.exec_module(h)
monkeypatch.setattr(h, "DARWIN", True)
monkeypatch.setattr(h, "validate", lambda config: "203.0.113.7")
m = h.Manager(tmp_path)
monkeypatch.setattr(m, "physical_route", lambda *args: None)
monkeypatch.setattr(m, "retire_physical_routes", lambda *args: None)
row = dict(interface="utun42", public_key="synthetic-public", private_key="synthetic-private", routes=[])
config = dict(server_id="wg_" + "1" * 32, server_public_key="synthetic-server", address="10.203.45.2", allowed_ips=["10.203.45.3/32"])
calls = []
def run(*args, **kwargs):
calls.append(args)
if args[0] == "/usr/sbin/sysctl":
data = "0"
elif args[1:] == ("show", "utun42", "public-key"):
data = "synthetic-public"
elif args[:3] == ("/sbin/route", "-n", "get"):
flags = "UP,HOST,WASCLONED,IFSCOPE" if cached else "UP,HOST,STATIC"
data = "flags: <" + flags + ">\ninterface: utun9\n"
else:
data = ""
return SimpleNamespace(stdout=data.encode(), returncode=0)
monkeypatch.setattr(h, "run", run)
if cached:
m.apply(row, config)
assert ("/sbin/route", "-n", "delete", "-host", "10.203.45.3", "-ifscope", "utun9") in calls
assert ("/sbin/route", "-n", "add", "-host", "10.203.45.3", "-interface", "utun42") in calls
assert row["routes"] == ["10.203.45.3/32"]
else:
with pytest.raises(ValueError, match="conflicts"):
m.apply(row, config)
assert not any(c[:3] in (("/sbin/route", "-n", "delete"), ("/sbin/route", "-n", "add")) for c in calls)
def test_failed_startup_restore_retries_then_stops_without_resetting_healthy_tunnel(network, monkeypatch):
n = network
calls = []
def apply(row, config):
calls.append(config)
if len(calls) == 1:
raise OSError("Wi-Fi not ready during boot")
monkeypatch.setattr(n.manager, "apply", apply)
n.manager.restore(startup=True)
n.manager.restore()
assert len(calls) == 1
n.state["now"] += 6
n.manager.restore()
assert len(calls) == 2
assert not n.manager.restore_retry
n.state["now"] += 60
n.manager.restore()
assert len(calls) == 2
def test_failed_rollback_retains_transaction_and_retries_saved_previous_profile(network, monkeypatch):
n = network
previous = {"previous": True}
n.row["pending"] = {"deadline": 0, "previous": previous}
calls = []
def apply(row, config):
calls.append(config)
if len(calls) == 1:
raise OSError("Transient route failure")
monkeypatch.setattr(n.manager, "apply", apply)
n.manager.restore(startup=True)
assert n.row["pending"]
n.state["now"] += 6
n.manager.restore()
assert calls == [previous, previous]
assert n.row["pending"] is None
+16 -5
View File
@@ -23,16 +23,19 @@ class RoverChannel:
# receipts, camera payloads or durable motion state.
binding = row["binding"]
projection = copy.deepcopy({
"name": row.get("name",row["id"]), "id": row["id"], "node_id": row["node_id"], "enrollment": row["enrollment"],
"name": row.get("name", row["id"]), "id": row["id"],
"node_id": row["node_id"], "enrollment": row["enrollment"],
"binding": {key: binding[key] for key in
("binding_id", "client_pem", "endpoint_revision") if key in binding},
"certificate_previous": row.get("certificate_previous"),
"network_paths": row.get("network_paths", {}),
})
with self.lock:
old = self.vehicles.get(row["id"])
if old and (old["node_id"] != row["node_id"]
or old["binding"]["binding_id"] != binding["binding_id"]
or old["binding"].get("endpoint_revision", 0) != binding.get("endpoint_revision", 0)
or old["binding"].get("endpoint_revision", 0)
!= binding.get("endpoint_revision", 0)
or (old["enrollment"] == "paired" and row["enrollment"] != "paired")):
self.nodes.pop(old["node_id"], None)
self.control.forget(old["node_id"])
@@ -40,12 +43,18 @@ class RoverChannel:
self.nodes[row["node_id"]] = projection
def same_generation(self, value):
"""Cheap retirement check only; a send still performs full authentication."""
"""Retire superseded endpoints; each send still fully authenticates a candidate.
A higher revision is an in-flight route change. Its feedback must work
before the first paced heartbeat can commit that revision.
"""
with self.lock:
row = self.nodes.get(value.get("node_id"))
revision = value.get("endpoint_revision", 0)
return bool(row and row["enrollment"] == "paired"
and row["binding"]["binding_id"] == value.get("binding_id")
and row["binding"].get("endpoint_revision", 0) == value.get("endpoint_revision", 0))
and type(revision) is int
and row["binding"].get("endpoint_revision", 0) <= revision <= 1000000000)
def operator(self, vehicle, operation, body=None, *, expires_at=None):
with self.lock:
@@ -89,7 +98,9 @@ class RoverChannel:
or not isinstance(relay, str) or len(relay) != 32
or any(c not in "0123456789abcdef" for c in relay)):
return 400, {"error": "Invalid rover link probe"}
return 200, {"connected": True, "sample_clock_v1": True, "diagnostic_lane_v1": True, "budget_interval_v1": True, "rover_details_v1": True,
return 200, {"connected": True, "sample_clock_v1": True,
"diagnostic_lane_v1": True, "budget_interval_v1": True,
"rover_details_v1": True,
"control_clock": self.control._clock()}
if path == "/v1/node/rover-diagnostics":
# Capture this binding's diagnostics object while authority is
+53 -1
View File
@@ -3,7 +3,7 @@ import socket
import time
import pytest
from test_pairing import cert, create, setup # noqa: F401
from test_pairing import cert, create, heartbeat, setup # noqa: F401
from k1link.fleet.rover_datagram import DatagramCipher, RoverDatagramServer
from k1link.fleet.trust import SCHEMA
@@ -177,3 +177,55 @@ def test_wake_hint_does_not_create_board_or_renew_authority():
assert control.intent_changed('node', 'a' * 32, None)
assert control.boards['node']['session']['until'] == deadline
assert control.stream('node', 'a' * 32)['command'] is None
@pytest.mark.parametrize("route", ["100.64.20.5", "10.203.42.2"])
def test_migration_feedback_precedes_full_heartbeat_commit(setup, route): # noqa: F811
"""The feedback needed to send inventory must work before its first commit."""
fleet, _, _, _ = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
row["network_paths"] = {"synthetic-wg": {"core": "10.203.42.2", "node": "10.203.42.3"}}
fleet.save(row)
certificate = cert(row)
migration = {"core_endpoint": f"https://{route}:8782", "endpoint_revision": 1}
body = {"schema": SCHEMA, "node_id": row["node_id"],
"binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32, **migration}
assert fleet.receive(certificate, "/v1/node/rover-link", body, address=route)[0] == 200
fleet.rover_control.view(row["node_id"])
server = RoverDatagramServer("127.0.0.1", fleet, port=0)
# Synthetic listener identity, with actual encrypted packets kept on loopback.
server.address = route
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(.3)
try:
_, grant = server.open(certificate, body)
channel = bytes.fromhex(grant["channel"])
tx = DatagramCipher(channel, bytes.fromhex(grant["send_key"]))
rx = DatagramCipher(channel, bytes.fromhex(grant["receive_key"]))
client.sendto(tx.seal({}), server.socket.getsockname())
reply = rx.open(client.recv(1201))[1]
assert reply["probe"] == 1 and reply["reply"]["command"] is None
assert fleet.find(public["id"])["binding"] == row["binding"]
assert fleet.receive(certificate, "/v1/node/heartbeat",
{**heartbeat(row), **migration}, address=route)[0] == 200
assert fleet.find(public["id"])["binding"]["endpoint_revision"] == 1
fleet.rover_control.view(row["node_id"])
client.sendto(tx.seal({}), server.socket.getsockname())
assert rx.open(client.recv(1201))[1]["reply"]["command"] is None
# Once a newer endpoint is committed this candidate must still retire.
current = fleet.find(public["id"])
current["binding"]["endpoint_revision"] = 2
fleet.save(current)
deadline = time.monotonic() + .3
while time.monotonic() < deadline:
with server.lock:
if channel not in server.channels:
break
time.sleep(.005)
with server.lock:
assert channel not in server.channels
finally:
client.close()
server.close()