feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,262 @@
|
||||
package node
|
||||
|
||||
// Opt-in Worker 006 qualification only. No device driver, sensor service,
|
||||
// external network or physical motor is reachable from this fixture.
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWorkerSharedBudgetUnderOptionalTrafficAndInterruptedExport(t *testing.T) {
|
||||
started := time.Now()
|
||||
budget, err := OpenLinkBudget("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 14*time.Second)
|
||||
defer cancel()
|
||||
var workers sync.WaitGroup
|
||||
for _, class := range []string{"video", "video", "cloud"} {
|
||||
workers.Add(1)
|
||||
go func(class string) {
|
||||
defer workers.Done()
|
||||
tick := time.NewTicker(time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
budget.Try(class, 1200)
|
||||
}
|
||||
}
|
||||
}(class)
|
||||
}
|
||||
payload := bytes.Repeat([]byte("synthetic-export"), 4096) // 64 KiB, fixed RAM.
|
||||
var calls, successes, disconnects atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got, e := io.ReadAll(io.LimitReader(r.Body, 65537))
|
||||
if e != nil || !bytes.Equal(got, payload) {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
n := calls.Add(1)
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-time.After(120 * time.Millisecond):
|
||||
}
|
||||
if n == 2 {
|
||||
connection, _, e := w.(http.Hijacker).Hijack()
|
||||
if e == nil {
|
||||
connection.Close()
|
||||
disconnects.Add(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
w.Write([]byte("verified"))
|
||||
}))
|
||||
defer server.Close()
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
client := &http.Client{Timeout: 13 * time.Second}
|
||||
defer client.CloseIdleConnections()
|
||||
for ctx.Err() == nil && successes.Load() < 3 {
|
||||
reader := &budgetReader{ctx: ctx, source: bytes.NewReader(payload), budget: budget, class: "bulk"}
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", server.URL, reader)
|
||||
req.ContentLength = int64(len(payload))
|
||||
response, e := client.Do(req)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
body, e := io.ReadAll(io.LimitReader(response.Body, 20))
|
||||
response.Body.Close()
|
||||
if e == nil && response.StatusCode == 200 && string(body) == "verified" {
|
||||
successes.Add(1)
|
||||
}
|
||||
}
|
||||
}()
|
||||
latencies := []int64{}
|
||||
fresh, stale, replay := 0, 0, 0
|
||||
tick := time.NewTicker(20 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for ctx.Err() == nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-tick.C:
|
||||
// Inject age/one-way delay without changing any host network.
|
||||
// The actual production state machine retains original expiry.
|
||||
for _, delay := range []int{20, 90, 150, 300, 450, 700} {
|
||||
origin := time.Now()
|
||||
state := newRoverStreamState(origin)
|
||||
state.budget = budget
|
||||
state.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
acknowledgeStop(state, origin)
|
||||
state.accept(streamIntent(1, 10000, 10400))
|
||||
before := time.Now()
|
||||
_, command, _ := state.delivery(origin.Add(time.Duration(delay) * time.Millisecond))
|
||||
latencies = append(latencies, time.Since(before).Microseconds())
|
||||
if delay >= 400 {
|
||||
if command != nil {
|
||||
t.Error("expired command reached delivery")
|
||||
}
|
||||
stale++
|
||||
} else {
|
||||
if command == nil {
|
||||
t.Error("fresh command blocked by optional traffic")
|
||||
}
|
||||
fresh++
|
||||
}
|
||||
state.stopStream()
|
||||
acknowledgeStop(state, origin)
|
||||
state.accept(streamIntent(2, 10000, 10400))
|
||||
_, command, _ = state.delivery(origin)
|
||||
if command != nil {
|
||||
t.Error("old session replayed after reconnect")
|
||||
}
|
||||
replay++
|
||||
}
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
workers.Wait()
|
||||
elapsed := time.Since(started).Seconds()
|
||||
snapshot := budget.Snapshot()
|
||||
classes := snapshot["classes"].(map[string]any)
|
||||
var total uint64
|
||||
for _, class := range []string{"video", "cloud", "bulk"} {
|
||||
n := classes[class].(map[string]any)["granted_bytes"].(uint64)
|
||||
if n == 0 {
|
||||
t.Error("optional class starved", class)
|
||||
}
|
||||
total += n
|
||||
}
|
||||
if float64(total) > (4000-512)*125*elapsed+linkBurst {
|
||||
t.Error("aggregate exceeded envelope")
|
||||
}
|
||||
if successes.Load() != 3 || disconnects.Load() != 1 {
|
||||
t.Error("bulk retry did not finish", successes.Load(), disconnects.Load())
|
||||
}
|
||||
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||
if len(latencies) == 0 {
|
||||
t.Fatal("no control samples")
|
||||
}
|
||||
p99 := latencies[len(latencies)*99/100]
|
||||
if p99 > 25000 {
|
||||
t.Error("control state access blocked", p99)
|
||||
}
|
||||
var memory runtime.MemStats
|
||||
runtime.ReadMemStats(&memory)
|
||||
if memory.HeapInuse > 64*1024*1024 {
|
||||
t.Error("unbounded fixture memory", memory.HeapInuse)
|
||||
}
|
||||
report, _ := json.Marshal(map[string]any{"elapsed_seconds": elapsed, "fresh_commands": fresh,
|
||||
"expired_commands_rejected": stale, "reconnect_replays_rejected": replay,
|
||||
"control_access_p99_us": p99, "control_access_max_us": latencies[len(latencies)-1],
|
||||
"bulk_completed": successes.Load(), "injected_disconnects": disconnects.Load(),
|
||||
"heap_inuse_bytes": memory.HeapInuse, "budget": snapshot})
|
||||
t.Log(string(report))
|
||||
}
|
||||
|
||||
// Real loopback HTTP at the minimum optional rate, with a continuously busy
|
||||
// video/cloud producer and small DEV polls. No host routes or drivers involved.
|
||||
func TestWorkerHeartbeatAndDevAtMinimumBudget(t *testing.T) {
|
||||
p, _ := testPairing(t)
|
||||
binding := testCoreBinding(t, p)
|
||||
p.state = PairState{Phase: "paired", Binding: &binding}
|
||||
budget, _ := OpenLinkBudget("")
|
||||
budget.effective = float64(budget.policy.ReserveKbps + 128)
|
||||
p.Budget = budget
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
var workers sync.WaitGroup
|
||||
var devBytes atomic.Int64
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
tick := time.NewTicker(10 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
budget.Try("video", 1200)
|
||||
budget.Try("cloud", 1200)
|
||||
if ok, _ := budget.Try("bulk", 400); ok {
|
||||
devBytes.Add(400)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() { cancel(); workers.Wait() }()
|
||||
var mu sync.Mutex
|
||||
var liveAt []time.Time
|
||||
var snapshotBytes int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 48*1024))
|
||||
if err != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
if r.URL.Path == "/v1/node/liveness" {
|
||||
if len(body) > 2048 {
|
||||
t.Error("oversized keepalive")
|
||||
}
|
||||
liveAt = append(liveAt, time.Now())
|
||||
} else {
|
||||
snapshotBytes = len(body)
|
||||
}
|
||||
mu.Unlock()
|
||||
w.Write([]byte(`{"ok":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
transport := &http.Transport{MaxConnsPerHost: 2}
|
||||
defer transport.CloseIdleConnections()
|
||||
p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{
|
||||
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
copy := r.Clone(r.Context())
|
||||
// Replace only fixture destination, retaining production body pacing,
|
||||
// length, cancellation and separate HTTP connections.
|
||||
destination, _ := http.NewRequest(r.Method, server.URL+r.URL.Path, nil)
|
||||
copy.URL = destination.URL
|
||||
copy.Host = destination.URL.Host
|
||||
return transport.RoundTrip(copy)
|
||||
}),
|
||||
}
|
||||
started := time.Now()
|
||||
_, status, err := p.sendHeartbeat(ctx, binding, map[string]any{
|
||||
"schema": PairSchema, "binding_id": binding.BindingID, "node_id": "fixture",
|
||||
"execution_binding": map[string]string{"agent_instance_id": "fixture", "platform": "linux"},
|
||||
"core_endpoint": binding.Endpoint, "endpoint_revision": 0,
|
||||
"host": string(bytes.Repeat([]byte("i"), 40*1024)),
|
||||
})
|
||||
elapsed := time.Since(started)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err != nil || status != 200 || snapshotBytes < 40*1024 || len(liveAt) < 5 || devBytes.Load() == 0 {
|
||||
t.Fatal("snapshot/presence/DEV starvation", err, status, snapshotBytes, len(liveAt), devBytes.Load())
|
||||
}
|
||||
maxGap := time.Duration(0)
|
||||
for i := 1; i < len(liveAt); i++ {
|
||||
if gap := liveAt[i].Sub(liveAt[i-1]); gap > maxGap {
|
||||
maxGap = gap
|
||||
}
|
||||
}
|
||||
if maxGap > 7*time.Second {
|
||||
t.Fatal("large transfer delayed liveness", maxGap)
|
||||
}
|
||||
t.Logf("snapshot_bytes=%d elapsed=%v liveness=%d max_gap=%v dev_bytes=%d", snapshotBytes, elapsed, len(liveAt), maxGap, devBytes.Load())
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package node
|
||||
|
||||
// Bounded connection establishment regression inside the existing isolated
|
||||
// Worker netem namespace. No motor, host networking, or board interface exists.
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWorkerConnectFirstSYN(t *testing.T) {
|
||||
for _, legacy := range []bool{false, true} {
|
||||
name := "production"
|
||||
if legacy {
|
||||
name = "legacy-one-second"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) { connectFirstSYN(t, legacy) })
|
||||
}
|
||||
}
|
||||
|
||||
func connectFirstSYN(t *testing.T, legacy bool) {
|
||||
if os.Getenv("MISSION_CORE_ISOLATED_NETEM") != "1" {
|
||||
t.Fatal("isolated netem only")
|
||||
}
|
||||
if _, err := os.Stat("/.dockerenv"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil || len(interfaces) != 1 || interfaces[0].Name != "lo" {
|
||||
t.Fatal("loopback-only namespace required")
|
||||
}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }))
|
||||
server.Listener.Close()
|
||||
server.Listener, err = net.Listen("tcp4", "127.0.0.2:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
tr := newRoverHTTPTransport(server.Client().Transport.(*http.Transport).TLSClientConfig.Clone())
|
||||
tr.TLSClientConfig.ServerName = "127.0.0.1"
|
||||
if legacy {
|
||||
tr.DialContext = (&net.Dialer{Timeout: time.Second}).DialContext
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
tc(t, "qdisc", "add", "dev", "lo", "root", "handle", "1:", "prio", "bands", "3")
|
||||
defer tc(t, "qdisc", "del", "dev", "lo", "root")
|
||||
tc(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "pref", "7", "u32",
|
||||
"match", "ip", "dst", "127.0.0.2/32", "match", "ip", "protocol", "6", "0xff",
|
||||
"match", "u8", "0x02", "0x12", "at", "33", "action", "drop")
|
||||
// The path is healthy again before the 1 s initial TCP retransmission.
|
||||
// Only the first SYN is intentionally discarded, never every retry.
|
||||
var workers sync.WaitGroup
|
||||
var counters string
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
counters = string(tc(t, "-s", "filter", "show", "dev", "lo", "parent", "1:", "pref", "7"))
|
||||
tc(t, "filter", "del", "dev", "lo", "parent", "1:", "pref", "7")
|
||||
}()
|
||||
started := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
|
||||
defer cancel()
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
|
||||
response, requestErr := (&http.Client{Transport: tr}).Do(req)
|
||||
elapsed := time.Since(started)
|
||||
status := 0
|
||||
if response != nil {
|
||||
status = response.StatusCode
|
||||
response.Body.Close()
|
||||
}
|
||||
workers.Wait()
|
||||
data, _ := json.Marshal(map[string]any{"case": t.Name(), "elapsed_ms": float64(elapsed.Microseconds()) / 1000,
|
||||
"status": status, "error": roverErrorKind(requestErr), "filter_counters": counters, "actuator_output": false})
|
||||
t.Log("CONNECT_EVIDENCE " + string(data))
|
||||
if !strings.Contains(counters, "dropped 1,") {
|
||||
t.Fatal("Expected exactly one dropped SYN")
|
||||
}
|
||||
if legacy && requestErr == nil {
|
||||
t.Fatal("Legacy deadline unexpectedly recovered SYN loss")
|
||||
}
|
||||
if !legacy && (requestErr != nil || status != 200) {
|
||||
t.Fatal("Production transport could not recover first SYN loss")
|
||||
}
|
||||
}
|
||||
|
||||
// A longer TCP establishment allowance must still obey its owning context.
|
||||
func TestWorkerConnectCancellation(t *testing.T) {
|
||||
if os.Getenv("MISSION_CORE_ISOLATED_NETEM") != "1" {
|
||||
t.Fatal("isolated Worker only")
|
||||
}
|
||||
listener, err := net.Listen("tcp4", "127.0.0.2:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
// Accept TCP but withhold TLS; cancellation must interrupt the handshake.
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
c, e := listener.Accept()
|
||||
if e == nil {
|
||||
defer c.Close()
|
||||
b := make([]byte, 4096)
|
||||
for {
|
||||
if _, e = c.Read(b); e != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
tr := newRoverHTTPTransport(nil)
|
||||
defer tr.CloseIdleConnections()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 75*time.Millisecond)
|
||||
defer cancel()
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", "https://"+listener.Addr().String(), nil)
|
||||
started := time.Now()
|
||||
response, err := (&http.Client{Transport: tr}).Do(req)
|
||||
requestElapsed := time.Since(started)
|
||||
if response != nil {
|
||||
response.Body.Close()
|
||||
}
|
||||
if err == nil || requestElapsed > 500*time.Millisecond {
|
||||
t.Fatal("Owning cancellation did not bound handshake")
|
||||
}
|
||||
listener.Close()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Handshake worker remained")
|
||||
}
|
||||
t.Logf("CONNECT_CANCEL request_elapsed_ms=%d cleanup_elapsed_ms=%d actuator_output=false", requestElapsed.Milliseconds(), time.Since(started).Milliseconds())
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package node
|
||||
|
||||
// Kernel shaping is confined to an otherwise network-none qualification
|
||||
// container. The Core/Node addresses are test loopback aliases, not host routes.
|
||||
// UDP datagrams represent encrypted video packet demand; no encoder/decoder or
|
||||
// WebRTC/DERP implementation is claimed by this fixture.
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type contentionProfile struct {
|
||||
name string
|
||||
down, up, oneWay int
|
||||
loss string
|
||||
jitter int
|
||||
}
|
||||
|
||||
func tc(t *testing.T, args ...string) []byte {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "tc", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("tc %v: %v %s", args, err, out)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func shape(t *testing.T, p contentionProfile) {
|
||||
t.Helper()
|
||||
if os.Getenv("MISSION_CORE_ISOLATED_NETEM") != "1" {
|
||||
t.Fatal("Only the declared network-none Worker container may run netem")
|
||||
}
|
||||
if _, err := os.Stat("/.dockerenv"); err != nil {
|
||||
t.Fatal("Docker isolation marker missing")
|
||||
}
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil || len(interfaces) != 1 || interfaces[0].Name != "lo" {
|
||||
t.Fatal("Only a loopback-only isolated namespace is admitted")
|
||||
}
|
||||
// No host interface, namespace creation, sysctl or routing change is used.
|
||||
tc(t, "qdisc", "add", "dev", "lo", "root", "handle", "1:", "prio", "bands", "3")
|
||||
t.Cleanup(func() { tc(t, "qdisc", "del", "dev", "lo", "root") })
|
||||
for _, d := range []struct {
|
||||
band, rate int
|
||||
dst string
|
||||
}{{1, p.up, "127.0.0.2/32"}, {2, p.down, "127.0.0.3/32"}} {
|
||||
args := []string{"qdisc", "add", "dev", "lo", "parent", fmt.Sprintf("1:%d", d.band), "handle", fmt.Sprintf("%d0:", d.band), "netem", "limit", "64", "delay", fmt.Sprintf("%dms", p.oneWay)}
|
||||
if p.jitter > 0 {
|
||||
args = append(args, fmt.Sprintf("%dms", p.jitter))
|
||||
}
|
||||
args = append(args, "rate", fmt.Sprintf("%dkbit", d.rate))
|
||||
tc(t, args...)
|
||||
tc(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "prio", fmt.Sprint(d.band), "u32", "match", "ip", "dst", d.dst, "flowid", fmt.Sprintf("1:%d", d.band))
|
||||
}
|
||||
}
|
||||
func percentile(values []float64, p float64) float64 {
|
||||
if len(values) == 0 {
|
||||
return 0
|
||||
}
|
||||
x := append([]float64{}, values...)
|
||||
sort.Float64s(x)
|
||||
return x[int(float64(len(x)-1)*p)]
|
||||
}
|
||||
func TestWorkerContentionMatrix(t *testing.T) {
|
||||
profiles := []contentionProfile{{"5M-5M-rtt40", 5000, 5000, 20, "", 0}, {"1M-256K-rtt100", 1000, 256, 50, "", 0}, {"256K-128K-rtt150", 256, 128, 75, "", 0}, {"256K-128K-rtt150-loss1", 256, 128, 75, "1%", 0}}
|
||||
for _, profile := range profiles {
|
||||
for _, mode := range []string{"none", "gated", "unregulated"} {
|
||||
t.Run(profile.name+"/"+mode, func(t *testing.T) { runContention(t, profile, mode, 8) })
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestWorkerContentionSoak(t *testing.T) {
|
||||
runContention(t, contentionProfile{"1M-256K-rtt100", 1000, 256, 50, "", 0}, "gated", 60)
|
||||
}
|
||||
func TestWorkerDatagramContentionMatrix(t *testing.T) {
|
||||
profiles := []contentionProfile{{"5M-5M-rtt40", 5000, 5000, 20, "", 0}, {"1M-256K-rtt100", 1000, 256, 50, "", 0}, {"256K-128K-rtt150", 256, 128, 75, "", 0}, {"256K-128K-rtt150-loss1", 256, 128, 75, "1%", 0}}
|
||||
for _, p := range profiles {
|
||||
for _, mode := range []string{"none", "gated"} {
|
||||
t.Run(p.name+"/"+mode, func(t *testing.T) { runContention(t, p, mode, 8, true) })
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestWorkerDatagramJitter(t *testing.T) {
|
||||
runContention(t, contentionProfile{"5M-5M-rtt40-jitter40", 5000, 5000, 20, "", 40}, "gated", 8, true)
|
||||
}
|
||||
|
||||
func TestWorkerDatagramCompareTCP(t *testing.T) {
|
||||
p := contentionProfile{"1M-256K-rtt100", 1000, 256, 50, "", 0}
|
||||
for _, datagram := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("datagram-%t", datagram), func(t *testing.T) { runContention(t, p, "gated", 8, datagram) })
|
||||
}
|
||||
}
|
||||
func runContention(t *testing.T, p contentionProfile, mode string, seconds int, datagram ...bool) {
|
||||
shape(t, p)
|
||||
useDatagram := len(datagram) > 0 && datagram[0]
|
||||
// UDP's loopback route selects .1; include it in exactly the same downlink
|
||||
// queue as TCP's .3. Otherwise the UDP comparison would bypass shaping.
|
||||
if useDatagram {
|
||||
tc(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "prio", "3", "u32", "match", "ip", "dst", "127.0.0.1/32", "flowid", "1:2")
|
||||
}
|
||||
f := newTransportRig(t, func(f *transportRig) {
|
||||
f.networkFixture = true
|
||||
f.timeout = time.Duration(seconds+20) * time.Second
|
||||
if useDatagram {
|
||||
f.datagram = &datagramRig{}
|
||||
}
|
||||
})
|
||||
var mu sync.Mutex
|
||||
var rows []map[string]any
|
||||
var overflow bool
|
||||
// The diagnostic collector is local to the fixture and never crosses qdisc.
|
||||
f.workers.Add(1)
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
tick := time.NewTicker(20 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
f.state.mu.Lock()
|
||||
batch := f.state.devEvents
|
||||
f.state.devEvents = nil
|
||||
f.state.mu.Unlock()
|
||||
mu.Lock()
|
||||
if len(batch) >= 64 {
|
||||
overflow = true
|
||||
}
|
||||
rows = append(rows, batch...)
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
// Fixed 20 Hz Core generation, original clock/expiry. No new identity is
|
||||
// fabricated after a stop. TCP writes may backpressure; the ticker coalesces.
|
||||
f.workers.Add(1)
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
tick := time.NewTicker(50 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
seq := 0
|
||||
for {
|
||||
select {
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
seq++
|
||||
if useDatagram {
|
||||
f.datagram.write(f.frame(transportSession, seq))
|
||||
continue
|
||||
}
|
||||
job := transportWrite{data: f.frame(transportSession, seq), done: make(chan error, 1)}
|
||||
select {
|
||||
case f.wire <- job:
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-job.done:
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
f.pause(2 * time.Second)
|
||||
f.mu.Lock()
|
||||
activeStart := float64(time.Since(f.origin).Microseconds()) / 1000
|
||||
telemetryBefore := f.telemetry
|
||||
f.mu.Unlock()
|
||||
if p.loss != "" {
|
||||
for _, d := range []struct{ band, rate int }{{1, p.up}, {2, p.down}} {
|
||||
tc(t, "qdisc", "change", "dev", "lo", "parent", fmt.Sprintf("1:%d", d.band), "handle", fmt.Sprintf("%d0:", d.band), "netem", "limit", "64", "delay", fmt.Sprintf("%dms", p.oneWay), "rate", fmt.Sprintf("%dkbit", d.rate), "loss", "random", p.loss)
|
||||
}
|
||||
}
|
||||
receiver, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender, err := net.DialUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.3")}, receiver.LocalAddr().(*net.UDPAddr))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { sender.Close(); receiver.Close() })
|
||||
var sent, received, denied atomic.Uint64
|
||||
var producerErrors atomic.Uint64
|
||||
f.workers.Add(1)
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
buf := make([]byte, 1200)
|
||||
for f.ctx.Err() == nil {
|
||||
receiver.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
n, _, e := receiver.ReadFromUDP(buf)
|
||||
if e == nil {
|
||||
received.Add(uint64(n))
|
||||
}
|
||||
}
|
||||
}()
|
||||
if mode != "none" {
|
||||
handler := f.state.budget.Handler()
|
||||
f.workers.Add(1)
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
tick := time.NewTicker(2200 * time.Microsecond)
|
||||
defer tick.Stop()
|
||||
renew := time.Time{}
|
||||
packet := make([]byte, 1100)
|
||||
for {
|
||||
select {
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
case now := <-tick.C:
|
||||
if mode == "gated" {
|
||||
if now.Sub(renew) >= time.Second {
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/producer", bytes.NewBufferString(`{"id":"ffffffffffffffffffffffffffffffff","class":"video","active":true,"demand_bps":4000000,"primary":true}`))
|
||||
handler.ServeHTTP(rr, req)
|
||||
renew = now
|
||||
if rr.Code != http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/permit", bytes.NewBufferString(`{"producer_id":"ffffffffffffffffffffffffffffffff","class":"video","bytes":1100}`))
|
||||
handler.ServeHTTP(rr, req)
|
||||
var permit struct {
|
||||
Granted bool `json:"granted"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &permit); err != nil || rr.Code != http.StatusOK {
|
||||
producerErrors.Add(1)
|
||||
return
|
||||
}
|
||||
if !permit.Granted {
|
||||
denied.Add(1)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if n, e := sender.Write(packet); e == nil {
|
||||
sent.Add(uint64(n))
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
var budgets []map[string]any
|
||||
for i := 0; i < seconds; i++ {
|
||||
f.pause(time.Second)
|
||||
budgets = append(budgets, f.state.budget.Snapshot())
|
||||
}
|
||||
activeEnd := float64(time.Since(f.origin).Microseconds()) / 1000
|
||||
qdisc := tc(t, "-s", "-j", "qdisc", "show", "dev", "lo")
|
||||
mu.Lock()
|
||||
events := append([]map[string]any{}, rows...)
|
||||
dropped := overflow
|
||||
mu.Unlock()
|
||||
if dropped {
|
||||
t.Error("local diagnostic ring overflowed")
|
||||
}
|
||||
var gaps, ages, telemetryElapsed []float64
|
||||
lastReceipt := activeStart
|
||||
maxSilence := 0.0
|
||||
var telemetryErrors, streamErrors int
|
||||
var tails []map[string]any
|
||||
for _, row := range events {
|
||||
at, _ := row["monotonic_ms"].(float64)
|
||||
if at < activeStart || at > activeEnd {
|
||||
continue
|
||||
}
|
||||
switch row["event"] {
|
||||
case "stream_frame_received":
|
||||
at, _ := row["monotonic_ms"].(float64)
|
||||
maxSilence = max(maxSilence, at-lastReceipt)
|
||||
lastReceipt = at
|
||||
g, _ := row["gap_ms"].(float64)
|
||||
a, _ := row["age_upper_ms"].(float64)
|
||||
gaps = append(gaps, g)
|
||||
ages = append(ages, a)
|
||||
if g >= 150 || a >= 250 {
|
||||
tails = append(tails, row)
|
||||
}
|
||||
case "telemetry":
|
||||
if elapsed, ok := row["elapsed_ms"].(int64); ok {
|
||||
telemetryElapsed = append(telemetryElapsed, float64(elapsed))
|
||||
}
|
||||
if row["error_stage"] != "" {
|
||||
telemetryErrors++
|
||||
}
|
||||
case "stream_disconnected":
|
||||
streamErrors++
|
||||
}
|
||||
}
|
||||
maxSilence = max(maxSilence, activeEnd-lastReceipt)
|
||||
if len(tails) > 12 {
|
||||
tails = tails[:12]
|
||||
}
|
||||
f.mu.Lock()
|
||||
telemetryOK := f.telemetry - telemetryBefore
|
||||
var stops []transportSample
|
||||
for _, s := range f.samples {
|
||||
if s.Mode == "stop" && s.AtMS >= activeStart && s.AtMS <= activeEnd {
|
||||
stops = append(stops, s)
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if useDatagram && mode != "unregulated" && len(stops) > 0 {
|
||||
t.Error("gated datagram profile stopped", stops)
|
||||
}
|
||||
if useDatagram && mode == "gated" && p.jitter > 0 && float64(received.Load())*8/(activeEnd-activeStart) < 384 {
|
||||
t.Error("healthy-capacity jitter profile starved optional media")
|
||||
}
|
||||
if producerErrors.Load() != 0 {
|
||||
t.Error("video producer/permit failed", producerErrors.Load())
|
||||
}
|
||||
if len(gaps) == 0 {
|
||||
t.Error("no production stream receipts measured")
|
||||
}
|
||||
if (mode == "none" || seconds >= 60) && p.loss == "" && p.up >= 256 && len(stops) > 0 {
|
||||
t.Error("critical-only admissible profile stopped")
|
||||
}
|
||||
result := map[string]any{"case": t.Name(), "started_utc": f.origin.UTC().Format(time.RFC3339Nano), "active_start_ms": activeStart, "active_end_ms": activeEnd, "profile": p.name, "mode": mode, "datagram": useDatagram,
|
||||
"telemetry_elapsed_p95_ms": percentile(telemetryElapsed, .95), "telemetry_elapsed_max_ms": percentile(telemetryElapsed, 1), "max_receipt_silence_ms": maxSilence, "receipts": len(gaps), "gap_p95_ms": percentile(gaps, .95), "gap_max_ms": percentile(gaps, 1), "age_p95_ms": percentile(ages, .95), "age_max_ms": percentile(ages, 1), "stream_errors": streamErrors, "telemetry_ok": telemetryOK, "telemetry_errors": telemetryErrors,
|
||||
"video_sent_bytes": sent.Load(), "video_received_bytes": received.Load(), "video_deferrals": denied.Load(), "stops": stops, "budget_samples": budgets, "qdisc": json.RawMessage(qdisc), "tails": tails, "local_trace_overflow": dropped, "actuator_output": false}
|
||||
raw, _ := json.Marshal(result)
|
||||
t.Log("CONTENTION_EVIDENCE " + string(raw))
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package node
|
||||
|
||||
// Worker-only real UDP sockets and production receiver/local delivery.
|
||||
// The synthetic Core and sink have no connection to a physical actuator.
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const datagramTestSend = "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
const datagramTestReceive = "3333333333333333333333333333333333333333333333333333333333333333"
|
||||
|
||||
type datagramRig struct {
|
||||
f *transportRig
|
||||
socket *net.UDPConn
|
||||
mu sync.Mutex
|
||||
tx, rx *roverDatagramCipher
|
||||
peer *net.UDPAddr
|
||||
reply roverStreamReply
|
||||
probe uint64
|
||||
probeClock roverClock
|
||||
last []byte
|
||||
drop, replay, tamper bool
|
||||
}
|
||||
|
||||
func (d *datagramRig) start(f *transportRig) {
|
||||
d.f = f
|
||||
address := "127.0.0.1"
|
||||
if f.networkFixture {
|
||||
address = "127.0.0.2"
|
||||
}
|
||||
var err error
|
||||
d.socket, err = net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP(address)})
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
d.reply = roverStreamReply{Watch: true, Clock: f.clock()}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
raw := make([]byte, 1201)
|
||||
n, peer, err := d.socket.ReadFromUDP(raw)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
d.mu.Lock()
|
||||
if d.rx != nil {
|
||||
if _, probe, ok := d.rx.open(raw[:n]); ok {
|
||||
d.peer = peer
|
||||
d.probe = probe
|
||||
d.probeClock = f.clock()
|
||||
}
|
||||
}
|
||||
d.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
f.workers.Add(1)
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
tick := time.NewTicker(50 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-f.ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
d.mu.Lock()
|
||||
d.emit()
|
||||
d.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
f.t.Cleanup(func() { d.socket.Close(); <-done })
|
||||
}
|
||||
func (d *datagramRig) grant(w http.ResponseWriter) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
channel := fmt.Sprintf("%032x", time.Now().UnixNano())
|
||||
d.tx, _ = newRoverDatagramCipher(channel, datagramTestReceive)
|
||||
d.rx, _ = newRoverDatagramCipher(channel, datagramTestSend)
|
||||
d.peer = nil
|
||||
d.f.mu.Lock()
|
||||
d.f.connects++
|
||||
d.f.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(roverDatagramGrant{channel, datagramTestSend, datagramTestReceive, d.socket.LocalAddr().(*net.UDPAddr).Port, 1200, 86400})
|
||||
}
|
||||
func (d *datagramRig) emit() {
|
||||
if d.peer == nil || d.tx == nil || d.drop {
|
||||
return
|
||||
}
|
||||
reply := d.reply
|
||||
reply.Clock = d.f.clock()
|
||||
raw, _ := json.Marshal(roverDatagramFrame{d.probe, d.probeClock, reply})
|
||||
packet, err := d.tx.seal(raw)
|
||||
if err != nil {
|
||||
d.f.t.Error(err)
|
||||
return
|
||||
}
|
||||
if d.replay {
|
||||
packet = d.last
|
||||
} else if d.tamper {
|
||||
packet[len(packet)-1] ^= 1
|
||||
} else {
|
||||
d.last = append([]byte(nil), packet...)
|
||||
}
|
||||
if len(packet) > 0 {
|
||||
d.socket.WriteToUDP(packet, d.peer)
|
||||
}
|
||||
}
|
||||
func (d *datagramRig) write(raw []byte) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if err := json.Unmarshal(raw, &d.reply); err != nil {
|
||||
d.f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func newDatagramRig(t *testing.T, network bool) *transportRig {
|
||||
return newTransportRig(t, func(f *transportRig) { f.datagram = &datagramRig{}; f.networkFixture = network })
|
||||
}
|
||||
func TestWorkerDatagramLatestSurvivesMissingPackets(t *testing.T) {
|
||||
f := newDatagramRig(t, false)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
for seq := 2; seq <= 30; seq++ {
|
||||
f.pause(40 * time.Millisecond)
|
||||
f.datagram.mu.Lock()
|
||||
f.datagram.drop = seq%3 == 0
|
||||
f.datagram.mu.Unlock()
|
||||
f.write(f.frame(transportSession, seq), false)
|
||||
}
|
||||
f.datagram.mu.Lock()
|
||||
f.datagram.drop = false
|
||||
f.datagram.mu.Unlock()
|
||||
f.send(transportSession, 31)
|
||||
f.assertContinuous(first)
|
||||
}
|
||||
func TestWorkerDatagramGuardReplayAndTamper(t *testing.T) {
|
||||
for _, kind := range []string{"silence", "replay", "tamper"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
f := newDatagramRig(t, false)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
f.datagram.mu.Lock()
|
||||
f.datagram.drop = kind == "silence"
|
||||
f.datagram.replay = kind == "replay"
|
||||
f.datagram.tamper = kind == "tamper"
|
||||
f.datagram.mu.Unlock()
|
||||
f.until("unchanged guard stops invalid traffic", func() bool { _, ok := f.stopAfter(first.AtMS); return ok })
|
||||
stop, _ := f.stopAfter(first.AtMS)
|
||||
if stop.AtMS-first.AtMS > 450 {
|
||||
t.Fatalf("late stop: %+v", stop)
|
||||
}
|
||||
f.datagram.mu.Lock()
|
||||
f.datagram.drop = false
|
||||
f.datagram.replay = false
|
||||
f.datagram.tamper = false
|
||||
f.datagram.mu.Unlock()
|
||||
f.pause(800 * time.Millisecond)
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWorkerDatagramNoDeadlineRefreshFromKeepalive(t *testing.T) {
|
||||
f := newDatagramRig(t, false)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
f.until("original command expiry", func() bool { _, ok := f.stopAfter(first.AtMS); return ok })
|
||||
stop, _ := f.stopAfter(first.AtMS)
|
||||
if stop.AtMS-first.AtMS > 450 {
|
||||
t.Fatalf("expiry extended: %+v", stop)
|
||||
}
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
}
|
||||
func TestWorkerDatagramNoTCPACKDependency(t *testing.T) {
|
||||
if os.Getenv("MISSION_CORE_ISOLATED_NETEM") != "1" {
|
||||
t.Skip("isolated Worker netem required")
|
||||
}
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil || len(interfaces) != 1 || interfaces[0].Name != "lo" {
|
||||
t.Fatal("loopback-only required")
|
||||
}
|
||||
f := newDatagramRig(t, true)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
datagramTC(t, "qdisc", "add", "dev", "lo", "root", "handle", "1:", "prio", "bands", "3")
|
||||
defer datagramTC(t, "qdisc", "del", "dev", "lo", "root")
|
||||
datagramTC(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "pref", "7", "u32", "match", "ip", "dst", "127.0.0.2/32", "match", "ip", "protocol", "6", "0xff", "action", "drop")
|
||||
for seq := 2; seq <= 60; seq++ {
|
||||
f.pause(50 * time.Millisecond)
|
||||
f.write(f.frame(transportSession, seq), false)
|
||||
}
|
||||
f.send(transportSession, 61)
|
||||
f.assertContinuous(first)
|
||||
counters := string(datagramTC(t, "-s", "filter", "show", "dev", "lo", "parent", "1:", "pref", "7"))
|
||||
if strings.Contains(counters, "dropped 0,") {
|
||||
t.Fatal("TCP fault did not engage")
|
||||
}
|
||||
t.Log("DATAGRAM_ACK_EVIDENCE " + counters)
|
||||
}
|
||||
|
||||
func datagramTC(t *testing.T, args ...string) []byte {
|
||||
t.Helper()
|
||||
raw, err := exec.Command("tc", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("tc: %v %s", err, raw)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package node
|
||||
|
||||
// Opt-in ordinary cross-language test. The Python side owns a temporary Core
|
||||
// registry and real mTLS/UDP endpoints. Delivery is observed only in RAM.
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPythonDatagramInterop(t *testing.T) {
|
||||
path := os.Getenv("MISSION_CORE_PYTHON_INTEROP")
|
||||
if path == "" {
|
||||
t.Skip("temporary Python fixture required")
|
||||
}
|
||||
var c struct {
|
||||
Endpoint, CA, Certificate, Key, Directory string
|
||||
Base map[string]any
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = json.Unmarshal(raw, &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pair, err := tls.X509KeyPair([]byte(c.Certificate), []byte(c.Key))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM([]byte(c.CA)) {
|
||||
t.Fatal("invalid test CA")
|
||||
}
|
||||
tr := newRoverHTTPTransport(&tls.Config{RootCAs: pool, Certificates: []tls.Certificate{pair}, MinVersion: tls.VersionTLS13, ServerName: "192.168.20.5"})
|
||||
client := &http.Client{Transport: tr, Timeout: 3 * time.Second}
|
||||
defer client.CloseIdleConnections()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.budget, err = OpenLinkBudget("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !roverConnectTelemetry(ctx, client, c.Endpoint, c.Base, state) {
|
||||
t.Fatal("mTLS capability failed")
|
||||
}
|
||||
state.mu.Lock()
|
||||
enabled := state.latestDatagram
|
||||
revision := state.stopRevision
|
||||
state.mu.Unlock()
|
||||
if !enabled {
|
||||
t.Fatal("datagram not advertised")
|
||||
}
|
||||
state.delivered(map[string]any{"state": "observing", "release_confirmed": true}, revision)
|
||||
state.setWatch(true)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- roverReadDatagram(ctx, client, c.Endpoint, c.Base, state) }()
|
||||
defer func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("receiver did not exit")
|
||||
}
|
||||
}()
|
||||
ready := false
|
||||
seen := map[int]bool{}
|
||||
var session string
|
||||
var first, last float64
|
||||
for ctx.Err() == nil {
|
||||
select {
|
||||
case err := <-done:
|
||||
done <- err
|
||||
if len(seen) != 3 {
|
||||
t.Fatalf("incomplete neutral delivery: %v err=%v", seen, err)
|
||||
}
|
||||
state.stopStream()
|
||||
_, command, stop := state.delivery(time.Now())
|
||||
if command != nil || stop == 0 {
|
||||
t.Fatal("revocation did not stop")
|
||||
}
|
||||
state.mu.Lock()
|
||||
retired := state.retired[session]
|
||||
state.mu.Unlock()
|
||||
if !retired {
|
||||
t.Fatal("interrupted session not retired")
|
||||
}
|
||||
fmt.Printf("PYTHON_INTEROP_EVIDENCE {\"sequences\":%d,\"first_ttl_ms\":%.3f,\"last_ttl_ms\":%.3f,\"retired\":true,\"actuator_output\":false}\n", len(seen), first, last)
|
||||
return
|
||||
default:
|
||||
}
|
||||
state.mu.Lock()
|
||||
received := !state.streamReceived.IsZero()
|
||||
state.mu.Unlock()
|
||||
if received && !ready {
|
||||
if err := os.WriteFile(filepath.Join(c.Directory, "ready"), []byte("ready"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ready = true
|
||||
}
|
||||
_, command, _ := state.delivery(time.Now())
|
||||
if command != nil {
|
||||
if command["left"] != float64(0) || command["right"] != float64(0) {
|
||||
t.Fatal("non-neutral command")
|
||||
}
|
||||
ttl, _ := finiteNumber(command["ttl_ms"])
|
||||
if ttl <= 0 || ttl > 400 {
|
||||
t.Fatal("invalid residual TTL", ttl)
|
||||
}
|
||||
seq := int(command["sequence"].(float64))
|
||||
session = command["id"].(string)
|
||||
if seq > 0 && !seen[seq] {
|
||||
seen[seq] = true
|
||||
if first == 0 {
|
||||
first = ttl
|
||||
}
|
||||
last = ttl
|
||||
if err := os.WriteFile(filepath.Join(c.Directory, fmt.Sprintf("seen-%d", seq)), []byte("seen"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("Python fixture deadline")
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
package node
|
||||
|
||||
// Opt-in Worker 006 qualification. Production TLS/NDJSON reception, clock
|
||||
// sampling, reconnect and local delivery run against a synthetic Core. Only
|
||||
// the private driver RPC is replaced: every intent is neutral and stays in RAM.
|
||||
// This injects application delivery stalls, NOT network rate/loss or DERP.
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type transportWrite struct {
|
||||
data []byte
|
||||
close bool
|
||||
done chan error
|
||||
}
|
||||
type transportSample struct {
|
||||
AtMS float64 `json:"at_ms"`
|
||||
Mode string `json:"mode"`
|
||||
Session string `json:"session,omitempty"`
|
||||
Sequence float64 `json:"sequence,omitempty"`
|
||||
TTLMS float64 `json:"ttl_ms,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type transportRig struct {
|
||||
t *testing.T
|
||||
origin time.Time
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
workers sync.WaitGroup
|
||||
server *httptest.Server
|
||||
state *roverStreamState
|
||||
wire chan transportWrite
|
||||
mu sync.Mutex
|
||||
blocked bool
|
||||
epoch string
|
||||
connects, telemetry int
|
||||
samples []transportSample
|
||||
faults []string
|
||||
deadlines map[string]float64
|
||||
datagram *datagramRig
|
||||
networkFixture bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func newTransportRig(t *testing.T, options ...func(*transportRig)) *transportRig {
|
||||
t.Helper()
|
||||
f := &transportRig{t: t, origin: time.Now(), timeout: 20 * time.Second, wire: make(chan transportWrite), epoch: testClockID, deadlines: map[string]float64{}}
|
||||
for _, option := range options {
|
||||
option(f)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), f.timeout)
|
||||
f.ctx, f.cancel = ctx, cancel
|
||||
f.state = newRoverStreamState(f.origin)
|
||||
var err error
|
||||
f.state.budget, err = OpenLinkBudget("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sensors := isolatedSensors(t)
|
||||
var model *sensorModel
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
model = &sensorModels[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if model == nil {
|
||||
t.Fatal("missing model")
|
||||
}
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
var body struct {
|
||||
Command map[string]any `json:"command"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 8192)).Decode(&body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if body.Command != nil {
|
||||
c := body.Command
|
||||
f.mu.Lock()
|
||||
key := fmt.Sprintf("%s/%.0f", c["id"], c["sequence"])
|
||||
expiry, exists := f.deadlines[key]
|
||||
ttl, ok := finiteNumber(c["ttl_ms"])
|
||||
if c["left"] != float64(0) || c["right"] != float64(0) || !ok || ttl <= 0 || ttl > 400 || !exists || ttl > expiry-f.clockMS()+1 {
|
||||
f.faults = append(f.faults, fmt.Sprintf("invalid/unowned/non-neutral delivery %s ttl=%v", key, c["ttl_ms"]))
|
||||
}
|
||||
f.mu.Unlock()
|
||||
return testSensorReply(f.sinkSnapshot(c)), nil
|
||||
}
|
||||
return testSensorReply(f.sinkSnapshot(nil)), nil
|
||||
})
|
||||
f.server = httptest.NewUnstartedServer(http.HandlerFunc(f.serve))
|
||||
if f.networkFixture {
|
||||
f.server.Listener.Close()
|
||||
f.server.Listener, err = net.Listen("tcp4", "127.0.0.2:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Drain local diagnostics in RAM; the fixture negotiates a dedicated lane,
|
||||
// so measurement events cannot change traffic on the shaped link.
|
||||
f.state.setDev(map[string]any{"id": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "enabled": true, "options": map[string]any{"network": true}})
|
||||
}
|
||||
f.server.StartTLS()
|
||||
if f.datagram != nil {
|
||||
f.datagram.start(f)
|
||||
}
|
||||
// Separate connection pools, as in runRoverChannel. The generated test CA is
|
||||
// trusted by httptest; no credentials, host routes or certificate bypass.
|
||||
client := func() *http.Client {
|
||||
tr := newRoverHTTPTransport(f.server.Client().Transport.(*http.Transport).TLSClientConfig.Clone())
|
||||
if f.networkFixture {
|
||||
tr.TLSClientConfig.ServerName = "127.0.0.1" // Verify the httptest certificate identity while dialing its loopback alias.
|
||||
tr.DialContext = (&net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.3")}, Timeout: roverConnectTimeout}).DialContext
|
||||
}
|
||||
return &http.Client{Transport: tr}
|
||||
}
|
||||
stream, telemetry := client(), client()
|
||||
telemetry.Timeout = 300 * time.Millisecond
|
||||
f.workers.Add(3)
|
||||
go func() { defer f.workers.Done(); roverCommands(ctx, stream, f.server.URL, map[string]any{}, f.state) }()
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
roverTelemetry(ctx, telemetry, f.server.URL, map[string]any{}, f.state)
|
||||
}()
|
||||
go func() {
|
||||
defer f.workers.Done()
|
||||
var delivery roverLocalDelivery
|
||||
for ctx.Err() == nil {
|
||||
select {
|
||||
case <-f.state.wake:
|
||||
default:
|
||||
}
|
||||
started := time.Now()
|
||||
frame := delivery.run(ctx, sensors, model, f.state, "synthetic-no-output", started)
|
||||
if frame.Delivery == "intent" || frame.Delivery == "stop" {
|
||||
f.mu.Lock()
|
||||
f.samples = append(f.samples, transportSample{AtMS: float64(started.Sub(f.origin).Microseconds()) / 1000, Mode: frame.Delivery, Session: frame.Session, Sequence: frame.Sequence, TTLMS: frame.TTLMS, Reason: frame.Reason})
|
||||
f.mu.Unlock()
|
||||
}
|
||||
timer := time.NewTimer(max(0, 50*time.Millisecond-time.Since(started)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-f.state.wake:
|
||||
case <-timer.C:
|
||||
}
|
||||
timer.Stop()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
f.workers.Wait()
|
||||
stream.CloseIdleConnections()
|
||||
telemetry.CloseIdleConnections()
|
||||
f.server.Close()
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.faults) > 0 {
|
||||
t.Error(f.faults)
|
||||
}
|
||||
evidence := map[string]any{"case": t.Name(), "started_utc": f.origin.UTC().Format(time.RFC3339Nano), "duration_ms": time.Since(f.origin).Milliseconds(), "connections": f.connects, "telemetry_replies": f.telemetry, "samples": f.samples, "violations": f.faults, "actuator_output": false}
|
||||
raw, _ := json.Marshal(evidence)
|
||||
t.Log("TRANSPORT_EVIDENCE " + string(raw))
|
||||
})
|
||||
f.until("initial TLS stream and acknowledged stop", func() bool {
|
||||
f.mu.Lock()
|
||||
connections := f.connects
|
||||
f.mu.Unlock()
|
||||
f.state.mu.Lock()
|
||||
ready := !f.state.stopPending && !f.state.streamReceived.IsZero()
|
||||
f.state.mu.Unlock()
|
||||
return connections > 0 && ready
|
||||
})
|
||||
return f
|
||||
}
|
||||
func (f *transportRig) clockMS() float64 {
|
||||
return 10000 + float64(time.Since(f.origin).Microseconds())/1000
|
||||
}
|
||||
func (f *transportRig) clock() roverClock {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return roverClock{f.epoch, f.clockMS()}
|
||||
}
|
||||
func (f *transportRig) serve(w http.ResponseWriter, r *http.Request) {
|
||||
// Production Core consumes the JSON request before streaming. Draining here
|
||||
// also lets net/http observe a cancelled request while response headers wait.
|
||||
io.Copy(io.Discard, io.LimitReader(r.Body, 65536))
|
||||
switch r.URL.Path {
|
||||
case "/v1/node/rover-link":
|
||||
json.NewEncoder(w).Encode(map[string]any{"latest_datagram_v1": f.datagram != nil, "connected": true, "sample_clock_v1": true, "budget_interval_v1": true, "diagnostic_lane_v1": f.networkFixture, "rover_details_v1": f.networkFixture, "control_clock": f.clock()})
|
||||
case "/v1/node/rover":
|
||||
reply := roverStreamReply{Watch: true, Clock: f.clock()}
|
||||
if f.networkFixture {
|
||||
active := true
|
||||
reply.ControlActive = &active
|
||||
}
|
||||
json.NewEncoder(w).Encode(reply)
|
||||
f.mu.Lock()
|
||||
f.telemetry++
|
||||
f.mu.Unlock()
|
||||
case "/v1/node/rover-datagram":
|
||||
if f.datagram == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
f.datagram.grant(w)
|
||||
case "/v1/node/rover-stream":
|
||||
// During an outage, reconnects cannot acquire a fresh response. Telemetry
|
||||
// deliberately stays up: its liveness must never renew command authority.
|
||||
for {
|
||||
f.mu.Lock()
|
||||
blocked := f.blocked
|
||||
f.mu.Unlock()
|
||||
if !blocked {
|
||||
break
|
||||
}
|
||||
if !roverWait(r.Context(), 10*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: f.clock()})
|
||||
w.(http.Flusher).Flush()
|
||||
f.mu.Lock()
|
||||
f.connects++
|
||||
f.mu.Unlock()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case job := <-f.wire:
|
||||
_, err := w.Write(job.data)
|
||||
w.(http.Flusher).Flush()
|
||||
job.done <- err
|
||||
if err != nil || job.close {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
func (f *transportRig) until(label string, fn func() bool) {
|
||||
f.t.Helper()
|
||||
duration := 1500 * time.Millisecond
|
||||
if f.networkFixture {
|
||||
duration = 4 * time.Second
|
||||
}
|
||||
limit := time.Now().Add(duration)
|
||||
for time.Now().Before(limit) && f.ctx.Err() == nil {
|
||||
if fn() {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if f.networkFixture {
|
||||
f.state.mu.Lock()
|
||||
raw, _ := json.Marshal(f.state.devEvents)
|
||||
f.state.mu.Unlock()
|
||||
f.t.Log("INITIAL_TRACE " + string(raw))
|
||||
}
|
||||
f.t.Fatal("timed out: " + label)
|
||||
}
|
||||
func (f *transportRig) pause(d time.Duration) {
|
||||
f.t.Helper()
|
||||
if !roverWait(f.ctx, d) {
|
||||
f.t.Fatal("fixture deadline")
|
||||
}
|
||||
}
|
||||
func (f *transportRig) frame(id string, sequence int) []byte {
|
||||
clock := f.clock()
|
||||
reply := streamIntent(sequence, clock.MonotonicMS, clock.MonotonicMS+400)
|
||||
reply.Clock = clock
|
||||
reply.Command["id"] = id
|
||||
reply.Command["left"] = float64(0)
|
||||
reply.Command["right"] = float64(0)
|
||||
f.mu.Lock()
|
||||
f.deadlines[fmt.Sprintf("%s/%d", id, sequence)] = clock.MonotonicMS + 400
|
||||
f.mu.Unlock()
|
||||
raw, err := json.Marshal(reply)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return append(raw, '\n')
|
||||
}
|
||||
func (f *transportRig) write(raw []byte, close bool) {
|
||||
f.t.Helper()
|
||||
if f.datagram != nil {
|
||||
f.datagram.write(raw)
|
||||
return
|
||||
}
|
||||
job := transportWrite{data: raw, close: close, done: make(chan error, 1)}
|
||||
select {
|
||||
case f.wire <- job:
|
||||
case <-f.ctx.Done():
|
||||
f.t.Fatal("no stream for injection")
|
||||
}
|
||||
select {
|
||||
case err := <-job.done:
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
case <-f.ctx.Done():
|
||||
f.t.Fatal("write did not finish")
|
||||
}
|
||||
}
|
||||
func (f *transportRig) send(id string, seq int) {
|
||||
f.t.Helper()
|
||||
f.write(f.frame(id, seq), false)
|
||||
f.until("neutral intent delivery", func() bool { return f.hasIntent(id, seq) })
|
||||
}
|
||||
func (f *transportRig) hasIntent(id string, seq int) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, s := range f.samples {
|
||||
if s.Mode == "intent" && s.Session == id && s.Sequence == float64(seq) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (f *transportRig) lastIntent() transportSample {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for i := len(f.samples) - 1; i >= 0; i-- {
|
||||
if f.samples[i].Mode == "intent" {
|
||||
return f.samples[i]
|
||||
}
|
||||
}
|
||||
f.t.Fatal("missing neutral intent")
|
||||
return transportSample{}
|
||||
}
|
||||
func (f *transportRig) stopAfter(at float64) (transportSample, bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, s := range f.samples {
|
||||
if s.Mode == "stop" && s.AtMS > at {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
return transportSample{}, false
|
||||
}
|
||||
func (f *transportRig) assertContinuous(since transportSample) {
|
||||
f.t.Helper()
|
||||
if stop, ok := f.stopAfter(since.AtMS); ok {
|
||||
f.t.Fatalf("unexpected stop within delivery envelope: %+v", stop)
|
||||
}
|
||||
}
|
||||
func (f *transportRig) recoverFreshIdentity(old string) {
|
||||
f.t.Helper()
|
||||
f.until("stop acknowledged", func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return !f.state.stopPending })
|
||||
f.write(f.frame(old, 1000), false)
|
||||
f.pause(100 * time.Millisecond)
|
||||
if f.hasIntent(old, 1000) {
|
||||
f.t.Fatal("interrupted identity was rearmed")
|
||||
}
|
||||
f.send("cccccccccccccccccccccccccccccccc", 1)
|
||||
}
|
||||
|
||||
const transportSession = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
|
||||
func TestWorkerTransportContinuousAndJitter(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
for i, d := range []time.Duration{50, 50, 50, 20, 90, 150, 50, 200, 50, 90, 50} {
|
||||
f.pause(d * time.Millisecond)
|
||||
f.send(transportSession, i+2)
|
||||
}
|
||||
f.assertContinuous(first)
|
||||
}
|
||||
func TestWorkerTransportRecordedBatch241ms(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
var batch []byte
|
||||
for i := 2; i <= 5; i++ {
|
||||
f.pause(50 * time.Millisecond)
|
||||
batch = append(batch, f.frame(transportSession, i)...)
|
||||
}
|
||||
f.pause(41 * time.Millisecond)
|
||||
f.write(batch, false)
|
||||
f.until("latest batched intent", func() bool { return f.hasIntent(transportSession, 5) })
|
||||
f.assertContinuous(first)
|
||||
// All four original expiries are retained. Coalescing may skip intermediate
|
||||
// sequences, so the test does not require every queued frame to reach a sink.
|
||||
}
|
||||
func TestWorkerTransportOutageMatrix(t *testing.T) {
|
||||
for _, duration := range []time.Duration{200 * time.Millisecond, 500 * time.Millisecond, 2 * time.Second, 10 * time.Second} {
|
||||
t.Run(duration.String(), func(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
f.mu.Lock()
|
||||
f.blocked = true
|
||||
connections := f.connects
|
||||
telemetry := f.telemetry
|
||||
f.mu.Unlock()
|
||||
f.pause(duration)
|
||||
if duration < 350*time.Millisecond {
|
||||
f.mu.Lock()
|
||||
f.blocked = false
|
||||
f.mu.Unlock()
|
||||
f.send(transportSession, 2)
|
||||
f.assertContinuous(first)
|
||||
return
|
||||
}
|
||||
stop, ok := f.stopAfter(first.AtMS)
|
||||
if !ok || stop.AtMS-first.AtMS > 450 {
|
||||
t.Fatalf("no bounded stop: first=%+v stop=%+v", first, stop)
|
||||
}
|
||||
if stop.Reason != "stream_unavailable" && stop.Reason != "command_deadline_expired" {
|
||||
t.Fatal("unexpected stop cause", stop)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.blocked = false
|
||||
replies := f.telemetry - telemetry
|
||||
f.mu.Unlock()
|
||||
if replies < 1 {
|
||||
t.Fatal("telemetry was not independent during the command outage")
|
||||
}
|
||||
f.until("reconnected TLS stream", func() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.connects > connections })
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWorkerTransportCorruptAndClosedStreams(t *testing.T) {
|
||||
for _, fault := range []string{"invalid-json", "oversize", "truncated", "closed"} {
|
||||
t.Run(fault, func(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
f.mu.Lock()
|
||||
connections := f.connects
|
||||
f.mu.Unlock()
|
||||
raw := []byte("not-json\n")
|
||||
close := false
|
||||
switch fault {
|
||||
case "oversize":
|
||||
raw = []byte(strings.Repeat("x", 32769) + "\n")
|
||||
case "truncated":
|
||||
raw = []byte("{\"watch\":")
|
||||
close = true
|
||||
case "closed":
|
||||
raw = nil
|
||||
close = true
|
||||
}
|
||||
f.write(raw, close)
|
||||
f.until("stop on broken stream", func() bool { _, ok := f.stopAfter(first.AtMS); return ok })
|
||||
stop, _ := f.stopAfter(first.AtMS)
|
||||
if stop.AtMS-first.AtMS > 450 {
|
||||
t.Fatal("late stop", stop)
|
||||
}
|
||||
f.until("new stream", func() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.connects > connections })
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestWorkerTransportCoreEpochChange(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
f.send(transportSession, 1)
|
||||
first := f.lastIntent()
|
||||
f.mu.Lock()
|
||||
f.epoch = "dddddddddddddddddddddddddddddddd"
|
||||
f.mu.Unlock()
|
||||
f.until("stop on clock identity change", func() bool { _, ok := f.stopAfter(first.AtMS); return ok })
|
||||
stop, _ := f.stopAfter(first.AtMS)
|
||||
if stop.Reason != "core_clock_changed" {
|
||||
t.Fatal("wrong stop reason", stop)
|
||||
}
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
}
|
||||
|
||||
func TestWorkerTransportAgedCommandKeepsResidualDeadline(t *testing.T) {
|
||||
f := newTransportRig(t)
|
||||
raw := f.frame(transportSession, 1)
|
||||
f.pause(125 * time.Millisecond)
|
||||
f.write(raw, false)
|
||||
f.until("aged neutral intent", func() bool { return f.hasIntent(transportSession, 1) })
|
||||
first := f.lastIntent()
|
||||
if first.TTLMS > 275 || first.TTLMS < 175 {
|
||||
t.Fatal("receipt refreshed or unexpectedly exhausted original expiry", first)
|
||||
}
|
||||
f.until("residual deadline stop", func() bool { _, ok := f.stopAfter(first.AtMS); return ok })
|
||||
stop, _ := f.stopAfter(first.AtMS)
|
||||
elapsed := stop.AtMS - first.AtMS
|
||||
if stop.Reason != "command_deadline_expired" || elapsed < first.TTLMS-2 || elapsed > first.TTLMS+75 {
|
||||
t.Fatalf("wrong expiry boundary: intent=%+v stop=%+v", first, stop)
|
||||
}
|
||||
f.recoverFreshIdentity(transportSession)
|
||||
}
|
||||
|
||||
// The shaped-link fixture includes two synthetic motor telemetry rows so its
|
||||
// critical upload is not the empty observer payload. No physical samples exist.
|
||||
func (f *transportRig) sinkSnapshot(command map[string]any) map[string]any {
|
||||
out := map[string]any{"state": "observing"}
|
||||
if command != nil {
|
||||
out["state"] = "ready"
|
||||
out["session_id"] = command["id"]
|
||||
}
|
||||
if !f.networkFixture {
|
||||
return out
|
||||
}
|
||||
out["instance"] = "synthetic-driver"
|
||||
out["supported"] = true
|
||||
out["control_modes"] = []any{"rpm", "duty"}
|
||||
out["profile"] = map[string]any{"revision": float64(1)}
|
||||
out["release_confirmed"] = true
|
||||
var devices []any
|
||||
for _, side := range []string{"left", "right"} {
|
||||
devices = append(devices, map[string]any{"id": side, "uuid": "synthetic-" + side, "slot": side + ".1", "label": side, "session_id": "synthetic-attachment-" + side, "age_ms": float64(20), "sample_time_ms": f.clockMS(),
|
||||
"values": map[string]any{"erpm": 0, "motor_current_a": 0, "input_current_a": 0, "input_voltage_v": 48, "duty_cycle": 0, "temp_mos_c": 30, "temp_motor_c": 30, "fault_code": 0, "amp_hours": 0, "watt_hours": 0, "tachometer": 0, "tachometer_abs": 0},
|
||||
"receiver": map[string]any{"active": false, "value": 0}, "current_limits": map[string]any{"motor_max_a": 30, "motor_min_a": -30}})
|
||||
}
|
||||
out["devices"] = devices
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user