From e06ff9a214a32e93040244eaca8ae065f494e2da Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:10:01 +0300 Subject: [PATCH] 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. --- .../src/components/rover/RoverDevWindow.tsx | 32 + .../src/components/rover/RoverLogs.tsx | 24 + .../src/components/rover/RoverTelemetry.tsx | 32 +- .../src/components/rover/RoverView.tsx | 67 +- .../components/rover/editor/RoverScene.tsx | 2 +- .../src/components/rover/rover.css | 12 +- .../src/components/rover/roverLogs.css | 10 + .../src/core/fleet/observationLayout.ts | 4 + .../src/core/fleet/observationSync.ts | 48 + .../src/core/fleet/roverDevEvents.ts | 38 + .../src/core/fleet/roverFaultNotice.ts | 18 + .../src/core/fleet/roverHoldInput.ts | 47 +- .../src/core/fleet/roverInput.ts | 18 +- .../src/core/fleet/roverLogSave.ts | 16 + .../src/core/fleet/roverLogTransfer.ts | 62 + .../src/core/fleet/roverObservation.ts | 21 + .../src/core/fleet/roverOperatorCapture.ts | 12 + .../src/core/fleet/roverRecovery.ts | 84 + .../src/core/fleet/roverTiming.ts | 36 + .../src/core/fleet/roverTransport.ts | 107 ++ .../src/core/fleet/sensorTransport.ts | 14 +- .../src/core/fleet/useBoardNetwork.ts | 35 + .../src/core/fleet/useFleet.ts | 4 +- .../src/core/fleet/useRoverControl.ts | 142 +- .../src/core/fleet/useRoverDiagnostics.ts | 61 + .../src/core/fleet/useVehicleObservation.ts | 119 +- .../workspaces/fleet/BoardNetworkSettings.tsx | 31 + apps/control-station/test/liveTiming.test.mjs | 32 + .../test/observationSync.test.mjs | 34 + .../test/roverControlFocus.test.mjs | 16 +- .../test/roverControlStartup.test.mjs | 228 ++- .../test/roverDevEvents.test.mjs | 15 + .../test/roverFaultNotice.test.mjs | 19 + .../test/roverHoldInput.test.mjs | 34 +- apps/control-station/test/roverInput.test.mjs | 33 +- .../test/roverLocalEvidence.test.mjs | 54 + .../test/roverLogSave.test.mjs | 47 + .../test/roverObservationLifecycle.test.mjs | 153 ++ .../test/roverObservationStatus.test.mjs | 27 + .../test/roverOperatorCapture.test.mjs | 33 + .../test/roverRecovery.test.mjs | 162 ++ .../test/roverRecoveryContinuity.test.mjs | 50 + .../test/roverStopRecoveryBench.test.mjs | 21 + .../test/roverTransport.test.mjs | 72 + .../test/roverTransportStartup.test.mjs | 49 + .../test/sensorTransportFreshness.test.mjs | 17 + apps/node-agent/cmd/node-agent/main.go | 36 +- apps/node-agent/internal/node/link_budget.go | 284 ++++ .../internal/node/link_budget_test.go | 152 ++ .../internal/node/link_command_health.go | 99 ++ .../internal/node/link_command_health_test.go | 264 ++++ .../internal/node/link_datagram_feedback.go | 164 ++ .../node/link_datagram_feedback_test.go | 157 ++ .../internal/node/link_operator_view_test.go | 183 +++ .../internal/node/link_producers.go | 154 ++ .../internal/node/link_producers_test.go | 68 + apps/node-agent/internal/node/link_runtime.go | 338 ++++ .../internal/node/link_runtime_test.go | 103 ++ .../internal/node/link_stop_recovery_test.go | 40 + .../internal/node/network_profile.go | 478 ++++++ .../internal/node/network_profile_test.go | 105 ++ apps/node-agent/internal/node/pairing.go | 8 +- .../internal/node/pairing_budget_test.go | 147 ++ .../internal/node/pairing_encoding_test.go | 72 + .../internal/node/pairing_liveness.go | 77 + .../internal/node/pairing_recovery.go | 7 +- .../internal/node/pairing_recovery_test.go | 3 + .../internal/node/pairing_transport.go | 67 +- .../node-agent/internal/node/rover_channel.go | 141 +- .../internal/node/rover_control_activity.go | 20 + .../node/rover_control_activity_test.go | 75 + .../internal/node/rover_datagram.go | 218 +++ .../internal/node/rover_datagram_codec.go | 68 + .../node/rover_datagram_codec_test.go | 43 + .../node/rover_datagram_continuity_test.go | 218 +++ apps/node-agent/internal/node/rover_dev.go | 206 +++ .../internal/node/rover_dev_test.go | 73 + .../internal/node/rover_diagnostics.go | 129 +- .../internal/node/rover_diagnostics_lane.go | 194 +++ .../node/rover_diagnostics_low_rate_test.go | 63 + .../internal/node/rover_diagnostics_test.go | 83 + .../internal/node/rover_error_kind_test.go | 44 + .../internal/node/rover_export_lane_test.go | 84 + .../internal/node/rover_http_trace.go | 64 + .../internal/node/rover_http_trace_test.go | 83 + apps/node-agent/internal/node/rover_link.go | 66 + .../internal/node/rover_link_test.go | 148 ++ .../internal/node/rover_local_delivery.go | 84 + .../node/rover_local_delivery_test.go | 184 +++ .../internal/node/rover_metadata.go | 89 ++ .../internal/node/rover_metadata_test.go | 83 + .../internal/node/rover_stream_health.go | 34 + .../internal/node/rover_stream_state.go | 116 +- .../internal/node/rover_stream_state_test.go | 41 + .../internal/node/rover_transport.go | 22 + .../node/sensor_failure_result_test.go | 37 + .../node-agent/internal/node/sensor_models.go | 12 +- .../internal/node/sensor_snapshots.go | 67 + .../internal/node/sensor_snapshots_test.go | 61 + .../internal/node/sensor_telemetry.go | 38 + .../internal/node/sensor_telemetry_test.go | 40 + .../internal/node/sensor_vesc_packages.go | 60 + .../node/sensor_vesc_packages_test.go | 10 + .../internal/node/sensor_vesc_test.go | 117 +- .../internal/node/sensor_vesc_transport.go | 141 ++ apps/node-agent/internal/node/sensors.go | 37 +- apps/node-agent/internal/node/server.go | 4 + .../testdata/command-jitter-redacted.json | 1388 +++++++++++++++++ apps/wireguard-client/build_macos.py | 50 + apps/wireguard-client/helper.py | 411 +++++ apps/wireguard-client/install_macos.py | 86 + apps/wireguard-client/test_helper.py | 19 + .../2026-10-26-network-runtime-and-dev.md | 99 ++ docs/node/04_NODE_CORE_PAIRING_PROTOCOL.md | 19 + .../node/25_OBSERVATION_AND_REMOTE_CONTROL.md | 417 +++++ docs/node/38_SHARED_LINK_BUDGET.md | 515 ++++++ docs/node/39_NETWORK_RUNTIME_AB.md | 1127 +++++++++++++ docs/node/40_WIREGUARD_FLEET_NETWORK.md | 64 + scripts/qualification/capture_rover_local.py | 222 +++ scripts/qualification/package_link_budget.py | 163 ++ scripts/qualification/passive_runtime.py | 424 +++++ src/k1link/fleet/channel_binding.py | 40 + src/k1link/fleet/heartbeat_encoding.py | 21 + src/k1link/fleet/network_client.py | 77 + src/k1link/fleet/network_media.py | 55 + src/k1link/fleet/network_profiles.py | 358 +++++ src/k1link/fleet/recovery.py | 10 +- src/k1link/fleet/registry.py | 142 +- src/k1link/fleet/rover_channel.py | 132 ++ src/k1link/fleet/rover_control.py | 270 +++- src/k1link/fleet/rover_datagram.py | 182 +++ src/k1link/fleet/rover_diagnostics.py | 189 +++ src/k1link/fleet/rover_diagnostics_export.py | 158 ++ src/k1link/fleet/rover_local_trace.py | 54 + src/k1link/fleet/rover_metadata.py | 81 + .../fleet/rover_observation_evidence.py | 59 + src/k1link/fleet/rover_preview_evidence.py | 67 + src/k1link/fleet/rover_stop_evidence.py | 48 + src/k1link/fleet/rover_stream_timing.py | 50 + src/k1link/fleet/sensor_transient.py | 91 ++ src/k1link/fleet/sensors.py | 10 +- src/k1link/fleet/transport.py | 45 +- src/k1link/web/app.py | 3 + src/k1link/web/fleet_api.py | 14 +- src/k1link/web/fleet_network_api.py | 47 + src/k1link/web/rover_api.py | 20 +- src/k1link/web/rover_diagnostics_api.py | 149 ++ src/k1link/web/rover_runtime_diagnostics.py | 41 + src/k1link/web/rover_socket.py | 126 ++ src/k1link/web/runtime_http_timing.py | 68 + tests/fleet/test_heartbeat_encoding.py | 66 + tests/fleet/test_network_profiles.py | 148 ++ tests/fleet/test_pairing.py | 98 ++ tests/fleet/test_rover_channel.py | 308 ++++ tests/fleet/test_rover_control.py | 161 +- tests/fleet/test_rover_datagram.py | 123 ++ tests/fleet/test_rover_datagram_binding.py | 179 +++ tests/fleet/test_rover_diagnostics.py | 154 ++ tests/fleet/test_rover_diagnostics_api.py | 71 + .../fleet/test_rover_diagnostics_stop_tail.py | 102 ++ tests/fleet/test_rover_export_transfer.py | 115 ++ tests/fleet/test_rover_local_collector.py | 123 ++ tests/fleet/test_rover_local_trace.py | 201 +++ tests/fleet/test_rover_metadata.py | 162 ++ .../fleet/test_rover_observation_evidence.py | 46 + tests/fleet/test_rover_python_interop.py | 112 ++ tests/fleet/test_rover_runtime_diagnostics.py | 39 + tests/fleet/test_rover_sample_age.py | 58 + tests/fleet/test_rover_socket.py | 166 ++ tests/fleet/test_rover_stop_evidence.py | 147 ++ tests/fleet/test_rover_stream_timing.py | 85 + tests/fleet/test_rover_stream_transport.py | 3 +- tests/fleet/test_runtime_http_timing.py | 80 + tests/fleet/test_sensor_transient.py | 68 + tests/qualification/link_budget_load_test.go | 262 ++++ tests/qualification/rover_connect_test.go | 141 ++ tests/qualification/rover_contention_test.go | 339 ++++ tests/qualification/rover_datagram_test.go | 217 +++ .../rover_python_interop_test.go | 134 ++ tests/qualification/rover_transport_test.go | 526 +++++++ 180 files changed, 20140 insertions(+), 400 deletions(-) create mode 100644 apps/control-station/src/components/rover/RoverDevWindow.tsx create mode 100644 apps/control-station/src/components/rover/RoverLogs.tsx create mode 100644 apps/control-station/src/components/rover/roverLogs.css create mode 100644 apps/control-station/src/core/fleet/observationSync.ts create mode 100644 apps/control-station/src/core/fleet/roverDevEvents.ts create mode 100644 apps/control-station/src/core/fleet/roverFaultNotice.ts create mode 100644 apps/control-station/src/core/fleet/roverLogSave.ts create mode 100644 apps/control-station/src/core/fleet/roverLogTransfer.ts create mode 100644 apps/control-station/src/core/fleet/roverObservation.ts create mode 100644 apps/control-station/src/core/fleet/roverOperatorCapture.ts create mode 100644 apps/control-station/src/core/fleet/roverRecovery.ts create mode 100644 apps/control-station/src/core/fleet/roverTiming.ts create mode 100644 apps/control-station/src/core/fleet/roverTransport.ts create mode 100644 apps/control-station/src/core/fleet/useBoardNetwork.ts create mode 100644 apps/control-station/src/core/fleet/useRoverDiagnostics.ts create mode 100644 apps/control-station/src/workspaces/fleet/BoardNetworkSettings.tsx create mode 100644 apps/control-station/test/liveTiming.test.mjs create mode 100644 apps/control-station/test/observationSync.test.mjs create mode 100644 apps/control-station/test/roverDevEvents.test.mjs create mode 100644 apps/control-station/test/roverFaultNotice.test.mjs create mode 100644 apps/control-station/test/roverLocalEvidence.test.mjs create mode 100644 apps/control-station/test/roverLogSave.test.mjs create mode 100644 apps/control-station/test/roverObservationLifecycle.test.mjs create mode 100644 apps/control-station/test/roverObservationStatus.test.mjs create mode 100644 apps/control-station/test/roverOperatorCapture.test.mjs create mode 100644 apps/control-station/test/roverRecovery.test.mjs create mode 100644 apps/control-station/test/roverRecoveryContinuity.test.mjs create mode 100644 apps/control-station/test/roverStopRecoveryBench.test.mjs create mode 100644 apps/control-station/test/roverTransport.test.mjs create mode 100644 apps/control-station/test/roverTransportStartup.test.mjs create mode 100644 apps/control-station/test/sensorTransportFreshness.test.mjs create mode 100644 apps/node-agent/internal/node/link_budget.go create mode 100644 apps/node-agent/internal/node/link_budget_test.go create mode 100644 apps/node-agent/internal/node/link_command_health.go create mode 100644 apps/node-agent/internal/node/link_command_health_test.go create mode 100644 apps/node-agent/internal/node/link_datagram_feedback.go create mode 100644 apps/node-agent/internal/node/link_datagram_feedback_test.go create mode 100644 apps/node-agent/internal/node/link_operator_view_test.go create mode 100644 apps/node-agent/internal/node/link_producers.go create mode 100644 apps/node-agent/internal/node/link_producers_test.go create mode 100644 apps/node-agent/internal/node/link_runtime.go create mode 100644 apps/node-agent/internal/node/link_runtime_test.go create mode 100644 apps/node-agent/internal/node/link_stop_recovery_test.go create mode 100644 apps/node-agent/internal/node/network_profile.go create mode 100644 apps/node-agent/internal/node/network_profile_test.go create mode 100644 apps/node-agent/internal/node/pairing_budget_test.go create mode 100644 apps/node-agent/internal/node/pairing_encoding_test.go create mode 100644 apps/node-agent/internal/node/pairing_liveness.go create mode 100644 apps/node-agent/internal/node/rover_control_activity.go create mode 100644 apps/node-agent/internal/node/rover_control_activity_test.go create mode 100644 apps/node-agent/internal/node/rover_datagram.go create mode 100644 apps/node-agent/internal/node/rover_datagram_codec.go create mode 100644 apps/node-agent/internal/node/rover_datagram_codec_test.go create mode 100644 apps/node-agent/internal/node/rover_datagram_continuity_test.go create mode 100644 apps/node-agent/internal/node/rover_dev.go create mode 100644 apps/node-agent/internal/node/rover_dev_test.go create mode 100644 apps/node-agent/internal/node/rover_diagnostics_lane.go create mode 100644 apps/node-agent/internal/node/rover_diagnostics_low_rate_test.go create mode 100644 apps/node-agent/internal/node/rover_error_kind_test.go create mode 100644 apps/node-agent/internal/node/rover_export_lane_test.go create mode 100644 apps/node-agent/internal/node/rover_http_trace.go create mode 100644 apps/node-agent/internal/node/rover_http_trace_test.go create mode 100644 apps/node-agent/internal/node/rover_link.go create mode 100644 apps/node-agent/internal/node/rover_link_test.go create mode 100644 apps/node-agent/internal/node/rover_local_delivery.go create mode 100644 apps/node-agent/internal/node/rover_local_delivery_test.go create mode 100644 apps/node-agent/internal/node/rover_metadata.go create mode 100644 apps/node-agent/internal/node/rover_metadata_test.go create mode 100644 apps/node-agent/internal/node/rover_stream_health.go create mode 100644 apps/node-agent/internal/node/rover_transport.go create mode 100644 apps/node-agent/internal/node/sensor_failure_result_test.go create mode 100644 apps/node-agent/internal/node/sensor_snapshots.go create mode 100644 apps/node-agent/internal/node/sensor_snapshots_test.go create mode 100644 apps/node-agent/internal/node/sensor_telemetry.go create mode 100644 apps/node-agent/internal/node/sensor_telemetry_test.go create mode 100644 apps/node-agent/internal/node/sensor_vesc_packages.go create mode 100644 apps/node-agent/internal/node/sensor_vesc_packages_test.go create mode 100644 apps/node-agent/internal/node/sensor_vesc_transport.go create mode 100644 apps/node-agent/internal/node/testdata/command-jitter-redacted.json create mode 100644 apps/wireguard-client/build_macos.py create mode 100644 apps/wireguard-client/helper.py create mode 100644 apps/wireguard-client/install_macos.py create mode 100644 apps/wireguard-client/test_helper.py create mode 100644 docs/audits/2026-10-26-network-runtime-and-dev.md create mode 100644 docs/node/38_SHARED_LINK_BUDGET.md create mode 100644 docs/node/39_NETWORK_RUNTIME_AB.md create mode 100644 docs/node/40_WIREGUARD_FLEET_NETWORK.md create mode 100644 scripts/qualification/capture_rover_local.py create mode 100644 scripts/qualification/package_link_budget.py create mode 100644 scripts/qualification/passive_runtime.py create mode 100644 src/k1link/fleet/channel_binding.py create mode 100644 src/k1link/fleet/heartbeat_encoding.py create mode 100644 src/k1link/fleet/network_client.py create mode 100644 src/k1link/fleet/network_media.py create mode 100644 src/k1link/fleet/network_profiles.py create mode 100644 src/k1link/fleet/rover_channel.py create mode 100644 src/k1link/fleet/rover_datagram.py create mode 100644 src/k1link/fleet/rover_diagnostics.py create mode 100644 src/k1link/fleet/rover_diagnostics_export.py create mode 100644 src/k1link/fleet/rover_local_trace.py create mode 100644 src/k1link/fleet/rover_metadata.py create mode 100644 src/k1link/fleet/rover_observation_evidence.py create mode 100644 src/k1link/fleet/rover_preview_evidence.py create mode 100644 src/k1link/fleet/rover_stop_evidence.py create mode 100644 src/k1link/fleet/rover_stream_timing.py create mode 100644 src/k1link/fleet/sensor_transient.py create mode 100644 src/k1link/web/fleet_network_api.py create mode 100644 src/k1link/web/rover_diagnostics_api.py create mode 100644 src/k1link/web/rover_runtime_diagnostics.py create mode 100644 src/k1link/web/rover_socket.py create mode 100644 src/k1link/web/runtime_http_timing.py create mode 100644 tests/fleet/test_heartbeat_encoding.py create mode 100644 tests/fleet/test_network_profiles.py create mode 100644 tests/fleet/test_rover_channel.py create mode 100644 tests/fleet/test_rover_datagram.py create mode 100644 tests/fleet/test_rover_datagram_binding.py create mode 100644 tests/fleet/test_rover_diagnostics.py create mode 100644 tests/fleet/test_rover_diagnostics_api.py create mode 100644 tests/fleet/test_rover_diagnostics_stop_tail.py create mode 100644 tests/fleet/test_rover_export_transfer.py create mode 100644 tests/fleet/test_rover_local_collector.py create mode 100644 tests/fleet/test_rover_local_trace.py create mode 100644 tests/fleet/test_rover_metadata.py create mode 100644 tests/fleet/test_rover_observation_evidence.py create mode 100644 tests/fleet/test_rover_python_interop.py create mode 100644 tests/fleet/test_rover_runtime_diagnostics.py create mode 100644 tests/fleet/test_rover_sample_age.py create mode 100644 tests/fleet/test_rover_socket.py create mode 100644 tests/fleet/test_rover_stop_evidence.py create mode 100644 tests/fleet/test_rover_stream_timing.py create mode 100644 tests/fleet/test_runtime_http_timing.py create mode 100644 tests/fleet/test_sensor_transient.py create mode 100644 tests/qualification/link_budget_load_test.go create mode 100644 tests/qualification/rover_connect_test.go create mode 100644 tests/qualification/rover_contention_test.go create mode 100644 tests/qualification/rover_datagram_test.go create mode 100644 tests/qualification/rover_python_interop_test.go create mode 100644 tests/qualification/rover_transport_test.go diff --git a/apps/control-station/src/components/rover/RoverDevWindow.tsx b/apps/control-station/src/components/rover/RoverDevWindow.tsx new file mode 100644 index 00000000..ad2ee771 --- /dev/null +++ b/apps/control-station/src/components/rover/RoverDevWindow.tsx @@ -0,0 +1,32 @@ +import {useState} from 'react'; +import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions} from '@nodedc/ui-react'; +import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics'; +import './roverLogs.css'; + +export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){ + const [options,setOptions]=useState({...localDevOptions}); + const [local,setLocal]=useState({enabled:true,preview:true}); + const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value})); + const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`})); + const begin=async()=>{if(await capture.toggle(options,local)){started();close();}}; + return }> +
+ Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись. + + set('motor_samples',value)}/> + set('network',value)}/> + + + setLocal(current=>({...current,enabled}))}/> + {local.enabled&&<>setLocal(current=>({...current,preview}))}/>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.} + + + set('live',value)}/> + {options.live&&set('core_kbps',Number(value))}/>} + + {!capture.state.options_supported&&Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.} +
+
; +} diff --git a/apps/control-station/src/components/rover/RoverLogs.tsx b/apps/control-station/src/components/rover/RoverLogs.tsx new file mode 100644 index 00000000..052121d3 --- /dev/null +++ b/apps/control-station/src/components/rover/RoverLogs.tsx @@ -0,0 +1,24 @@ +import {createPortal} from 'react-dom'; +import {Button,StatusBadge} from '@nodedc/ui-react'; +import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics'; +import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; +import './roverLogs.css'; +export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){ + const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error; + const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта'; + return <> + {createPortal(,header.statusTarget)} + +
+
{capture.state.local_capture?.id&&}
+

{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}

+ {storage?.file&&

{storage.file}

} + {failed&&

Файл может быть неполным: {failed}

} +

{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.

+ {capture.state.local_capture?.id&&

Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.

} +
+ {[...capture.rows].reverse().map(item=>{const row=item.record??item;return
{JSON.stringify(row,null,2)}
;})} +
+
+ ; +} diff --git a/apps/control-station/src/components/rover/RoverTelemetry.tsx b/apps/control-station/src/components/rover/RoverTelemetry.tsx index 482630d4..faf7c7c5 100644 --- a/apps/control-station/src/components/rover/RoverTelemetry.tsx +++ b/apps/control-station/src/components/rover/RoverTelemetry.tsx @@ -1,7 +1,9 @@ +import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react'; import type {RoverState} from '../../core/fleet/useRoverControl'; +import type {RoverObservationStatus} from '../../core/fleet/roverObservation'; import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model'; const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—'; -export function RoverTelemetry({state}:{state:RoverState}){ +export function roverTelemetryTable(state:RoverState){ const devices=state.snapshot.devices??[],profile=state.snapshot.profile; const positions=drivePositions(profile?.layout??null); const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({ @@ -9,17 +11,19 @@ export function RoverTelemetry({state}:{state:RoverState}){ reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid), })); const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))]; - return
- {!state.fresh?

Нет свежих показаний VESC.

:!readings.length?

Получение показаний VESC…

:readings.map(d=>{ - const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined; - return
{d.label}VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''} -
Ток мотора
{number(v?.motor_current_a)} А
-
Ток батареи
{number(v?.input_current_a)} А
-
Напряжение
{number(v?.input_voltage_v)} В
-
Обороты, ERPM
{number(v?.erpm,0)}
-
Контроллер
{number(v?.mos_temperature_c)} °C
-
Ошибка VESC
{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}
-
; - })} -
; + const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000; + const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const; + return { + columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})), + rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')}, + {id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')}, + ...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})), + {id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}], + }; } +export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){ + const table=roverTelemetryTable(state); + return
{observation?.label&&{observation.label}}{table.columns.length?:!observation?.label&&{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}}
; +} + +export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};} diff --git a/apps/control-station/src/components/rover/RoverView.tsx b/apps/control-station/src/components/rover/RoverView.tsx index fb557a65..58c23b2c 100644 --- a/apps/control-station/src/components/rover/RoverView.tsx +++ b/apps/control-station/src/components/rover/RoverView.tsx @@ -1,45 +1,63 @@ import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react'; import {createPortal} from 'react-dom'; -import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react'; -import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput'; +import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react'; +import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput'; +import {roverDevEvent} from '../../core/fleet/roverDevEvents'; import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput'; import type {RoverController} from '../../core/fleet/useRoverControl'; +import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation'; import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; import './rover.css'; const Scene=lazy(()=>import('./editor/RoverScene')); -const labels:Record={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'}; +const labels:Record={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'}; -export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){ +export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){ const storage=`missioncore.rover-view.v1:${vehicleID}`; const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}}); - const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState>(new Set()); + const [open,setOpen]=useState(false),[held,setHeld]=useState>(new Set()); const [editing,setEditing]=useState(false); const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading'); const stage=useRef(null),input=useRef|null>(null); - const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]); - useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]); + const focusAfterArm=useRef(false); + useEffect(()=>{ + if(open||!focusAfterArm.current)return; + focusAfterArm.current=false; + // Window restores its opener on close. Transfer input after that cleanup, + // once only, without taking focus back from another window or dialog. + const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});}); + return()=>cancelAnimationFrame(frame); + },[open,active]); + const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]); + useEffect(()=>{if(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]); useEffect(()=>{if(!active)stop();},[active,stop]); useEffect(()=>{ if(!c.ready||!active||open||editing||!stage.current)return; - const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop}); + const scope=stage.current.closest('.observation-center')??stage.current; + const binding=bindRoverHoldInput(scope,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop,trace:(event,data)=>roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,event,data)}); input.current=binding;c.setInputGuard(binding.valid); return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;}; },[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]); const showSettings=()=>{setEditing(false);stop();setOpen(true);}; - const preparing=c.pending||(c.armed&&!c.ready); - const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null; - const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral'; - const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение'); + const preparing=c.recovering||c.pending||(c.armed&&!c.ready); + const duty=c.controlMode!=='rpm'; + const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits); + const currentDescription=limits.length?limits.map(d=>`${d.label}: до ${d.current_limits!.motor_a.toLocaleString('ru-RU',{maximumFractionDigits:2})} А`).join('; ')+'. Выбранный предел ограничивает тягу; настройки VESC сохраняются.':'Предел тяги. Каждый мотор также ограничен своей конфигурацией VESC.'; + const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000; + const observing=observation??roverObservationStatus(c.state,c.connection); + const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null); + const tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral'; + const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение'); + const running=c.armed||c.pending||c.recovering; return <> - {createPortal(<>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}>,header.actionsTarget)} - {createPortal(,header.statusTarget)} + {createPortal(<>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}>,header.actionsTarget)} + {createPortal(<>

{editing?'Редактирование сцены':status}

,header.statusTarget)}
{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}} onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}> - {settings.model==='dcd006-v020'? + {settings.model==='dcd006-v020'? {modelState==='error'&&

Не удалось загрузить модель ровера.

}
:

Выберите модель аппарата.

} -
{editing?'Редактирование сцены':status}
{c.ready&&!editing&&
{keysFor(settings.mode).map(code=> {settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп
} - {!editing&&
- {c.armed||c.pending?:} -
}
setOpen(false)} title="Управление ровером" size="md">
setSettings(v=>({...v,model}))}/> - setSettings(v=>({...v,currentA:Number(e.target.value)}))}/> - setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/> - - {availability&&{availability}} -

Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.

- + {duty?setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>: + setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>} + setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/> + {(availability||c.error)&&{availability||c.error}} +

Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.

+
; diff --git a/apps/control-station/src/components/rover/editor/RoverScene.tsx b/apps/control-station/src/components/rover/editor/RoverScene.tsx index 74bf5a10..d100c6cb 100644 --- a/apps/control-station/src/components/rover/editor/RoverScene.tsx +++ b/apps/control-station/src/components/rover/editor/RoverScene.tsx @@ -20,7 +20,7 @@ export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:s {scene.ready&&}
{editing&&<> -
setPalette(v=>!v)}>setEnvironment(v=>!v)}>
+
setPalette(v=>!v)}>setEnvironment(v=>!v)}>
{status}
{palette&&
Материалы · выберите в палитре или на моделиsetPalette(false)}>
{Object.entries(scene.document.materials).map(([id,m])=>)}
} } diff --git a/apps/control-station/src/components/rover/rover.css b/apps/control-station/src/components/rover/rover.css index 49d72231..0e2197fa 100644 --- a/apps/control-station/src/components/rover/rover.css +++ b/apps/control-station/src/components/rover/rover.css @@ -2,19 +2,11 @@ .rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; } .rover-view .rover-view__scene { position:absolute; inset:0; } .rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); } -.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); } -.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; } +.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; } .rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); } .rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); } .rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; } .rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; } -.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); } -@container (max-width: 380px) { - .rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; } -} .rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); } .rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); } -.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); } -.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); } -.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); } -.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; } +.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;} diff --git a/apps/control-station/src/components/rover/roverLogs.css b/apps/control-station/src/components/rover/roverLogs.css new file mode 100644 index 00000000..bbac5fd1 --- /dev/null +++ b/apps/control-station/src/components/rover/roverLogs.css @@ -0,0 +1,10 @@ +.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);} +.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);} +.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;} +.rover-logs__entries {flex:1;min-height:0;overflow:auto;} +.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);} + +.rover-dev-options {display:flex;flex-direction:column;gap:var(--nodedc-space-3);} +.rover-dev-options .nodedc-settings-card__body {display:flex;flex-direction:column;gap:var(--nodedc-space-3);} + +.rover-logs__actions {display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);} diff --git a/apps/control-station/src/core/fleet/observationLayout.ts b/apps/control-station/src/core/fleet/observationLayout.ts index ba51e0a5..31f538d8 100644 --- a/apps/control-station/src/core/fleet/observationLayout.ts +++ b/apps/control-station/src/core/fleet/observationLayout.ts @@ -38,6 +38,10 @@ export function observationTree(layout:ObservationLayout,ids:string[]):DockTree| const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x'; return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!}; }; + if(layout.arrangement==='auto' && !Object.keys(layout.splits).length && ids.includes('telemetry') && ids.length>=3){ + const other=ids.filter(id=>id!=='telemetry'); + return {axis:'x',ratio:65,first:build(other.slice(0,-1))!,second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:other.at(-1)!}}}; + } return build(ids); } export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout { diff --git a/apps/control-station/src/core/fleet/observationSync.ts b/apps/control-station/src/core/fleet/observationSync.ts new file mode 100644 index 00000000..b60e2759 --- /dev/null +++ b/apps/control-station/src/core/fleet/observationSync.ts @@ -0,0 +1,48 @@ +import {sameConfiguration} from './configurationEquality'; + +const queues=new Map>(); +/** A pending save survives unmount. The next mount reads only after its ACK. */ +export function observationSerial(key:string,work:()=>Promise):Promise{ + const previous=queues.get(key)??Promise.resolve(); + const next=previous.catch(()=>{}).then(work);queues.set(key,next); + void next.finally(()=>{if(queues.get(key)===next)queues.delete(key);}).catch(()=>{}); + return next; +} +const object=(v:unknown):v is Record=>v!==null&&typeof v==='object'&&!Array.isArray(v); +/** Three-way merge: unrelated fields survive; arrays and conflicting leaves are atomic. */ +export function mergeObservation(base:T,local:T,remote:T):{value:T;conflicts:string[]}{ + const conflicts:string[]=[]; + function merge(b:unknown,l:unknown,r:unknown,path:string):unknown{ + if(sameConfiguration(l,b))return r; + if(sameConfiguration(r,b)||sameConfiguration(l,r))return l; + if(object(b)&&object(l)&&object(r)){ + const result:Record={}; + for(const key of new Set([...Object.keys(b),...Object.keys(l),...Object.keys(r)])){ + const value=merge(b[key],l[key],r[key],path?path+'.'+key:key); + if(value!==undefined)result[key]=value; + } + return result; + } + conflicts.push(path);return l; + } + return {value:merge(base,local,remote,'') as T,conflicts}; +} +export interface ObservationReceipt{revision:number;document:T|null;writable:boolean} +export async function saveObservation(revision:number,base:T,local:T,read:()=>Promise>,write:(revision:number,value:T)=>Promise>,normalize:(value:T|null)=>T){ + let payload=local; + for(let attempt=0;attempt<2;attempt++){ + try{return {receipt:await write(revision,payload),document:payload};} + catch(error){ + // Read after any failed ACK, including timeout. Identity/equality can prove + // an already committed write without retrying it or incrementing revision. + const latest=await read();if(!latest.writable)throw error; + const remote=normalize(latest.document); + if(sameConfiguration(remote,payload))return {receipt:latest,document:remote}; + const merged=mergeObservation(base,payload,remote); + if(merged.conflicts.length)throw Error('Раскладка изменена в другом окне. Черновик сохранён: можно загрузить бортовую версию или применить свой черновик.'); + if(attempt===1)throw error; + revision=latest.revision;base=remote;payload=merged.value; + } + } + throw Error('Подтверждение сохранения не получено.'); +} diff --git a/apps/control-station/src/core/fleet/roverDevEvents.ts b/apps/control-station/src/core/fleet/roverDevEvents.ts new file mode 100644 index 00000000..0a0a9f2d --- /dev/null +++ b/apps/control-station/src/core/fleet/roverDevEvents.ts @@ -0,0 +1,38 @@ +/** Opt-in bounded queues on the operator host. Never awaited by motor transport. */ +type Row=Record; +export class BrowserEvidence { + id:string|null=null;rows:Row[]=[];busy=false;dropped=0; + constructor(readonly url:string,readonly local=false){} + set(id:string|null){if(this.id!==id){this.rows=[];this.dropped=0;this.id=id;}} + record(event:string,data:Row={}){ + if(!this.id)return; + const row={event,browser_ms:performance.now(),...data}; + if(JSON.stringify(row).length>2048){this.dropped++;return;} + if(this.rows.length>=256){this.rows.shift();this.dropped++;} + this.rows.push(row); + } + async flush(){ + if(this.busy||!this.id||!this.rows.length)return; + const id=this.id,rows=this.rows.splice(0,32);this.busy=true; + try{const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'}, + body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(2000),keepalive:true}); + if(!r.ok)throw Error('trace'); + if(this.local&&(await r.json()).accepted!==true&&id===this.id)this.set(null); + } + catch{if(id===this.id){const pending=[...rows,...this.rows];this.dropped+=Math.max(0,pending.length-256);this.rows=pending.slice(-256);}} + finally{this.busy=false;} + } +} +const sessions=new Map(); +export function roverDevEvent(url:string,event:string,data:Row={}){try{const pair=sessions.get(url);pair?.remote.record(event,data);pair?.local.record(event,data);}catch{/* No change to input authority. */}} +/** Camera metrics never enter the optional WAN recorder. */ +export function roverPreviewEvidence(url:string,sample:Row){try{const pair=sessions.get(url);if(pair?.preview)pair.local.record('preview',{sample});}catch{/* No preview/control side effect. */}} +export function connectRoverEvidence(url:string){ + const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true};sessions.set(url,pair); + const timer=setInterval(()=>{for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush();}},250); + return {set(id:string|null,localID:string|null=null,preview=true){pair.preview=preview;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});}, + async flush(){for(const e of [pair.remote,pair.local])for(let n=0;n<9&&e.rows.length;n++){if(e.busy)await new Promise(r=>setTimeout(r,25));else await e.flush();}}, + close(){clearInterval(timer);for(const e of [pair.remote,pair.local])void e.flush();if(sessions.get(url)===pair)sessions.delete(url);}}; +} + +export function roverEvidenceForeground(){try{return typeof document!=='undefined'&&!document.hidden&&document.hasFocus();}catch{return false;}} diff --git a/apps/control-station/src/core/fleet/roverFaultNotice.ts b/apps/control-station/src/core/fleet/roverFaultNotice.ts new file mode 100644 index 00000000..003fe3e5 --- /dev/null +++ b/apps/control-station/src/core/fleet/roverFaultNotice.ts @@ -0,0 +1,18 @@ +import type {RoverState} from './useRoverControl'; + +/** Opening a view reads state; only a new failure produces an event toast. */ +export class RoverFaultNotice { + private baseline=false; + private key=''; + private message=''; + update(value:RoverState,ownedSession:string|null):{show?:string;clear?:string}{ + if(!value.fresh)return {}; + const s=value.snapshot,message=s.state==='fault'?s.message??'':''; + const key=message?JSON.stringify([s.instance,s.session_id,message]):''; + const changed=key!==this.key; + const show=changed&&message&&(this.baseline||!!ownedSession)?message:undefined; + const clear=changed&&this.message?this.message:undefined; + this.baseline=true;this.key=key;this.message=message; + return {show,clear}; + } +} diff --git a/apps/control-station/src/core/fleet/roverHoldInput.ts b/apps/control-station/src/core/fleet/roverHoldInput.ts index 7ebd75c5..d003d529 100644 --- a/apps/control-station/src/core/fleet/roverHoldInput.ts +++ b/apps/control-station/src/core/fleet/roverHoldInput.ts @@ -1,44 +1,53 @@ import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput'; -// The network heartbeat is not evidence that a physical key is still held. -// Allow the initial OS repeat delay, then require continuing keyboard evidence. -export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300; +// Key state is keydown/keyup, independent of OS autorepeat (which may +// stop for the remaining key after releasing the last key in a chord). +// Focus/visibility revoke input; Core and Node independently expire heartbeat. export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{ + trace?:(event:string,data:Record)=>void; held:(keys:Set)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void; -},now:()=>number=()=>performance.now()){ +}){ const doc=scope.ownerDocument,win=doc.defaultView!; const keyboard=new Set(),pointers=new Map(); - let deadline=0,closed=false,suspended=false; - const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());}; - const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();}; - const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();}; - const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement); + let closed=false,suspended=false; + const trace=(event:string,data:Record={})=>{try{callbacks.trace?.(event,{mode,held:[...keyboard,...pointers.values()],...data});}catch{}}; + const clear=()=>{keyboard.clear();pointers.clear();callbacks.held(new Set());}; + const pause=(reason:unknown="contextmenu")=>{if(closed||suspended)return;trace("pause",{reason:typeof reason==="string"?reason:"contextmenu"});suspended=true;clear();callbacks.pause();}; + const stop=()=>{if(closed)return;trace("stop",{reason:"operator_or_pagehide"});closed=true;clear();callbacks.stop();}; + // Armed authority belongs to the visible observation center, not one canvas. + // Modal focus returns to its header Play button; browser chrome can return it + // to body. Neither should require a canvas click before a NEW physical press. + const editable='input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role=dialog],[role=listbox],[role=menu]'; + const focused=()=>!doc.hidden&&doc.hasFocus() + &&(scope.contains(doc.activeElement)||doc.activeElement===doc.body) + &&!doc.activeElement?.closest(editable)&&!doc.querySelector('[role=dialog],[role=listbox],[role=menu]'); const valid=()=>{ if(closed)return false; - if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;} + if(!focused()){pause("focus_lost");return false;} return true; }; const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));}; const down=(e:KeyboardEvent)=>{ if(!e.isTrusted||closed)return; + if(keysFor(mode).includes(e.code)||e.code==='Space'||e.code==='Escape')trace('key_down',{code:e.code,repeat:e.repeat}); if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;} if(e.altKey||e.ctrlKey||e.metaKey){pause();return;} if(!keysFor(mode).includes(e.code)||!valid())return; - if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;} + if((e.target as HTMLElement)?.closest(editable)){pause();return;} // A repeat delivered after focus returns cannot become a fresh press. if(e.repeat&&!keyboard.has(e.code))return; e.preventDefault();suspended=false;keyboard.add(e.code); - deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish(); + publish(); }; const up=(e:KeyboardEvent)=>{ if(!e.isTrusted||closed||!keyboard.delete(e.code))return; - e.preventDefault();if(!keyboard.size)deadline=0;publish(); + trace("key_up",{code:e.code});e.preventDefault();publish(); }; - const blur=(e:Event)=>{if(e.target===win)pause();}; + const blur=(e:Event)=>{if(e.target===win)pause("window_blur");}; const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();}; const focusIn=()=>{if(!focused())pause();}; - const hidden=()=>{if(doc.hidden)pause();}; - const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();}; + const hidden=()=>{if(doc.hidden)pause("page_hidden");}; + const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause("outside_pointer");}; const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();}; const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();}; win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true); @@ -50,11 +59,11 @@ export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{ const timer=win.setInterval(valid,50); return { valid, - pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}}, + pointerDown(id:number,code:string){if(valid()){trace("pointer_down",{code});suspended=false;pointers.set(id,code);publish();}}, pointerUp(id:number){if(!closed&&pointers.delete(id))publish();}, - pointerCancel(id:number){if(pointers.has(id))pause();}, + pointerCancel(id:number){if(pointers.has(id)){trace("pointer_cancel");pause("pointer_cancel");}}, dispose(){ - closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer); + trace("lifecycle",{reason:"input_disposed"});closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer); win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true); win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop); doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true); diff --git a/apps/control-station/src/core/fleet/roverInput.ts b/apps/control-station/src/core/fleet/roverInput.ts index 547d1f3b..f07bdfc9 100644 --- a/apps/control-station/src/core/fleet/roverInput.ts +++ b/apps/control-station/src/core/fleet/roverInput.ts @@ -8,13 +8,25 @@ export function keyDemand(mode:RoverMode,held:ReadonlySet):Demand { const scale=Math.max(1,Math.abs(forward)+Math.abs(turn)); return {left:(forward+turn)/scale,right:(forward-turn)/scale}; } -export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''}; +export const defaultRoverSettings={version:3,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,throttlePercent:10,model:''}; export function roverSettings(value:unknown):typeof defaultRoverSettings { const v=value as Partial|null; - return {...defaultRoverSettings,...(v?.version===1?{ + return {...defaultRoverSettings,...(v?.version===1||v?.version===2||v?.version===3?{ mode:v.mode==='tank'?'tank':'arcade', - currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30, + // Legacy forms persisted an empty field as 0, then clamped it to .5. + // Repair that legacy floor once; v3 keeps an explicitly chosen .5 A. + currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)&&v.currentA>=.5&&!(v.version!==3&&v.currentA===.5)?v.currentA:30, maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000, + // ERPM has no trustworthy conversion to throttle. Migrate at 10%, never + // reinterpret an old saved number as a percentage or full throttle. + throttlePercent:v.version!==1&&typeof v.throttlePercent==='number'&&Number.isFinite(v.throttlePercent)?Math.max(1,Math.min(100,v.throttlePercent)):10, model:v.model==='dcd006-v020'?v.model:'', }:{} )}; } + +export const roverNumberInput=(value:string)=>value.trim()===''?Number.NaN:Number(value); +export function persistableRoverSettings(v:typeof defaultRoverSettings){ + return Number.isFinite(v.currentA)&&v.currentA>=.5 + &&Number.isFinite(v.throttlePercent)&&v.throttlePercent>=1&&v.throttlePercent<=100 + &&Number.isFinite(v.maxErpm)&&v.maxErpm>=300&&v.maxErpm<=3000; +} diff --git a/apps/control-station/src/core/fleet/roverLogSave.ts b/apps/control-station/src/core/fleet/roverLogSave.ts new file mode 100644 index 00000000..47e7e87b --- /dev/null +++ b/apps/control-station/src/core/fleet/roverLogSave.ts @@ -0,0 +1,16 @@ +/** Stream the complete onboard snapshot to the operator's chosen file. */ +import {transferRoverLog} from './roverLogTransfer'; +type SaveWindow=Window&{showSaveFilePicker?:(options:unknown)=>Promise}; +export async function saveRoverLog(url:string,name:string){ + const picker=(window as SaveWindow).showSaveFilePicker; + if(!picker){ + // Native download remains a streaming fallback; the browser owns its save UI. + const a=document.createElement('a');a.href=url+'/diagnostics/export';a.download=name;a.click();return; + } + const handle=await picker.call(window,{suggestedName:name,types:[{description:'Лог сессии JSONL',accept:{'application/x-ndjson':['.jsonl']}}]}); + const writable=await handle.createWritable(); + try{ + await transferRoverLog(url,data=>writable.write(data)); + await writable.close(); + }catch(error){await writable.abort().catch(()=>{});throw error;} +} diff --git a/apps/control-station/src/core/fleet/roverLogTransfer.ts b/apps/control-station/src/core/fleet/roverLogTransfer.ts new file mode 100644 index 00000000..535d930e --- /dev/null +++ b/apps/control-station/src/core/fleet/roverLogTransfer.ts @@ -0,0 +1,62 @@ +/** Bounded transfer of an immutable onboard snapshot over the existing HTTP API. */ +export type LogCursor={capture_id:string;total_bytes:number;snapshot:string;offset:number}; +const MAX_LINE=100*1024; +const failure=()=>new Error('Не удалось проверить файл с борта. Повторите сохранение.'); + +export async function readLogBlocks(response:Response,cursor:LogCursor|undefined,write:(data:Uint8Array)=>Promise,confirmed:(value:LogCursor)=>void){ + if(!response.body)throw failure(); + const reader=response.body.getReader(),decoder=new TextDecoder('utf-8',{fatal:true}); + let pending='',complete=false; + try{ + while(true){ + const {done,value}=await reader.read(); + if(done){if(pending||!complete)throw failure();return;} + // Split before decoding so even an unexpectedly large HTTP read cannot create + // an unbounded accumulated string. Only a single export block is retained. + for(let start=0;start=0){ + if(end>MAX_LINE||complete)throw failure(); + const row=JSON.parse(pending.slice(0,end));pending=pending.slice(end+1); + if(!/^[a-f0-9]{32}$/.test(row.capture_id)||!/^[a-f0-9]{64}$/.test(row.snapshot)||!/^[a-f0-9]{64}$/.test(row.sha256) + ||![row.offset,row.next,row.total_bytes].every(Number.isSafeInteger) + ||row.offset<0||row.nextrow.total_bytes + ||typeof row.data!=='string'||row.data.length>87384)throw failure(); + if(cursor?(row.capture_id!==cursor.capture_id||row.snapshot!==cursor.snapshot||row.total_bytes!==cursor.total_bytes||row.offset!==cursor.offset):row.offset!==0)throw failure(); + const raw=Uint8Array.from(atob(row.data),c=>c.charCodeAt(0)); + if(raw.length>65536||raw.length!==row.next-row.offset||(!raw.length&&row.next!==row.total_bytes))throw failure(); + const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',raw)),n=>n.toString(16).padStart(2,'0')).join(''); + if(digest!==row.sha256)throw failure(); + await write(raw); + cursor={capture_id:row.capture_id,total_bytes:row.total_bytes,snapshot:row.snapshot,offset:row.next}; + confirmed(cursor);complete=cursor.offset===cursor.total_bytes; + } + if(pending.length>MAX_LINE)throw failure(); + } + } + }finally{await reader.cancel().catch(()=>{});reader.releaseLock();} +} + +export async function transferRoverLog(url:string,write:(data:Uint8Array)=>Promise){ + let cursor:LogCursor|undefined; + for(let attempt=0;attempt<4;attempt++){ + const params=new URLSearchParams({format:'chunks'}); + if(cursor)for(const [key,value] of Object.entries(cursor))params.set(key,String(value)); + const controller=new AbortController(); + let timer:ReturnType; + const reset=()=>{clearTimeout(timer);timer=setTimeout(()=>controller.abort(),130000);}; + reset(); + try{ + const response=await fetch(url+'/diagnostics/export?'+params,{signal:controller.signal}); + if(!response.ok)throw new Error('Не удалось получить файл с борта. Проверьте связь и повторите сохранение.'); + await readLogBlocks(response,cursor,write,value=>{cursor=value;reset();}); + return; + }catch(error){ + if(attempt===3)throw error; + // No session-duration limit. Retry only a failed download, retaining the + // exact snapshot and the last verified, successfully written offset. + await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1))); + }finally{clearTimeout(timer!);controller.abort();} + } +} diff --git a/apps/control-station/src/core/fleet/roverObservation.ts b/apps/control-station/src/core/fleet/roverObservation.ts new file mode 100644 index 00000000..a6bb435b --- /dev/null +++ b/apps/control-station/src/core/fleet/roverObservation.ts @@ -0,0 +1,21 @@ +import type {RoverConnection} from './roverTransport'; +import type {RoverState} from './useRoverControl'; + +export interface RoverObservationStatus {label:string|null;pulse:boolean} +/** Presentation only. A fresh driver snapshot owns its attachment lifecycle; + * inventory and elapsed UI time cannot establish readiness or motor authority. */ +export function roverObservationStatus(state:RoverState,connection:RoverConnection):RoverObservationStatus{ + const pending=(label:string)=>({label,pulse:true}); + if(connection==='connecting')return pending('Подключение к Mission Core'); + if(connection!=='connected')return pending('Восстановление связи с Mission Core'); + if(!state.fresh)return pending('Ожидание телеметрии с борта'); + const snapshot=state.snapshot; + if(!snapshot.supported)return {label:'Служба управления на борту недоступна',pulse:false}; + if(snapshot.message||snapshot.state==='fault')return {label:null,pulse:false}; + const readings=snapshot.devices??[],expected=Object.values(snapshot.profile?.bindings??{}); + const missing=expected.filter(b=>!readings.some(d=>d.id===b.device_id&&d.uuid===b.uuid)); + const initializing=snapshot.observation?.initializing_devices??[]; + if(initializing.length&&(missing.length?missing.every(b=>initializing.includes(b.device_id)):!expected.length&&!readings.length))return pending('Инициализация VESC'); + if(missing.length||!readings.length||readings.some(d=>!Number.isFinite(d.age_ms)||d.age_ms<0||d.age_ms>=1000))return pending('Ожидание свежих показаний VESC'); + return {label:null,pulse:false}; +} diff --git a/apps/control-station/src/core/fleet/roverOperatorCapture.ts b/apps/control-station/src/core/fleet/roverOperatorCapture.ts new file mode 100644 index 00000000..4c60eca7 --- /dev/null +++ b/apps/control-station/src/core/fleet/roverOperatorCapture.ts @@ -0,0 +1,12 @@ +/** Bounded local diagnostic download. No request to the board or motion API. */ +export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise=async()=>{}){ + if(!/^[a-f0-9]{32}$/.test(id))throw Error('Запись изменилась.'); + await beforeSnapshot(); + const response=await fetch(url+'/diagnostics/local/export?capture_id='+id,{cache:'no-store',signal:AbortSignal.timeout(5000)}); + if(!response.ok)throw Error('Не удалось выгрузить замер компьютера. Запись сохранена в Core.'); + const blob=await response.blob();if(blob.size>4*1024*1024)throw Error('Размер замера превышает допустимый.'); + // The bounded snapshot uses the browser's normal download flow, including fullscreen. + const href=URL.createObjectURL(blob),a=document.createElement('a'); + try{a.href=href;a.download=`rover-operator-${id}.jsonl`;document.body.append(a);a.click();} + finally{a.remove();setTimeout(()=>URL.revokeObjectURL(href),1000);} +} diff --git a/apps/control-station/src/core/fleet/roverRecovery.ts b/apps/control-station/src/core/fleet/roverRecovery.ts new file mode 100644 index 00000000..926184a6 --- /dev/null +++ b/apps/control-station/src/core/fleet/roverRecovery.ts @@ -0,0 +1,84 @@ +import type {RoverState} from './useRoverControl'; + +export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty'} +const MAX_RETRY_BACKOFF=3; +const STABLE_CONNECTION_MS=30000; +const MAX_READY_OBSERVATION_GAP_MS=1000; +const profileKey=(s:RoverState['snapshot'])=>JSON.stringify(s.profile??null); +const motorKey=(s:RoverState['snapshot'])=>(s.devices??[]).map(d=>d.uuid+'@'+(d.session_id??'')).sort().join(':'); + +// Reacquire a NEW neutral lease after transport loss. Never revive an expired +// lease or remember motion. Explicit Stop, hardware faults and RC takeover end +// the operator's request; navigation/reload never persists it. +export class RoverRecovery { + private request:{settings:RoverArmSettings;instance:string;profile:string;motors:string;previousSession:string|null|undefined}|null=null; + private pendingSession:string|null=null; + private quietSince:number|null=null; + private retryAt=0; + private attempts=0; + private readySince:number|null=null; + private lastReadyAt:number|null=null; + private retiredSession:string|null=null; + waiting=false; + remember(settings:RoverArmSettings,value:RoverState){ + this.clear(); + if(value.fresh&&value.snapshot.instance&&value.snapshot.devices?.length&&value.snapshot.devices.every(d=>d.session_id))this.request={settings:{...settings},instance:value.snapshot.instance,profile:profileKey(value.snapshot),motors:motorKey(value.snapshot),previousSession:value.snapshot.session_id}; + } + clear(){this.request=null;this.waiting=false;this.quietSince=null;this.attempts=0;this.retryAt=0;this.retiredSession=null;this.pendingSession=null;this.readySince=null;this.lastReadyAt=null;} + started(session:string){if(!this.waiting)this.pendingSession=session;} + previousStatus(value:RoverState,ownedSession:string|null){ + // An explicit new arm acknowledges the previous terminal session. Core may + // still expose that snapshot until the board receives the new neutral lease. + return !!this.request&&!!ownedSession&&ownedSession===this.pendingSession&&!this.waiting + &&value.fresh&&value.controlling&&value.snapshot.session_id===this.request.previousSession + &&value.snapshot.session_id!==ownedSession&&['fault','stopped','receiver','observing'].includes(value.snapshot.state??''); + } + connected(now:number){ + this.waiting=false;this.quietSince=null;this.pendingSession=null; + // One ready snapshot is not a recovered link. Require continuous fresh + // observations before forgiving repeated automatic rearm attempts. + if(this.lastReadyAt===null||nowMAX_READY_OBSERVATION_GAP_MS)this.readySince=now; + this.lastReadyAt=now;this.readySince??=now; + if(now-this.readySince>=STABLE_CONNECTION_MS){this.attempts=0;this.retryAt=0;} + } + interrupt(now:number,session:string|null){ + if(!this.request)return false; + this.readySince=null;this.lastReadyAt=null; + if(!this.waiting){this.retryAt=Math.max(this.retryAt,now+500);this.quietSince=null;} + this.retiredSession=session??this.retiredSession;this.waiting=true;this.pendingSession=null;return true; + } + blocker(value:RoverState,ownedSession:string|null=null){ + if(!this.request||!value.fresh)return null; + const s=value.snapshot; + if(s.instance!==this.request.instance)return 'Борт перезапустился. Проверьте состояние и включите управление.'; + if(motorKey(s)!==this.request.motors)return 'Подключение VESC изменилось. Проверьте состояние и включите управление.'; + if(profileKey(s)!==this.request.profile)return 'Назначение моторов изменилось. Проверьте настройки управления.'; + if(s.supported!==true||(this.request.settings.mode==='duty'&&!s.control_modes?.includes('duty')))return 'Режим управления на борту изменился.'; + if(s.session_id===ownedSession)this.pendingSession=null; + if(this.previousStatus(value,ownedSession))return null; + const ended=s.last_stop; + if(ended?.state==='fault'&&(ended.session_id===ownedSession||ended.session_id===this.retiredSession))return ended.message||'Предыдущий сеанс завершился с ошибкой. Включите управление заново.'; + // Stopping is an interlock, not a terminal cancellation. The board may need + // fresh passive samples to verify release. next() still requires confirmed + // stopped state; a hardware fault (including historical fault) still blocks. + if(s.state==='fault'||(s.release_confirmed===false&&s.state!=='stopping'))return s.message||'Борт сообщил об ошибке. Проверьте состояние перед включением.'; + if(s.state==='receiver')return 'Управление передано пульту.'; + if(this.waiting&&value.controlling&&s.session_id&&s.session_id!==this.retiredSession&&s.session_id!==ownedSession)return 'Управление включено в другом окне.'; + return null; + } + next(value:RoverState,now:number,focused:boolean):RoverArmSettings|null{ + if(!this.waiting||!this.request)return null; + if(this.blocker(value)){this.clear();return null;} + const s=value.snapshot,devices=s.devices??[]; + const quiet=value.fresh&&!value.controlling&&s.state==='stopped'&&s.release_confirmed===true + &&motorKey(s)===this.request.motors&&devices.length>0&&devices.every(d=>Number.isFinite(d.age_ms)&&d.age_ms>=0&&d.age_ms<=500 + &&Number.isFinite(d.values.erpm)&&Math.abs(d.values.erpm)<60&&d.values.fault_code===0); + if(!focused||!quiet){this.quietSince=null;return null;} + this.quietSince??=now; + if(now-this.quietSince<500||now[]=[]; + private started=performance.now(); + private tickGap=0; + private requestMS=0; + private samples=0; + private staleSamples=0; + private hadFresh=false; + view(fresh:boolean){this.samples++;if(fresh)this.hadFresh=true;else if(this.hadFresh)this.staleSamples++;this.publish();} + private event(value:Record){ + this.events.push({at_ms:Math.round(performance.now()-this.started),...value});this.events=this.events.slice(-16); + } + tick(active:boolean){ + const now=performance.now();this.tickGap=this.lastTick===null?0:Math.round(now-this.lastTick);this.lastTick=now; + if(this.tickGap>=200)this.event({kind:'heartbeat-gap',gap_ms:this.tickGap,active,hidden:document.hidden,focused:document.hasFocus()}); + this.publish(); + } + request(kind:'view'|'arm'|'command',started:number,outcome:'ok'|'http'|'transport',url?:string){ + this.requestMS=Math.round(performance.now()-started); + let network:Record={}; + try{if(url&&typeof performance.getEntriesByName==='function'){ + const entry=performance.getEntriesByName(new URL(url,window.location.href).href,'resource').at(-1) as PerformanceResourceTiming|undefined; + if(entry&&entry.startTime>=started-1&&entry.requestStart>0)network={browser_wait_ms:Math.round(entry.requestStart-entry.fetchStart),response_wait_ms:Math.round(entry.responseStart-entry.requestStart),body_ms:Math.round(entry.responseEnd-entry.responseStart)}; + }}catch{/* Diagnostics cannot interfere with a command. */} + if(this.requestMS>=200||outcome!=='ok')this.event({kind,outcome,duration_ms:this.requestMS,hidden:document.hidden,focused:document.hasFocus(),...network}); + this.publish(); + } + private publish(){ + // One replaceable DOM diagnostic record; no telemetry archive or product control. + if(document.documentElement)document.documentElement.dataset.roverTiming=JSON.stringify({sampled_at_ms:Math.round(performance.now()),tick_gap_ms:this.tickGap,request_ms:this.requestMS,state_samples:this.samples,stale_after_fresh:this.staleSamples,events:this.events}); + } + clear(){this.lastTick=null;this.events=[];this.samples=0;this.staleSamples=0;this.hadFresh=false;this.started=performance.now();if(document.documentElement)delete document.documentElement.dataset.roverTiming;} +} +export const roverTiming=new RoverTiming(); diff --git a/apps/control-station/src/core/fleet/roverTransport.ts b/apps/control-station/src/core/fleet/roverTransport.ts new file mode 100644 index 00000000..e4038986 --- /dev/null +++ b/apps/control-station/src/core/fleet/roverTransport.ts @@ -0,0 +1,107 @@ +import {roverDevEvent,roverEvidenceForeground} from './roverDevEvents'; +/** Separate socket from HTTP asset/SSE queues. No queued or replayed commands. */ +export class RoverHttpError extends Error {constructor(message:string,readonly status:number){super(message);}} +export type RoverConnection='connecting'|'connected'|'reconnecting'|'closed'; +type Pending={resolve:(value:any)=>void;reject:(reason:Error)=>void;timer:ReturnType}; +export class RoverTransport { + private socket:WebSocket|null=null; + private latest:unknown; + private seen=-Infinity; + private clock=0; + private clockAt=0; + private next=0; + private socketID=''; + private lastSent:number|null=null; + private pending=new Map(); + private waiting=new Set(); + private retry:ReturnType|undefined; + private closed=false; + private watchdog:ReturnType|undefined; + private failures=0; + private received=false; + connection():RoverConnection{return this.closed?'closed':performance.now()-this.seen<600?'connected':this.received||this.failures>0?'reconnecting':'connecting';} + private touch(socket:WebSocket){ + clearTimeout(this.watchdog); + this.watchdog=setTimeout(()=>this.disconnect(socket,"watchdog"),1500); + } + private disconnect(socket:WebSocket,reason:string){ + if(this.socket!==socket)return; + roverDevEvent(this.url,"transport",{reason,ready_state:socket.readyState,buffered_bytes:socket.bufferedAmount,pending:this.pending.size}); + this.socket=null;this.seen=-Infinity;clearTimeout(this.watchdog);this.fail(); + // Retire locally even when the browser never emits a close event. + socket.onopen=socket.onmessage=socket.onclose=socket.onerror=null;socket.close(); + if(!this.closed)this.retry=setTimeout(()=>this.connect(),Math.min(250*2**Math.min(this.failures++,4),4000)); + } + constructor(private url:string,private create:(url:string)=>WebSocket=url=>new WebSocket(url)){this.connect();} + private connect(){ + if(this.closed)return; + const url=new URL(this.url+'-channel',window.location.href);url.protocol=url.protocol==='https:'?'wss:':'ws:'; + const socket=this.create(url.href);this.socket=socket;this.socketID='';this.lastSent=null; + // A browser handshake owns no motion authority. Do not repeatedly cancel a + // cold connection with the live-state deadline before it can open. Once open, + // the original watchdog and all sample/command deadlines still apply. + clearTimeout(this.watchdog); + this.watchdog=setTimeout(()=>this.disconnect(socket,'connect_timeout'),10000); + socket.onopen=()=>{if(this.socket===socket)this.touch(socket);}; + if(socket.readyState===1)this.touch(socket); + socket.onmessage=event=>{ + if(this.socket!==socket)return; + try{const value=JSON.parse(event.data); + if(typeof value.socket_id==='string')this.socketID=value.socket_id; + if(value.type==='reply')roverDevEvent(this.url,'transport',{reason:'reply_received',request_id:value.id,socket_id:this.socketID,clock_ms:value.clock_ms,outcome:String(value.status??200)}); + if(value.type==='state'&&Number.isFinite(value.clock_ms)){ + this.received=true;this.latest=value.value;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket); + for(const p of this.waiting){clearTimeout(p.timer);p.resolve(this.latest);}this.waiting.clear(); + }else if(value.type==='reply'){ + const p=this.pending.get(value.id);if(!p)return;this.pending.delete(value.id);clearTimeout(p.timer); + if(value.state&&Number.isFinite(value.clock_ms)){ + this.latest=value.state;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket); + for(const waiter of this.waiting){clearTimeout(waiter.timer);waiter.resolve(this.latest);}this.waiting.clear(); + } + if(value.error)roverDevEvent(this.url,'transport',{reason:'reply_rejected',outcome:String(value.status??409)}); + if(value.error)p.reject(new RoverHttpError(value.error,value.status??409));else p.resolve(value.value); + } + }catch{/* Invalid frames never acknowledge a request. */} + }; + socket.onclose=event=>{roverDevEvent(this.url,"transport",{reason:"close",close_code:event?.code});this.disconnect(socket,"close");}; + socket.onerror=()=>this.disconnect(socket,"error"); + } + private fail(){ + for(const p of [...this.pending.values(),...this.waiting]){clearTimeout(p.timer);p.reject(new Error('Канал управления недоступен.'));} + this.pending.clear();this.waiting.clear(); + } + view():Promise{ + if(this.closed)return Promise.reject(new Error('Канал управления недоступен.')); + if(performance.now()-this.seen<600)return Promise.resolve(this.latest); + return new Promise((resolve,reject)=>{const p:Pending={resolve,reject,timer:setTimeout(()=>{this.waiting.delete(p);reject(new Error('Нет свежих данных с борта.'));},1000)};this.waiting.add(p);}); + } + command(action:'arm'|'command'|'hold',body:unknown):Promise{ + const socket=this.socket,now=performance.now(); + if(!socket||socket.readyState!==1||socket.bufferedAmount>4096||now-this.seen>=600||this.pending.size>=4)return Promise.reject(new Error('Канал управления недоступен.')); + const id=++this.next; + return new Promise((resolve,reject)=>{ + this.pending.set(id,{resolve,reject,timer:setTimeout(()=>{this.pending.delete(id);roverDevEvent(this.url,'transport',{reason:'ack_timeout',action,request_id:id,socket_id:this.socketID});reject(new Error('Команда не подтверждена.'));},350)}); + try{ + const expires=this.clock+(now-this.clockAt)+400; + const fields=body&&typeof body==='object'?body as Record:{}; + roverDevEvent(this.url,'request',{reason:'socket_send',request_id:id,socket_id:this.socketID,action, + session_id:fields.session_id,sequence:fields.sequence,expires_ms:expires,state_age_ms:now-this.seen, + gap_ms:this.lastSent===null?0:now-this.lastSent,foreground:roverEvidenceForeground()}); + socket.send(JSON.stringify({id,action,body,expires_ms:expires}));this.lastSent=now; + } + catch{const p=this.pending.get(id);if(p){clearTimeout(p.timer);this.pending.delete(id);}reject(new Error('Канал управления недоступен.'));} + }); + } + close(){this.closed=true;clearTimeout(this.retry);clearTimeout(this.watchdog);const socket=this.socket;this.socket=null;this.seen=-Infinity;this.fail();socket?.close();} +} +const clients=new Map(); +export function retainRoverTransport(url:string){ + let entry=clients.get(url);if(!entry){entry={transport:new RoverTransport(url),users:0};clients.set(url,entry);}entry.users++; + return()=>{if(--entry!.users===0){entry!.transport.close();clients.delete(url);}}; +} +export function roverRequest(url:string,body?:unknown):Promise{ + const action=url.endsWith('/arm')?'arm':url.endsWith('/hold')?'hold':'command',base=body?url.slice(0,url.lastIndexOf('/')):url,client=clients.get(base); + if(!client)return Promise.reject(new Error('Канал управления недоступен.')); + return (body?client.transport.command(action,body):client.transport.view()) as Promise; +} +export function roverConnection(url:string):RoverConnection{return clients.get(url)?.transport.connection()??'closed';} diff --git a/apps/control-station/src/core/fleet/sensorTransport.ts b/apps/control-station/src/core/fleet/sensorTransport.ts index d557b979..62ac1580 100644 --- a/apps/control-station/src/core/fleet/sensorTransport.ts +++ b/apps/control-station/src/core/fleet/sensorTransport.ts @@ -1,17 +1,23 @@ -import type {SensorInventory, SensorTransport} from '../../../../../packages/sensor-ui/src/contracts'; +import type {SensorInventory, SensorTransport, SensorLiveFrame} from '../../../../../packages/sensor-ui/src/contracts'; import {fleetRequest} from './useFleet'; +import {roverPreviewEvidence} from './roverDevEvents'; export function createFleetSensorTransport(vehicleID:string):SensorTransport { const path=`/${encodeURIComponent(vehicleID)}/devices`; - const inventory=(fleet:{items:{id:string;connectivity:string;enrollment:string;sensor_state:SensorInventory}[]})=>{ + const inventory=(fleet:{items:{id:string;core_endpoint?:string;connectivity:string;enrollment:string;inventory_fresh?:boolean;sensor_state:SensorInventory}[]})=>{ const value=fleet.items.find(v=>v.id===vehicleID); if(!value)throw new Error('Аппарат не найден.'); - return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'}; + return {...value.sensor_state,items:value.sensor_state.items.map(item=>({...item,transport_generation:value.core_endpoint})),fresh:value.connectivity==='online'&&value.enrollment==='paired'&&value.inventory_fresh!==false}; }; return { + previewEvidence:sample=>roverPreviewEvidence(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,sample), + liveTelemetry:async signal=>{ + const value=await fleetRequest<{fresh:boolean;snapshot:Omit}>(`/${encodeURIComponent(vehicleID)}/rover`,'GET',undefined,1200,signal); + return {...value.snapshot,fresh:value.fresh}; + }, configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)}, enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)}, - inventory:async()=>inventory(await fleetRequest()), + inventory:async signal=>inventory(await fleetRequest('','GET',undefined,12000,signal)), subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();}, submit:value=>fleetRequest(`${path}/operations`,'POST',value), operation:id=>fleetRequest(`${path}/operations/${encodeURIComponent(id)}`), diff --git a/apps/control-station/src/core/fleet/useBoardNetwork.ts b/apps/control-station/src/core/fleet/useBoardNetwork.ts new file mode 100644 index 00000000..aeb3cbf2 --- /dev/null +++ b/apps/control-station/src/core/fleet/useBoardNetwork.ts @@ -0,0 +1,35 @@ +import {useCallback,useEffect,useRef,useState} from 'react'; +import {fleetRequest} from './useFleet'; +export type NetworkProvider='tailscale'|'wireguard'; +export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number} +export interface BoardNetworkView { + profiles:SharedNetworkProfile[];available:boolean; + node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null; + operation:{id:string;state:string;error?:string}|null; +} +export function useBoardNetwork(vehicleId:string){ + const [value,setValue]=useState(null),[provider,setProvider]=useState('tailscale'),[profileId,setProfileId]=useState(''); + const [error,setError]=useState(''),[busy,setBusy]=useState(false); + const revision=useRef(null); + const accept=useCallback((next:BoardNetworkView)=>{ + setValue(next); + if(next.node&&revision.current!==next.node.revision){revision.current=next.node.revision;setProvider(next.node.provider);setProfileId(next.node.server_id||'');} + },[]); + const refresh=useCallback(async()=>{const next=await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`);accept(next);return next;},[vehicleId,accept]); + useEffect(()=>{let active=true;let timer:ReturnType;const controller=new AbortController(); + const poll=async()=>{try{const next=await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'GET',undefined,12000,controller.signal);if(active)accept(next);}catch(e){if(active){setError(e instanceof Error?e.message:'Состояние подключения недоступно.');setValue(current=>current?{...current,available:false}:null);}}finally{if(active)timer=setTimeout(poll,2000);}}; + revision.current=null;void poll();return()=>{active=false;controller.abort();clearTimeout(timer);}; + },[vehicleId,accept]); + const importing=async(file:File)=>{if(busy)return;setBusy(true);setError('');try{ + if(file.size>16384)throw Error('Выберите файл подключения, созданный установщиком VPS.'); + const item=await fleetRequest('/network-profiles/import','POST',{document:await file.text()},240000); + await refresh();setProvider('wireguard');setProfileId(item.id); + }catch(e){setError(e instanceof Error?e.message:'Файл не удалось импортировать.');}finally{setBusy(false);}}; + const applying=value?.operation?.state==='applying'||value?.operation?.state==='rolling_back'; + const dirty=Boolean(value?.node&&(provider!==value.node.provider||(provider==='wireguard'&&profileId!==value.node.server_id))); + const save=async()=>{if(!value?.node||busy||applying)return;setBusy(true);setError('');try{ + await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh(); + }catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}}; + return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save, + canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))}; +} diff --git a/apps/control-station/src/core/fleet/useFleet.ts b/apps/control-station/src/core/fleet/useFleet.ts index 6fc2d9fa..ed5e3305 100644 --- a/apps/control-station/src/core/fleet/useFleet.ts +++ b/apps/control-station/src/core/fleet/useFleet.ts @@ -16,11 +16,11 @@ export interface FleetPreview { preview_id: string; node_id: string; name: string; host: BoardHost; endpoint: string; expires_at: number; } -export async function fleetRequest(path = "", method = "GET", body?: unknown, timeoutMs = 12000): Promise { +export async function fleetRequest(path = "", method = "GET", body?: unknown, timeoutMs = 12000, signal?:AbortSignal): Promise { const response = await fetch(`/api/v1/fleet${path}`, { method, credentials: "same-origin", cache: "no-store", headers: body === undefined ? {} : { "Content-Type": "application/json" }, - body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), + body: body === undefined ? undefined : JSON.stringify(body), signal: signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs), }); if (!response.ok) { const data = await response.json().catch(() => ({})); diff --git a/apps/control-station/src/core/fleet/useRoverControl.ts b/apps/control-station/src/core/fleet/useRoverControl.ts index a8a8ad19..3dd70854 100644 --- a/apps/control-station/src/core/fleet/useRoverControl.ts +++ b/apps/control-station/src/core/fleet/useRoverControl.ts @@ -1,79 +1,139 @@ +import {roverDevEvent} from './roverDevEvents'; import {useCallback,useEffect,useRef,useState} from 'react'; import type {Demand} from './roverInput'; +import {RoverRecovery,type RoverArmSettings} from './roverRecovery'; +import {RoverFaultNotice} from './roverFaultNotice'; +import {roverTiming} from './roverTiming'; +import {retainRoverTransport,roverRequest,roverConnection,RoverHttpError,type RoverConnection} from './roverTransport'; export interface RoverReading { - id:string;uuid:string;slot:string|null;label:string;age_ms:number; + id:string;uuid:string;session_id?:string;slot:string|null;label:string;age_ms:number; + current_limits?:{motor_a:number;brake_a:number}|null; values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number}; } export interface RoverState { fresh:boolean;controlling:boolean; - snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[]; + snapshot:{supported?:boolean;control_modes?:string[];instance?:string;state?:string;session_id?:string|null;message?:string|null;release_confirmed?:boolean|null;devices?:RoverReading[]; + observation?:{initializing_devices:string[]}; + last_stop?:{session_id:string;state:string;message:string|null;recovered_at?:string}; profile?:{layout:null|'1x1'|'2x2';bindings:Record}}; } +// Generate fresh intent at the command channel cadence. Keepalive frames do +// not renew the original 400 ms deadline; duplicating a 100 ms-old sample +// wastes half of the 50 ms carrier opportunities during a network burst. +const INTENT_INTERVAL_MS=50; const empty:RoverState={fresh:false,controlling:false,snapshot:{}}; -async function request(url:string,body?:unknown,keepalive=false):Promise{ - const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined, - body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive}); - const result=await response.json(); - if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.'); +const retryable=(e:unknown)=>!(e instanceof RoverHttpError)||e.status>=500||[408,429].includes(e.status)||['Управление завершено. Включите его заново.','Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.'].includes(e.message); +async function request(url:string,body?:unknown,_keepalive=false):Promise{ + const started=performance.now(),kind=url.endsWith('/arm')?'arm':body?'command':'view';let outcome:'ok'|'http'|'transport'='transport'; + try{ + const result=await roverRequest(url,body); + outcome='ok'; return result; + }catch(e){if(e instanceof RoverHttpError)outcome='http';throw e;}finally{roverTiming.request(kind,started,outcome);if(body)roverDevEvent(url.slice(0,url.lastIndexOf('/')),'request',{action:kind,outcome,elapsed_ms:performance.now()-started});} } export function useRoverControl(vehicleID:string,visible:boolean){ const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`; const [state,setState]=useState(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState(null); - const [connecting,setConnecting]=useState(true),armPending=useRef(false); - const session=useRef(null),seq=useRef(0),demand=useRef({left:0,right:0}),sending=useRef(false),generation=useRef(0); + const [connection,setConnection]=useState('connecting'),armPending=useRef(false); + const [recovering,setRecovering]=useState(false),recovery=useRef(new RoverRecovery()),latest=useRef(empty); + const [controlMode,setControlMode]=useState<'unknown'|'rpm'|'duty'>('unknown'); + const session=useRef(null),seq=useRef(0),demand=useRef({left:0,right:0}),sending=useRef(new Set()),acknowledged=useRef(0),generation=useRef(0); + const holding=useRef(null); const inputGuard=useRef<(()=>boolean)|null>(null); const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]); - const stop=useCallback(()=>{ - generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false); + const retire=useCallback(()=>{ + holding.current=null;generation.current++;armPending.current=false;const id=session.current;session.current=null;sending.current.clear();inputGuard.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false); if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{}); },[url]); + const stop=useCallback(()=>{recovery.current.clear();setRecovering(false);retire();},[retire]); + const interrupt=useCallback((reason:string)=>{ + roverDevEvent(url,"lifecycle",{reason,action:"interrupt",session_id:session.current}); + const resume=recovery.current.interrupt(performance.now(),session.current);retire();setRecovering(resume);setError(resume?null:reason); + },[retire]); const send=useCallback(async()=>{ + roverTiming.tick(session.current!==null); const id=session.current;if(!id)return; // Check on every heartbeat, even when a previous request is still pending. - const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.(); - if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0}; - if(sending.current)return; - sending.current=true; - try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});} - catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}} - finally{sending.current=false;} - },[url,stop]); - const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]); + const foreground=!document.hidden&&document.hasFocus(); + const inputValid=inputGuard.current?.()??false; + roverDevEvent(url,"heartbeat",{session_id:id,sequence:seq.current,foreground,input_valid:inputValid,pending:sending.current.size,...demand.current}); + if(!foreground||!inputValid)demand.current={left:0,right:0}; + // A hidden renderer cannot provide a reliable heartbeat. Hand only neutral + // readiness to the native Core owner socket; it can never renew movement. + if(!foreground&&holding.current===id)return; + // A delayed HTTP acknowledgement must not delay the next fresh intent. + // Bound concurrent requests; keep no queue and never renew remembered input. + if(sending.current.size>=4)return; + const sequence=++seq.current,key=`${id}:${sequence}`;sending.current.add(key); + const hold=!foreground;holding.current=hold?id:null; + try{await request(url+(hold?'/hold':'/command'),hold?{session_id:id,sequence}:{session_id:id,sequence,...demand.current,stop:false}); + if(session.current===id)acknowledged.current=Math.max(acknowledged.current,sequence); + }catch(e){if(session.current===id&&sequence>acknowledged.current&&sequence===seq.current){const reason=e instanceof Error?e.message:'Команда не подтверждена.'; + if(hold&&retryable(e)){holding.current=null;return;} // A delayed JS ack is not a lost board; poll verifies the lease. + if(retryable(e))interrupt(reason);else{stop();setError(reason);}}} + finally{sending.current.delete(key);} + },[url,stop,interrupt]); + const setDemand=useCallback((next:Demand)=>{roverDevEvent(url,"demand",next);demand.current=next;void send();},[send]); const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]); - const arm=useCallback(async(currentA:number,maxErpm:number)=>{ - if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true); + const start=useCallback(async({currentA,speed,mode}:RoverArmSettings)=>{ + if(document.hidden||!document.hasFocus()||session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true); try{ - const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm}); + const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})}); if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;} // Retire every read started before this acknowledgement, including reads // begun while POST /arm was pending. They describe the previous authority. generation.current++;armPending.current=false;setPending(false); - seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send(); + seq.current=0;acknowledged.current=0;demand.current={left:0,right:0};session.current=result.session_id;recovery.current.started(result.session_id);setArmed(true);void send(); return true; - }catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;} + }catch(e){if(g===generation.current){const reason=e instanceof Error?e.message:'Не удалось включить управление.'; + if(retryable(e)){interrupt(reason);return recovery.current.waiting;}stop();setError(reason); + }return false;} finally{if(g===generation.current){armPending.current=false;setPending(false);}} - },[url,send]); + },[url,send,interrupt,stop]); + const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm')=>{ + if(session.current||armPending.current||recovery.current.waiting)return Promise.resolve(false); + const settings={currentA,speed,mode};recovery.current.remember(settings,latest.current);return start(settings); + },[start]); useEffect(()=>{ - if(!visible){stop();setState(empty);setConnecting(false);return;} - let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true); + if(!visible){stop();setState(empty);setError(null);setConnection('closed');return;} + const releaseTransport=retainRoverTransport(url); + let alive=true,busy=false;const notices=new RoverFaultNotice();setError(null);setConnection(roverConnection(url));setControlMode('unknown'); + const recover=(value:RoverState,focused:boolean)=>{ + if(session.current||armPending.current)return; + const settings=recovery.current.next(value,performance.now(),focused); + if(settings)void start(settings); + }; const poll=async()=>{ if(busy)return;busy=true;const before=generation.current; - try{const value=await request(url);if(alive&&before===generation.current){setState(value); - setConnecting(!value.fresh&&performance.now()-started<2000); - if(session.current&&(!value.fresh||!value.controlling)){stop();} - const fault=value.snapshot.state==='fault'?value.snapshot.message??'':''; - if(fault&&lastFault!==fault){lastFault=fault;setError(fault);} - }}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;} + try{const value=await request(url);if(alive&&before===generation.current){roverTiming.view(value.fresh);setState(value);latest.current=value; + setConnection(roverConnection(url)); + // Telemetry absence is not a declaration of an old RPM-only driver. + if(value.fresh&&value.snapshot.supported)setControlMode(value.snapshot.control_modes?.includes('duty')?'duty':'rpm'); + const ownedSession=session.current; + const previousStatus=armPending.current||recovery.current.previousStatus(value,ownedSession); + const blocker=armPending.current?null:recovery.current.blocker(value,session.current); + if(blocker){stop();setError(blocker);} + else if(session.current&&(!value.fresh||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){ + const reason=value.snapshot.message||(!value.fresh?'Управление прервано: нет свежих данных с борта.':value.snapshot.state==='receiver'?'Управление передано пульту.':'Управление прервано: борт перестал подтверждать команды. Повторите включение.'); + interrupt(reason); + } + if(session.current&&value.fresh&&value.snapshot.session_id===session.current&&['ready','driving'].includes(value.snapshot.state??'')){ + recovery.current.connected(performance.now());setRecovering(false); + } + recover(value,!document.hidden&&document.hasFocus()); + if(!previousStatus){const notice=notices.update(value,ownedSession);if(notice.show)setError(notice.show);else if(notice.clear)setError(current=>current===notice.clear?null:current);} + }}catch{if(alive&&before===generation.current){setState(empty);latest.current=empty;setConnection(roverConnection(url));if(session.current)interrupt('Управление прервано: не удалось проверить связь с бортом.');recover(empty,false);}}finally{busy=false;} }; - void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100); - const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();}; - window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden); - return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();}; - },[url,visible,stop,send,pauseInput]); + void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),INTENT_INTERVAL_MS); + const blur=()=>pauseInput(); + const foreground=()=>{if(document.hidden||!document.hasFocus())return;void poll();void send();}; + const hidden=()=>{if(document.hidden)pauseInput();else foreground();}; + window.addEventListener('blur',blur);window.addEventListener('focus',foreground);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden); + return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('focus',foreground);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();releaseTransport();roverTiming.clear();}; + },[url,visible,stop,send,pauseInput,start,interrupt]); const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??''); - const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??''); - return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)}; + const canArm=!recovering&&state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??''); + return {state,armed,pending,error,connection,connecting:connection==='connecting',controlMode,recovering,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)}; } export type RoverController=ReturnType; diff --git a/apps/control-station/src/core/fleet/useRoverDiagnostics.ts b/apps/control-station/src/core/fleet/useRoverDiagnostics.ts new file mode 100644 index 00000000..c9e65cdf --- /dev/null +++ b/apps/control-station/src/core/fleet/useRoverDiagnostics.ts @@ -0,0 +1,61 @@ +import {useCallback,useEffect,useRef,useState} from 'react'; +import {connectRoverEvidence,roverDevEvent} from './roverDevEvents'; +import {saveRoverLog} from './roverLogSave'; +import {saveOperatorCapture} from './roverOperatorCapture'; +export type LocalCaptureOptions={enabled:boolean;preview:boolean}; +export type DevOptions={live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;live_kbps:number;core_kbps:number}; +export const localDevOptions:DevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16}; +export type DevRow={record_sequence:number;source:string;event:string;at_utc:string;record?:DevRow;[key:string]:unknown}; +export type DevState={local_capture?:{id:string|null;active:boolean;preview?:boolean;dropped?:number;sequence?:number};options?:DevOptions;options_supported?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[]; + node?:{active?:boolean;transport_error?:string;storage?:{file?:string;closed:boolean;written:number;dropped:number;error?:string}}}; +const empty:DevState={id:null,active:false,closing:false,sequence:0,frames:[]}; +export function useRoverDiagnostics(vehicleID:string){ + const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`; + const [state,setState]=useState(empty),[rows,setRows]=useState([]); + const [pending,setPending]=useState(false),[saving,setSaving]=useState(false),[error,setError]=useState(null); + const savedLocal=useRef(null); + const evidence=useRef|null>(null),latest=useRef(empty); + const accept=useCallback((value:DevState)=>{ + const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false); + const failure=value.node?.storage?.error; + if(failure&&(previous.id!==value.id||previous.node?.storage?.error!==failure)) + setError(failure==='CaptureInterrupted'?'DEV-запись прервана перезапуском борта. Сохранившийся файл оставлен на борту. Можно начать новую запись.':failure==='CaptureNotFound'?'Предыдущая DEV-запись на борту не найдена. Можно начать новую запись.':`Запись остановлена: ${failure}. Файл может быть неполным.`); + setRows(rows=>[...(previous.id===value.id?rows:[]),...value.frames.filter(r=>previous.id!==value.id||r.record_sequence>previous.sequence)].slice(-200)); + },[]); + useEffect(()=>{ + let alive=true,busy=false;latest.current=empty;setState(empty);setRows([]); + const client=connectRoverEvidence(url);evidence.current=client; + const poll=async()=>{if(busy)return;busy=true;const started=performance.now();try{ + const r=await fetch(url+'/diagnostics?after='+latest.current.sequence,{cache:'no-store',signal:AbortSignal.timeout(3000)}); + if(!r.ok)throw Error();const value:DevState=await r.json(); + if(performance.now()-started>=200)roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'slow',elapsed_ms:performance.now()-started});if(alive){accept(value);setError(current=>current==='Нет связи с Mission Core. Файл остаётся на борту.'?null:current);} + }catch{roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'transport',elapsed_ms:performance.now()-started});if(alive&&latest.current.active)setError('Нет связи с Mission Core. Файл остаётся на борту.');}finally{busy=false;}}; + void poll();const timer=setInterval(()=>void poll(),500); + return()=>{alive=false;clearInterval(timer);client.close();evidence.current=null;}; + },[url,accept]); + const toggle=useCallback(async(options?:DevOptions,local?:LocalCaptureOptions)=>{ + if(pending||latest.current.closing)return false; + setPending(true);setError(null); + try{ + const enabled=!latest.current.active;if(!enabled)await evidence.current?.flush(); + const previousID=latest.current.local_capture?.id; + if(enabled&&local?.enabled&&previousID&&savedLocal.current!==previousID)throw Error("Сначала сохраните предыдущий замер компьютера в окне логов."); + const r=await fetch(url+'/diagnostics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(enabled?{enabled,options:options??localDevOptions,...(local?{local_options:{...local,previous_id:previousID??null}}:{})}:{enabled})}); + const value=await r.json();if(!r.ok)throw Error(value.detail??'Не удалось переключить DEV.');accept(value);return enabled; + }catch(e){setError(e instanceof Error?e.message:'Не удалось переключить DEV.');return false;}finally{setPending(false);} + },[url,pending,accept]); + const save=useCallback(async()=>{ + if(saving)return;setSaving(true);setError(null); + try{await saveRoverLog(url,latest.current.node?.storage?.file?.split('/').pop()??`rover-${latest.current.id}.jsonl`);} + catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить файл.');} + finally{setSaving(false);} + },[url,saving]); + const saveLocal=useCallback(async()=>{ + const id=latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null); + try{await saveOperatorCapture(url,id,async()=>{await evidence.current?.flush();});if(latest.current.local_capture?.id===id&&!latest.current.local_capture.active)savedLocal.current=id;} + catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить замер.');} + finally{setSaving(false);} + },[url,saving]); + return {state,rows,pending,saving,error,toggle,save,saveLocal,clearError:()=>setError(null)}; +} +export type RoverDiagnostics=ReturnType; diff --git a/apps/control-station/src/core/fleet/useVehicleObservation.ts b/apps/control-station/src/core/fleet/useVehicleObservation.ts index be5e51a3..eac14df3 100644 --- a/apps/control-station/src/core/fleet/useVehicleObservation.ts +++ b/apps/control-station/src/core/fleet/useVehicleObservation.ts @@ -4,56 +4,105 @@ import type {ObservationLayout} from './observationLayout'; import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets'; import {fleetRequest} from './useFleet'; import {sameConfiguration} from './configurationEquality'; +import {observationSerial,mergeObservation,saveObservation} from './observationSync'; interface Document {layouts:ObservationPresets;cameras:Record} interface Receipt {schema:'missioncore.rover-configuration/v1';revision:number;document:Document|null;draft?:Document|null;source:'onboard'|'mirror';writable:boolean;available:boolean} -interface Draft {revision:number;document:Document} +interface Draft {revision:number;document:Document;base?:Document} export function useVehicleObservation(vehicleID:string) { const draftKey=`missioncore.observation.draft.v1:${vehicleID}`; const stored=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}}; const initial=():Document=>({layouts:decodeObservationPresets(null,stored(`missioncore.observation.v1:${vehicleID}`)),cameras:{}}); + const [recovery,setRecovery]=useState(null); + const [connectionError,setConnectionError]=useState(null); const [document,setDocument]=useState(initial),[ready,setReady]=useState(false),[error,setError]=useState(null),[edit,setEdit]=useState(0),[pending,setPending]=useState(false),[errorDismissed,setErrorDismissed]=useState(false); - const state=useRef({document,edit:0,saved:0,revision:0,ready:false}); + const state=useRef({document,base:document,edit:0,saved:0,revision:0,ready:false}); const mounted=useRef(true),writes=useRef(Promise.resolve()); const path=`/${encodeURIComponent(vehicleID)}/observation-configuration`; - const normalize=(value:Document):Document=>({...value,layouts:decodeObservationPresets(value.layouts)}); - const remember=()=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:state.current.revision,document:state.current.document}));}catch{/* The board acknowledgement remains the durable save. */}}; + const normalize=(value:Document|null):Document=>value?({...value,layouts:decodeObservationPresets(value.layouts)}):initial(); + const remember=(current=state.current)=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:current.revision,document:current.document,base:current.base}));}catch{/* The board acknowledgement remains the durable save. */}}; const flush=()=>{ + const current=state.current; const write=async()=>{ - const current=state.current;if(!current.ready||current.saved===current.edit)return; + if(!current.ready||current.saved===current.edit)return; const version=current.edit,payload=current.document; - if(mounted.current)setPending(true); + if((mounted.current&&state.current===current))setPending(true); try { - const receipt=await fleetRequest(path,'PUT',{expected_revision:current.revision,document:payload},20000); - current.revision=receipt.revision;current.saved=version; - if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember(); - if(mounted.current)setError(null); - }catch(cause){if(mounted.current){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}} - finally{if(mounted.current)setPending(current.saved!==current.edit);} + const saved=await saveObservation(current.revision,current.base,payload, + ()=>fleetRequest(path),(revision,document)=>fleetRequest(path,'PUT',{expected_revision:revision,document},20000),normalize); + current.revision=saved.receipt.revision;current.base=saved.document;current.saved=version; + // Preserve edits made while the request was pending, plus unrelated changes + // which were merged from the board. Conflicting new edits remain local. + current.document=mergeObservation(payload,current.document,saved.document).value; + if((mounted.current&&state.current===current))setDocument(current.document); + if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember(current); + if((mounted.current&&state.current===current))setError(null); + }catch(cause){if((mounted.current&&state.current===current)){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}} + finally{if((mounted.current&&state.current===current))setPending(current.saved!==current.edit);} }; - writes.current=writes.current.then(write,write);return writes.current; + writes.current=observationSerial(vehicleID,write);return writes.current; }; useEffect(()=>{ - mounted.current=true;let active=true; - fleetRequest(path).then(receipt=>{ + mounted.current=true;let active=true,timer:ReturnType|undefined,wasWritable=false; + const empty=initial();state.current={document:empty,base:empty,edit:0,saved:0,revision:0,ready:false}; + setReady(false);setError(null);setConnectionError(null);setErrorDismissed(false);setRecovery(null); + const refresh=async()=>{ + let retrySave=false; + try{await observationSerial(vehicleID,async()=>{ if(!active)return; - const saved=receipt.document?normalize(receipt.document):initial(); + const receipt=await fleetRequest(path); + if(!active)return; + setConnectionError(receipt.writable?null:'Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.'); + const recovered=receipt.writable&&!wasWritable;wasWritable=receipt.writable; + const current=state.current; + if(current.ready){ + // Availability is rechecked independently of edits. A mirror cannot roll + // back the acknowledged board version or overwrite an unsaved local draft. + if(!receipt.writable||receipt.revision{if(active)setError(cause instanceof Error?cause.message:'Настройки недоступны.');}); - return()=>{active=false;mounted.current=false;void flush();}; + }); + if(active&&retrySave)void flush(); + }catch(cause){if(active){wasWritable=false;setConnectionError(cause instanceof Error?cause.message:'Настройки недоступны.');}} + finally{if(active)timer=setTimeout(()=>void refresh(),5000);} + }; + void refresh(); + return()=>{active=false;clearTimeout(timer);mounted.current=false;void flush();}; },[vehicleID]); useEffect(()=>{if(!ready||edit===0)return;const timer=setTimeout(()=>void flush(),350);return()=>clearTimeout(timer);},[edit,ready]); const update=(change:(value:Document)=>Document)=>{ if(!state.current.ready)return; - const current=state.current;current.document=change(current.document);current.edit++;remember(); + const current=state.current;const next=change(current.document);if(sameConfiguration(next,current.document))return;current.document=next;current.edit++;remember(); setDocument(current.document);setEdit(current.edit);setPending(true); }; const changeLayouts=(change:(value:ObservationPresets)=>ObservationPresets)=>{ @@ -61,22 +110,32 @@ export function useVehicleObservation(vehicleID:string) { catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;} }; const reload=async()=>{ + const current=state.current; + if(state.current.saved!==state.current.edit){const copy=state.current.document;setRecovery(copy);try{localStorage.setItem(draftKey+':recovery',JSON.stringify(copy));}catch{}} await writes.current; try{ - const receipt=await fleetRequest(path); + const receipt=await observationSerial(vehicleID,()=>fleetRequest(path)); + if(!mounted.current||state.current!==current)return false; if(!receipt.writable)throw Error('Не удалось получить актуальную конфигурацию с борта. Черновик сохранён.'); const value=receipt.document?normalize(receipt.document):initial(); - state.current={document:value,edit:0,saved:0,revision:receipt.revision,ready:true}; + state.current={document:value,base:value,edit:0,saved:0,revision:receipt.revision,ready:true}; setDocument(value);setReady(true);setEdit(0);setPending(false);setError(null); try{localStorage.removeItem(draftKey);}catch{} - }catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');} + return true; + }catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');return false;} }; const setLayout=(value:SetStateAction)=>changeLayouts(current=>({...current,layout:typeof value==='function'?value(current.layout):value})); - return {...document.layouts,ready,pending,cameras:document.cameras,setLayout, + const restore=async()=>{ + const retained=recovery??state.current.document; + if(!await reload())return; + update(()=>retained);setRecovery(null); + try{localStorage.removeItem(draftKey+':recovery');}catch{} + }; + return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout, setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})), select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)), save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)), rename:(id:string,name:string)=>changeLayouts(current=>renameObservationPreset(current,id,name)), remove:(id:string)=>changeLayouts(current=>removeObservationPreset(current,id)), - error,toastError:errorDismissed?null:error,clearError:()=>setErrorDismissed(true),retry:flush,reload}; + error:error??connectionError,toastError:errorDismissed?null:error??connectionError,clearError:()=>setErrorDismissed(true),retry:flush,reload}; } diff --git a/apps/control-station/src/workspaces/fleet/BoardNetworkSettings.tsx b/apps/control-station/src/workspaces/fleet/BoardNetworkSettings.tsx new file mode 100644 index 00000000..7392b720 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/BoardNetworkSettings.tsx @@ -0,0 +1,31 @@ +import {useRef} from 'react'; +import {Button,Icon,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react'; +import {useBoardNetwork,type NetworkProvider} from '../../core/fleet/useBoardNetwork'; +import {InstallerCard} from './equipment/InstallerCard'; +export function BoardNetworkSettings({network}:{network:ReturnType}){ + const input=useRef(null); + const {value,provider,profileId,busy,applying,error}=network; + const current=value?.node; + const selected=value?.profiles.find(p=>p.id===profileId); + const progress=value?.operation?.state; + const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён'; + return
+ {label}}> + p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/> + {selected&&{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}} +

Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.

+ } + {!value?.available&&

Для изменения настроек нужен доступный БК с актуальной версией Node.

} + {(error||value?.operation?.error||current?.error)&&{error||value?.operation?.error||current?.error}} +
+ {provider==='wireguard'&&<> + + {const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(file)void network.importing(file);}}/> + + + + } +
; +} diff --git a/apps/control-station/test/liveTiming.test.mjs b/apps/control-station/test/liveTiming.test.mjs new file mode 100644 index 00000000..78236e85 --- /dev/null +++ b/apps/control-station/test/liveTiming.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +async function module(path){const result=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));} +const {PreviewMetrics}=await module('../../../packages/sensor-ui/src/previewMetrics.ts'); +const {RoverTiming}=await module('../src/core/fleet/roverTiming.ts'); +const stats=(extra={})=>new Map([['video',{id:'a',type:'inbound-rtp',kind:'video',timestamp:1000,bytesReceived:1e6,framesDecoded:100,packetsLost:2,framesDropped:1,jitterBufferDelay:50,jitterBufferEmittedCount:100,totalDecodeTime:2,...extra}],['pair',{type:'candidate-pair',state:'succeeded',nominated:true,currentRoundTripTime:.012}]]); +test('preview reports interval latency, not the lifetime mean or capture-to-screen age',()=>{ + const m=new PreviewMetrics();assert.equal(m.sample(stats()).jitter_buffer_ms,null); + const v=m.sample(stats({timestamp:3000,bytesReceived:1.5e6,framesDecoded:130,packetsLost:3,framesDropped:3,jitterBufferDelay:53,jitterBufferEmittedCount:130,totalDecodeTime:2.06})); + assert.equal(v.fps,15);assert.equal(v.mbps,2);assert.equal(v.jitter_buffer_ms,100);assert.equal(v.decode_ms,2);assert.equal(v.round_trip_ms,12);assert.equal(v.packets_lost,1);assert.equal(v.frames_dropped,2);assert.equal(v.scope,'receiver-interval');assert.equal(v.processing_ms,null); +}); +test('missing counters and replacement streams cannot manufacture zero latency',()=>{ + const m=new PreviewMetrics();m.sample(stats()); + assert.equal(m.sample(stats({id:'b',timestamp:3000,jitterBufferDelay:55,jitterBufferEmittedCount:130})).jitter_buffer_ms,null); + assert.equal(m.sample(stats({id:'b',timestamp:3000})).fps,null); + assert.equal(m.sample(new Map()),null); +}); +test('counter resets do not create negative rates or leaked endpoint data',()=>{ + const m=new PreviewMetrics();m.sample(stats());const v=m.sample(stats({timestamp:3000,framesDecoded:1,bytesReceived:1,remoteAddress:'private',sdp:'secret'})); + assert.equal(v.fps,null);assert.equal(v.mbps,null);assert.ok(!JSON.stringify(v).includes('private'));assert.ok(!JSON.stringify(v).includes('secret')); +}); +test('control timing separates scheduling gaps from HTTP time and remains bounded',()=>{ + const oldDocument=globalThis.document,oldPerformance=globalThis.performance;let now=0; + globalThis.document={hidden:false,hasFocus:()=>true,documentElement:{dataset:{}}};globalThis.performance={now:()=>now}; + try{const m=new RoverTiming();m.tick(false);now=100;m.tick(false);assert.equal(JSON.parse(document.documentElement.dataset.roverTiming).events.length,0); + now=500;document.hidden=true;m.tick(true);let v=JSON.parse(document.documentElement.dataset.roverTiming);assert.equal(v.events[0].kind,'heartbeat-gap');assert.equal(v.events[0].gap_ms,400);assert.equal(v.events[0].hidden,true); + now=600;m.request('view',590,'transport');v=JSON.parse(document.documentElement.dataset.roverTiming);assert.equal(v.events.at(-1).duration_ms,10);assert.equal(v.events.at(-1).outcome,'transport'); + for(let i=0;i<100;i++){now+=300;m.tick(false);}assert.equal(JSON.parse(document.documentElement.dataset.roverTiming).events.length,16); + m.clear();assert.equal(document.documentElement.dataset.roverTiming,undefined); + }finally{globalThis.document=oldDocument;globalThis.performance=oldPerformance;} +}); diff --git a/apps/control-station/test/observationSync.test.mjs b/apps/control-station/test/observationSync.test.mjs new file mode 100644 index 00000000..8bccc807 --- /dev/null +++ b/apps/control-station/test/observationSync.test.mjs @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import {before,after,test} from 'node:test'; +import {createServer} from './support/vite-server.mjs'; +let server,sync; +before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});sync=await server.ssrLoadModule('/src/core/fleet/observationSync.ts');}); +after(async()=>{await server?.close();}); +const receipt=(document,revision=2)=>({document,revision,writable:true}); +test('disjoint camera and layout edits merge while conflicting leaves and arrays remain explicit',()=>{ + const base={camera:{yaw:0,flip:false},layout:{ratio:50,hidden:[]}},local={...base,camera:{...base.camera,yaw:90}},remote={...base,layout:{...base.layout,ratio:60}}; + assert.deepEqual(sync.mergeObservation(base,local,remote),{value:{camera:local.camera,layout:remote.layout},conflicts:[]}); + assert.deepEqual(sync.mergeObservation(base,local,{...base,camera:{...base.camera,yaw:180}}).conflicts,['camera.yaw']); + assert.deepEqual(sync.mergeObservation({a:1,b:2},{b:2},{a:1,b:3}),{value:{b:3},conflicts:[]}); + assert.deepEqual(sync.mergeObservation([],['a'],['b']).conflicts,['']); +}); +test('lost ACK is settled by equality without replay',async()=>{ + let writes=0;const doc={ratio:55};const saved=await sync.saveObservation(1,{ratio:50},doc,async()=>receipt(doc,2),async()=>{writes++;throw Error('timeout');},v=>v); + assert.equal(saved.receipt.revision,2);assert.equal(writes,1); +}); +test('revision conflict retries once with a fresh revision and merged document',async()=>{ + const calls=[];const saved=await sync.saveObservation(1,{a:1,b:1},{a:2,b:1},async()=>receipt({a:1,b:2},3),async(rev,doc)=>{calls.push([rev,doc]);if(rev===1)throw Error('conflict');return receipt(doc,4);},v=>v); + assert.deepEqual(calls,[[1,{a:2,b:1}],[3,{a:2,b:2}]]);assert.deepEqual(saved.document,{a:2,b:2}); +}); +test('competing edits never overwrite and repeated failures are bounded',async()=>{ + let writes=0; + await assert.rejects(sync.saveObservation(1,{x:1},{x:2},async()=>receipt({x:3}),async()=>{writes++;throw Error('conflict');},v=>v),/другом окне/);assert.equal(writes,1); + writes=0;await assert.rejects(sync.saveObservation(1,{x:1},{x:2},async()=>receipt({x:1}),async()=>{writes++;throw Error('down');},v=>v),/down/);assert.equal(writes,2); +}); +test('next mount reads after pending save, failed writes do not poison queue, vehicles are independent',async()=>{ + let release;const gate=new Promise(r=>{release=r;}),events=[]; + const a=sync.observationSerial('rover',async()=>{events.push('write');await gate;events.push('ack');}); + const b=sync.observationSerial('rover',async()=>events.push('read')); + await sync.observationSerial('other',async()=>events.push('other'));assert.deepEqual(events,['write','other']);release();await Promise.all([a,b]);assert.deepEqual(events,['write','other','ack','read']); + await assert.rejects(sync.observationSerial('rover',async()=>{throw Error('fail');}));assert.equal(await sync.observationSerial('rover',async()=>42),42); +}); diff --git a/apps/control-station/test/roverControlFocus.test.mjs b/apps/control-station/test/roverControlFocus.test.mjs index c3fd7a70..2714b1de 100644 --- a/apps/control-station/test/roverControlFocus.test.mjs +++ b/apps/control-station/test/roverControlFocus.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import {build} from 'esbuild'; const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){ b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'})); + b.onResolve({filter:/^\.\/roverTransport$/},()=>({path:'transport',namespace:'fixture-transport'})); + b.onLoad({filter:/.*/,namespace:'fixture-transport'},()=>({contents:`export class RoverHttpError extends Error{constructor(message,status){super(message);this.status=status;}};export const retainRoverTransport=()=>()=>{};export const roverConnection=()=>"connected";export async function roverRequest(url,body){const response=await fetch(url,{body:body?JSON.stringify(body):undefined});const result=await response.json();if(!response.ok)throw new RoverHttpError(result.detail,response.status);return result;}`})); b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`})); }}]}); const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); @@ -20,24 +22,24 @@ async function fixture(run){ } test('command heartbeat sends neutral on lost blur, keeps session, and accepts new focused input',async()=>fixture(async f=>{ f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush(); - assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===100).f();await flush(); - assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0); - f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0); - f.focus();f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.left,0); + assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===50).f();await flush(); + assert.ok(f.calls.at(-1).url.endsWith('/hold'));assert.equal('left' in f.calls.at(-1).body,false); + f.c.setDemand({left:1,right:1});await flush();assert.ok(f.calls.at(-1).url.endsWith('/hold')); + f.focus();f.timers.find(t=>t.ms===50).f();await flush();assert.equal(f.calls.at(-1).body.left,0); f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1); assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); })); test('expired physical input prevents heartbeat from renewing remembered demand',async()=>fixture(async f=>{ let valid=true;f.c.setInputGuard(()=>valid);f.c.setDemand({left:1,right:-1});await flush();valid=false; - f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.stop,false); + f.timers.find(t=>t.ms===50).f();await flush();assert.equal(f.calls.at(-1).body.stop,false); })); test('no registered input scope cannot issue motion',async()=>fixture(async f=>{ f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.stop,false); assert.equal(f.calls.some(x=>x.body?.left===1),false); })); -test('hidden document sends only neutral without a visibility event',async()=>fixture(async f=>{ +test('hidden document hands neutral readiness to Core even without a visibility event',async()=>fixture(async f=>{ f.c.setInputGuard(()=>true);f.hide();f.c.setDemand({left:1,right:1});await flush(); - assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.some(x=>x.body?.left===1),false); + assert.ok(f.calls.at(-1).url.endsWith('/hold'));assert.equal(f.calls.some(x=>x.body?.left===1),false); })); test('explicit pause clears demand without revoking session; explicit stop still revokes it',async()=>fixture(async f=>{ diff --git a/apps/control-station/test/roverControlStartup.test.mjs b/apps/control-station/test/roverControlStartup.test.mjs index 05b371e3..1756b99e 100644 --- a/apps/control-station/test/roverControlStartup.test.mjs +++ b/apps/control-station/test/roverControlStartup.test.mjs @@ -3,26 +3,34 @@ import assert from 'node:assert/strict'; import {build} from 'esbuild'; const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){ b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'})); - b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`})); + b.onResolve({filter:/^\.\/roverTransport$/},()=>({path:'transport',namespace:'fixture-transport'})); + b.onLoad({filter:/.*/,namespace:'fixture-transport'},()=>({contents:`export class RoverHttpError extends Error{constructor(message,status){super(message);this.status=status;}};export const retainRoverTransport=()=>()=>{};export const roverConnection=()=>"connected";export async function roverRequest(url,body){const response=await fetch(url,{body:body?JSON.stringify(body):undefined});const result=await response.json();if(!response.ok)throw new RoverHttpError(result.detail,response.status);return result;}`})); + b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,next=>globalThis.roverStateWrites.push(next)];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`})); }}]}); const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); const flush=()=>new Promise(resolve=>setImmediate(resolve)); const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}; const response=value=>({ok:true,json:async()=>value}); -const idle={fresh:true,controlling:false,snapshot:{supported:true,state:'observing'}}; +const idle={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'driver-A',state:'observing',release_confirmed:true,devices:[{uuid:'motor-A',session_id:'usb-A',age_ms:0,values:{erpm:0,fault_code:0}}]}}; +const stopped={...idle,snapshot:{...idle.snapshot,state:'stopped',session_id:'new-session'}}; async function fixture(run){ - const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]])); - const calls=[],timers=[];globalThis.roverEffects=[]; - globalThis.window={addEventListener(){},removeEventListener(){}};globalThis.document={hidden:false,hasFocus:()=>true,addEventListener(){},removeEventListener(){}}; + const originals=Object.fromEntries(['window','document','fetch','roverEffects','roverStateWrites','setInterval','clearInterval','performance'].map(k=>[k,globalThis[k]])); + let now=0;globalThis.performance={now:()=>now};const calls=[],timers=[];globalThis.roverEffects=[];globalThis.roverStateWrites=[]; + const windowEvents=new Map(),documentEvents=new Map();let focused=true; + const events=target=>({addEventListener:(name,fn)=>target.set(name,fn),removeEventListener:name=>target.delete(name)}); + globalThis.window=events(windowEvents);globalThis.document={hidden:false,hasFocus:()=>focused,...events(documentEvents)}; globalThis.setInterval=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearInterval=()=>{}; - let armResponse=null,nextPoll=null; + let armResponse=null,nextPoll=null,holdCommands=false;const commands=[]; globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body}); if(url.endsWith('/arm'))return armResponse?armResponse.promise:response({session_id:'new-session'}); if(!body)return nextPoll?nextPoll.promise:response(idle); + if(holdCommands&&!body.stop){const gate=deferred();commands.push({body,gate});return gate.promise;} return response({accepted_sequence:body.sequence}); }; const c=useRoverControl('fixture',true),cleanup=globalThis.roverEffects.map(f=>f()); - try{await flush();await run({c,calls,poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===100).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});} + try{await flush();await run({c,calls,stateWrites:globalThis.roverStateWrites,commands,timers,advance:ms=>{now+=ms;},hide:()=>{globalThis.document.hidden=true;focused=false;documentEvents.get('visibilitychange')?.();}, + show:()=>{globalThis.document.hidden=false;focused=true;documentEvents.get('visibilitychange')?.();windowEvents.get('focus')?.();}, + pagehide:()=>windowEvents.get('pagehide')?.(),holdCommands:()=>{holdCommands=true;},poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===50).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});} finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}} } test('idle poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{ @@ -47,3 +55,209 @@ test('duplicate arm clicks while request pending create exactly one lease reques a.resolve(response({session_id:'new-session'}));await Promise.all([first,second]);await flush(); assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); })); +test('throttle uses explicit percent units and starts with zero demand',async()=>fixture(async f=>{ + assert.equal(await f.c.arm(30,50,'duty'),true);await flush(); + assert.deepEqual(f.calls.find(x=>x.url.endsWith('/arm')).body,{standstill_confirmed:true,current_a:30,max_duty_percent:50}); + assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0); +})); + +test('delayed acknowledgements do not serialize fresh commands; bounded and no queue',async()=>fixture(async f=>{ + f.holdCommands();assert.equal(await f.c.arm(30,70,'duty'),true);await flush(); + f.heartbeat();f.heartbeat();f.heartbeat();f.heartbeat();await flush(); + assert.equal(f.commands.length,4,'fresh commands must proceed while earlier replies are pending, bounded to four'); + assert.deepEqual(f.commands.map(x=>x.body.sequence),[1,2,3,4]); + f.commands[3].gate.resolve(response({accepted_sequence:4}));await flush(); + f.commands[0].gate.resolve({ok:false,json:async()=>({detail:'Устаревшая команда отклонена.'})});await flush(); + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'late obsolete reply must not revoke newer acknowledged input'); + f.heartbeat();await flush();assert.equal(f.commands.length,5); + f.commands[1].gate.resolve(response({accepted_sequence:2}));f.commands[2].gate.resolve(response({accepted_sequence:3})); + f.commands[4].gate.resolve({ok:false,json:async()=>({detail:'Канал управления недоступен.'})});await flush(); + assert.equal(f.calls.at(-1).body.stop,true); + assert.ok(f.stateWrites.includes('Канал управления недоступен.')); +})); +test('missing telemetry preserves the last verified control mode and reports session end',async()=>fixture(async f=>{ + let p=f.delayPoll();f.poll();p.resolve(response({fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],state:'observing'}}));await flush(); + assert.equal(f.stateWrites.at(-1),'duty'); + assert.equal(await f.c.arm(30,70,'duty'),true);await flush(); + const mark=f.stateWrites.length;p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush(); + assert.equal(f.calls.at(-1).body.stop,true); + assert.ok(f.stateWrites.slice(mark).some(v=>typeof v==='string'&&v.includes('нет свежих данных'))); + assert.equal(f.stateWrites.slice(mark).includes('rpm'),false); +})); +test('unknown driver identity after preparation produces a visible reason',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush();const p=f.delayPoll();f.poll(); + p.resolve(response({fresh:true,controlling:false,snapshot:{supported:true,control_modes:['duty'],state:'stopped'}}));await flush(); + assert.ok(f.stateWrites.some(v=>typeof v==='string'&&v.includes('перезапустился'))); + assert.equal(f.calls.at(-1).body.stop,true); +})); + + +test('transport loss reacquires a new neutral session only after stable stopped observations',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:1});await flush(); + let p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush(); + assert.equal(f.calls.at(-1).body.stop,true); + assert.equal(f.stateWrites.at(-1),null,'transient loss uses recovery state, not a terminal error'); + f.advance(600);p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); + f.advance(600);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2); + assert.deepEqual(f.calls.filter(x=>x.url.endsWith('/arm')).at(-1).body,{standstill_confirmed:true,current_a:30,max_duty_percent:70}); + assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0); + f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0,'previous input guard must be retired'); +})); +test('explicit Stop cancels recovery and a delayed successful rearm is retired',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush();let p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush(); + f.advance(600);p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + const a=f.delayArm();f.advance(600);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2);f.c.stop(); + a.resolve(response({session_id:'replacement-session'}));await flush(); + assert.deepEqual(f.calls.at(-1).body,{session_id:'replacement-session',sequence:1,left:0,right:0,stop:true}); + f.advance(9000);f.poll();await flush();assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2); +})); +test('receiver takeover is terminal and cannot automatically reacquire control',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush();let p=f.delayPoll();f.poll();p.resolve(response({...stopped,snapshot:{...stopped.snapshot,state:'receiver'}}));await flush(); + assert.ok(f.stateWrites.includes('Управление передано пульту.')); + p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();f.advance(9000);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); +})); +test('manual retry after USB recovery survives old fault polls before and after arm acknowledgement',async()=>fixture(async f=>{ + const failed={...idle,snapshot:{...idle.snapshot,session_id:'previous-session',state:'fault',release_confirmed:false,message:'Previous USB failure'}}; + let p=f.delayPoll();f.poll();p.resolve(response(failed));await flush(); + const mark=f.stateWrites.length,a=f.delayArm(),arming=f.c.arm(30,70,'duty'); + p=f.delayPoll();f.poll();p.resolve(response(failed));await flush(); + a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush(); + p=f.delayPoll();f.poll();p.resolve(response({...failed,controlling:true}));await flush();f.heartbeat();await flush(); + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0); + assert.equal(f.stateWrites.slice(mark).includes('Previous USB failure'),false); + assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0); + const preparing={...idle,controlling:true,snapshot:{...idle.snapshot,session_id:'new-session',state:'preparing',release_confirmed:null}}; + p=f.delayPoll();f.poll();p.resolve(response(preparing));await flush(); + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0); + p=f.delayPoll();f.poll();p.resolve(response({...preparing,snapshot:{...preparing.snapshot,state:'fault',release_confirmed:false,message:'New hardware failure'}}));await flush(); + assert.equal(f.calls.at(-1).body.stop,true);assert.ok(f.stateWrites.includes('New hardware failure')); +})); + + +// No physical hardware is used. Core/socket tests separately prove that the +// hold survives missing renderer heartbeats and cannot refresh movement. +test('five-second hidden desktop retains the same lease and resumes without another arm',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush(); + f.hide();await flush(); + assert.ok(f.calls.at(-1).url.endsWith('/hold')); + assert.deepEqual(f.calls.at(-1).body,{session_id:'new-session',sequence:3}); + const ready={...idle,controlling:true,snapshot:{...idle.snapshot,state:'ready',session_id:'new-session'}}; + let p=f.delayPoll();f.poll();p.resolve(response(ready));await flush(); + const count=f.calls.length; + for(let n=0;n<5;n++){f.advance(1000);f.heartbeat();f.poll();await flush();} + assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); + assert.ok(f.calls.slice(count).every(x=>!x.body),'native Core retains neutral without a JS command loop'); + f.show();await flush(); + assert.equal(f.calls.at(-1).body.session_id,'new-session'); + assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1,'return must not prepare another session'); + f.c.setDemand({left:.5,right:.5});await flush(); + assert.equal(f.calls.at(-1).body.left,.5,'a new input is accepted immediately'); +})); +test('hide during pending preparation hands the acknowledged lease to neutral hold',async()=>fixture(async f=>{ + const a=f.delayArm(),arming=f.c.arm(30,70,'duty');f.hide();await flush(); + a.resolve(response({session_id:'late-session'}));await arming;await flush(); + assert.ok(f.calls.at(-1).url.endsWith('/hold')); + assert.deepEqual(f.calls.at(-1).body,{session_id:'late-session',sequence:1}); + f.advance(5000);f.heartbeat();await flush(); + assert.equal(f.calls.filter(x=>x.body?.session_id==='late-session').length,1); + assert.equal(f.calls.some(x=>x.body?.stop===true),false); +})); +test('Stop and page navigation terminate a held session without automatic rearm',async()=>{ + for(const action of ['stop','pagehide'])await fixture(async f=>{ + await f.c.arm(30,70,'duty');f.hide();await flush(); + if(action==='stop')f.c.stop();else f.pagehide(); + assert.equal(f.calls.at(-1).body.stop,true); + const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + f.show();await flush();f.advance(10000);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); + }); +}); +test('actual telemetry loss during neutral hold still retires the session',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');f.hide();await flush(); + const p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush(); + assert.equal(f.calls.at(-1).body.stop,true); + f.show();await flush();f.advance(10000);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); +})); +test('manual arm while hidden cannot acquire a lease',async()=>fixture(async f=>{ + f.hide();assert.equal(await f.c.arm(30,70,'duty'),false); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,0); +})); + + +test('USB reconnection retires control even when the controller UUID is unchanged',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + const changed={...stopped,snapshot:{...stopped.snapshot,devices:stopped.snapshot.devices.map(d=>({...d,session_id:'usb-B'}))}}; + let p=f.delayPoll();f.poll();p.resolve(response(changed));await flush(); + assert.equal(f.calls.at(-1).body.stop,true); + f.advance(9000);f.poll();await flush(); + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1); + assert.ok(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Подключение VESC изменилось'))); +})); + + +test('fresh intent occupies each 50ms carrier opportunity without replaying invalid input',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush();f.c.setInputGuard(()=>true); + const heartbeat=f.timers.find(t=>t.ms===50);assert.ok(heartbeat); + assert.equal(f.timers.filter(t=>t.ms<200).length,1,'one producer timer'); + const start=f.calls.filter(x=>x.url.endsWith('/command')).length; + for(let n=0;n<4;n++){f.advance(50);heartbeat.f();await flush();} + const commands=f.calls.filter(x=>x.url.endsWith('/command')).slice(start); + assert.equal(commands.length,4);assert.deepEqual(commands.map(x=>x.body.sequence),[2,3,4,5]); + assert.ok(commands.every(x=>x.body.left===0&&x.body.right===0)); + f.c.setInputGuard(()=>false);f.c.setDemand({left:1,right:1});await flush(); + f.advance(50);heartbeat.f();await flush();assert.equal(f.calls.at(-1).body.left,0); + f.c.stop();await flush();const count=f.calls.length; + f.advance(50);heartbeat.f();await flush();assert.equal(f.calls.length,count,'stop retires timer authority'); +})); + + +test('repeated failed automatic arm stays rate bounded until explicit Stop',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + const a=f.delayArm();a.resolve({ok:false,status:503,json:async()=>({detail:'Канал временно недоступен.'})}); + for(let tick=0;tick<100;tick++){f.advance(200);f.poll();await flush();} + const count=f.calls.filter(x=>x.url.endsWith('/arm')).length; + assert.ok(count>=5&&count<=7,'rate bounded retries survive transient failures'); + assert.equal(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Автовосстановление остановлено')),false); + f.c.stop();await flush(); + for(let n=0;n<3;n++){f.advance(100000);f.poll();await flush();} + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,count,'explicit stop cancels all further attempts'); +})); + +// Owner-requested transport continuity through repeated failed admissions. +test('transport recovery persists beyond three failures and explicit Stop cancels it',async()=>fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + const a=f.delayArm();a.resolve({ok:false,status:503,json:async()=>({detail:'Канал временно недоступен.'})}); + for(let tick=0;tick<100;tick++){f.advance(200);f.poll();await flush();} + const count=f.calls.filter(x=>x.url.endsWith('/arm')).length; + assert.ok(count>=5&&count<=7,'bounded retry frequency without terminal cutoff'); + assert.equal(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Автовосстановление остановлено')),false); + f.c.stop();await flush(); + for(let n=0;n<3;n++){f.advance(100000);f.poll();await flush();} + assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,count,'explicit stop cancels background recovery'); +})); + +test('transient 409 admission races preserve recovery but ownership conflicts remain terminal',async()=>{ + for(const reason of ['Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.','Аппаратом уже управляют. Сначала остановите управление.']){ + await fixture(async f=>{ + await f.c.arm(30,70,'duty');await flush(); + const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush(); + const a=f.delayArm();a.resolve({ok:false,status:409,json:async()=>({detail:reason})}); + for(let tick=0;tick<60;tick++){f.advance(200);f.poll();await flush();} + const count=f.calls.filter(x=>x.url.endsWith('/arm')).length; + if(reason.startsWith('Аппаратом уже'))assert.equal(count,2,'another owner cannot be automatically overridden'); + else assert.ok(count>2&&count<=6,'temporary conflict should retain rate bounded recovery: '+reason); + assert.ok(f.calls.filter(x=>x.body&&'left' in x.body).every(x=>x.body.left===0&&x.body.right===0)); + }); + } +}); diff --git a/apps/control-station/test/roverDevEvents.test.mjs b/apps/control-station/test/roverDevEvents.test.mjs new file mode 100644 index 00000000..aca53332 --- /dev/null +++ b/apps/control-station/test/roverDevEvents.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const compiled=await build({entryPoints:[new URL('../src/core/fleet/roverDevEvents.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {connectRoverEvidence,roverDevEvent}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64')); +test('browser evidence is opt-in, separate, and disabled again at session end',async()=>{ + const original=globalThis.fetch,calls=[];globalThis.fetch=async(_url,init)=>{calls.push(JSON.parse(init.body));return {ok:true};}; + const connection=connectRoverEvidence('/rover'); + try{ + roverDevEvent('/rover','demand',{left:1});await connection.flush();assert.equal(calls.length,0); + connection.set('a'.repeat(32));roverDevEvent('/rover','demand',{left:1,right:-1});await connection.flush(); + assert.equal(calls.length,1);assert.equal(calls[0].events[0].right,-1); + connection.set(null);roverDevEvent('/rover','demand',{left:1});await connection.flush();assert.equal(calls.length,1); + }finally{connection.close();globalThis.fetch=original;} +}); diff --git a/apps/control-station/test/roverFaultNotice.test.mjs b/apps/control-station/test/roverFaultNotice.test.mjs new file mode 100644 index 00000000..7050a7e3 --- /dev/null +++ b/apps/control-station/test/roverFaultNotice.test.mjs @@ -0,0 +1,19 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const source=await build({entryPoints:[new URL('../src/core/fleet/roverFaultNotice.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {RoverFaultNotice}=await import('data:text/javascript;base64,'+Buffer.from(source.outputFiles[0].contents).toString('base64')); +const frame=(message='old fault',session_id='old',fresh=true)=>({fresh,snapshot:{instance_id:'node',session_id,state:message?'fault':'stopped',message}}); +test('opening an existing terminal snapshot is a baseline, not a new failure toast',()=>{ + const n=new RoverFaultNotice();assert.equal(n.update(frame(),null).show,undefined); + assert.equal(n.update(frame(),null).show,undefined); + assert.equal(n.update(frame(null),null).clear,'old fault'); + assert.equal(n.update(frame('new fault','new'),null).show,'new fault'); + assert.equal(n.update(frame('new fault','new'),null).show,undefined); +}); +test('stale snapshots cannot establish baseline or clear a live error; owned new faults are immediate',()=>{ + const n=new RoverFaultNotice();assert.deepEqual(n.update(frame('ignored','old',false),null),{}); + assert.equal(n.update(frame('active fault','owned'),'owned').show,'active fault'); + assert.deepEqual(n.update(frame(null,'owned',false),'owned'),{}); + assert.equal(n.update(frame(null,'owned'),'owned').clear,'active fault'); +}); diff --git a/apps/control-station/test/roverHoldInput.test.mjs b/apps/control-station/test/roverHoldInput.test.mjs index 5b2af77d..9687e90c 100644 --- a/apps/control-station/test/roverHoldInput.test.mjs +++ b/apps/control-station/test/roverHoldInput.test.mjs @@ -13,7 +13,7 @@ class Events { tick(){for(const fn of this.timers.values())fn();} } function fixture(mode='arcade'){ - let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus; + let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus;doc.querySelector=()=>null;doc.body={closest:()=>null}; const scope={ownerDocument:doc,closest:()=>null},child={closest:()=>null};scope.contains=x=>x===scope||x===child;doc.activeElement=scope; const states=[],demands=[];let stops=0,pauses=0; const binding=bindRoverHoldInput(scope,mode,{held:k=>states.push([...k]),demand:d=>demands.push(d),stop:()=>stops++,pause:()=>{pauses++;demands.push({left:0,right:0});}},()=>time); @@ -34,12 +34,15 @@ test('heartbeat validity catches missing blur event using document focus',()=>{ test('focus polling catches missing event or moving to another control',()=>{ const f=fixture();f.key('KeyW');f.doc.activeElement={};f.advance(50);assert.equal(f.pauses(),1);f.binding.dispose(); }); -test('lost keyup AND missing focus notifications still expire repeated D',()=>{ - const f=fixture();f.key('KeyD');f.advance(500);f.key('KeyD',true);f.advance(299);assert.equal(f.pauses(),0); - f.advance(1);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.key('KeyD',true);assert.equal(f.pauses(),1);f.binding.dispose(); +test('releasing the repeated key in AD keeps A held without OS autorepeat',()=>{ + const f=fixture('tank');f.key('KeyA');f.key('KeyD');f.advance(500);f.key('KeyD',true); + f.up('KeyD');f.advance(10000);assert.equal(f.pauses(),0); + assert.deepEqual(f.demands.at(-1),{left:-1,right:0}); + f.up('KeyA');assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.binding.dispose(); }); -test('first press allows OS repeat delay but never an indefinite hold',()=>{ - const f=fixture();f.key('KeyW');f.advance(999);assert.equal(f.pauses(),0);f.advance(1);assert.equal(f.pauses(),1);f.binding.dispose(); +test('a held key does not require OS autorepeat, but focus still revokes it',()=>{ + const f=fixture();f.key('KeyW');f.advance(10000);assert.equal(f.pauses(),0); + f.loseFocus();f.advance(50);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.binding.dispose(); }); test('continuous repeat renews hold; keyup immediately sends neutral',()=>{ const f=fixture();f.key('KeyW');f.advance(600); @@ -83,3 +86,22 @@ test('modifier shortcuts pause; cleanup removes listeners, timer and held demand test('Space and Escape remain explicit session stops',()=>{ for(const code of ['Space','Escape']){const f=fixture();f.key('KeyW');f.key(code);assert.equal(f.stops(),1);assert.equal(f.binding.valid(),false);f.binding.dispose();} }); + +test('a fresh key works from observation header or browser body without a canvas click',()=>{ + for(const mode of ['tank','arcade'])for(const focus of ['header','body']){ + const f=fixture(mode);f.doc.activeElement=focus==='header'?f.child:f.doc.body; + f.key(mode==='tank'?'KeyQ':'KeyW'); + assert.deepEqual(f.demands.at(-1),mode==='tank'?{left:1,right:0}:{left:1,right:1}); + f.win.emit('blur');f.key(mode==='tank'?'KeyQ':'KeyW',true); + assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.binding.dispose(); + } +}); +test('forms, content editors and modal layers never become driving input',()=>{ + for(const blocker of ['input','contenteditable','dialog','listbox','menu']){ + const f=fixture();f.key('KeyW'); + if(blocker==='input'||blocker==='contenteditable')f.child.closest=()=>({}); + else f.doc.querySelector=()=>({}); + f.doc.activeElement=f.child;f.advance(50);f.key('KeyD'); + assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.binding.valid(),false);f.binding.dispose(); + } +}); diff --git a/apps/control-station/test/roverInput.test.mjs b/apps/control-station/test/roverInput.test.mjs index f1d41f02..3b925e64 100644 --- a/apps/control-station/test/roverInput.test.mjs +++ b/apps/control-station/test/roverInput.test.mjs @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {build} from 'esbuild'; const result=await build({entryPoints:[new URL('../src/core/fleet/roverInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); -const {keyDemand,roverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const {keyDemand,roverSettings,roverNumberInput,persistableRoverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); const keys=(...k)=>new Set(k.map(v=>'Key'+v)); test('arcade mixes directions and opposite keys cancel',()=>{ assert.deepEqual(keyDemand('arcade',keys('W')),{left:1,right:1}); @@ -21,3 +21,34 @@ test('invalid stored settings never grant motion or invalid limits',()=>{ assert.equal(roverSettings({version:1,model:'https://other/model.glb'}).model,''); assert.deepEqual(keyDemand('arcade',new Set()),{left:0,right:0}); }); +test('saved RPM never becomes full throttle during migration',()=>{ + const migrated=roverSettings({version:1,maxErpm:3000,currentA:30,mode:'tank',model:'dcd006-v020',throttlePercent:100}); + assert.equal(migrated.version,3);assert.equal(migrated.throttlePercent,10); + assert.equal(migrated.mode,'tank');assert.equal(migrated.model,'dcd006-v020'); + assert.equal(roverSettings({...migrated,throttlePercent:50}).throttlePercent,50); + assert.equal(roverSettings({...migrated,throttlePercent:Infinity}).throttlePercent,10); + assert.equal(roverSettings({...migrated,throttlePercent:101}).throttlePercent,100); +}); + +test('legacy empty and clamped current recover to 30 A once',()=>{ + for(const version of [1,2])for(const currentA of [0,.5,null,undefined,-1]) + assert.equal(roverSettings({version,currentA}).currentA,30); + assert.equal(roverSettings({version:2,currentA:12,throttlePercent:70}).currentA,12); + assert.equal(roverSettings({version:2,currentA:.5,throttlePercent:70}).throttlePercent,70); + assert.equal(roverSettings({version:3,currentA:.5}).currentA,.5); +}); +test('empty and invalid number drafts cannot overwrite saved valid settings',()=>{ + const saved=roverSettings({version:3,currentA:30,throttlePercent:70}); + assert.ok(persistableRoverSettings(saved)); + for(const text of ['', ' ', '0', 'Infinity', 'NaN']) + assert.equal(persistableRoverSettings({...saved,currentA:roverNumberInput(text)}),false); + assert.ok(Number.isNaN(roverNumberInput(''))); + assert.ok(persistableRoverSettings({...saved,currentA:roverNumberInput('0.5')})); +}); + +test('operator current above 30 A persists without silently changing it',()=>{ + for(const currentA of [35,60,100,120,150]){ + const saved=roverSettings({version:3,currentA});assert.equal(saved.currentA,currentA); + assert.ok(persistableRoverSettings(saved)); + } +}); diff --git a/apps/control-station/test/roverLocalEvidence.test.mjs b/apps/control-station/test/roverLocalEvidence.test.mjs new file mode 100644 index 00000000..0f7a5046 --- /dev/null +++ b/apps/control-station/test/roverLocalEvidence.test.mjs @@ -0,0 +1,54 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({stdin:{contents:"export * from './roverDevEvents'; export * from './roverTransport';",resolveDir:new URL('../src/core/fleet/',import.meta.url).pathname,loader:'ts'},bundle:true,write:false,platform:'node',format:'esm'}); +const {BrowserEvidence,connectRoverEvidence,roverDevEvent,RoverTransport}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +test('local browser events use only the operator-host endpoint while remote DEV is disabled',async()=>{ + const previous=globalThis.fetch,calls=[];globalThis.fetch=async(url,options)=>{calls.push({url,body:JSON.parse(options.body)});return {ok:true,json:async()=>({accepted:true})};}; + const capture=connectRoverEvidence('/api/v1/fleet/fixture/rover'); + try{capture.set(null,'local');roverDevEvent('/api/v1/fleet/fixture/rover','request',{request_id:8,sequence:12}); + await new Promise(r=>setTimeout(r,300));assert.equal(calls.length,1); + assert.equal(calls[0].url,'/api/v1/fleet/fixture/rover/diagnostics/local/events'); + assert.equal(calls[0].body.events[0].reason,'local_capture_attached');assert.equal(calls[0].body.id,'local');assert.equal(calls[0].body.events.find(e=>e.event==='request').request_id,8); + }finally{capture.close();globalThis.fetch=previous;} +}); +test('failed local transfers are bounded and never count a retry as a lost event',async()=>{ + const old=globalThis.fetch;globalThis.fetch=async()=>{throw Error('offline');}; + try{const e=new BrowserEvidence('/local',true);e.set('a');for(let n=0;n<300;n++)e.record('request',{sequence:n}); + assert.equal(e.rows.length,256);assert.equal(e.dropped,44);await e.flush(); + assert.equal(e.rows.length,256);assert.equal(e.dropped,44); + e.set('b');assert.equal(e.rows.length,0); + }finally{globalThis.fetch=old;} +}); +test('old in-flight reply cannot disable or prepend rows to a newer capture',async()=>{ + const old=globalThis.fetch;let done;globalThis.fetch=()=>new Promise(r=>done=r); + try{const e=new BrowserEvidence('/local',true);e.set('a');e.record('request');const f=e.flush(); + e.set('b');e.record('request',{sequence:2});done({ok:true,json:async()=>({accepted:false})});await f; + assert.equal(e.id,'b');assert.equal(e.rows[0].sequence,2); + }finally{globalThis.fetch=old;} +}); +test('closed local capture stops ingestion and oversized events are not retained',async()=>{ + const old=globalThis.fetch;globalThis.fetch=async()=>({ok:true,json:async()=>({accepted:false})}); + try{const e=new BrowserEvidence('/local',true);e.set('a');e.record('request',{reason:'x'.repeat(3000)}); + assert.equal(e.rows.length,0);assert.equal(e.dropped,1);e.record('request');await e.flush();assert.equal(e.id,null); + }finally{globalThis.fetch=old;} +}); + +test('send and ack correlate with Core socket identity without altering the command envelope',async()=>{ + const oldFetch=globalThis.fetch,oldWindow=globalThis.window,calls=[]; + globalThis.window={location:{href:'http://127.0.0.1:8000/'}}; + globalThis.fetch=async(url,options)=>{calls.push(JSON.parse(options.body));return {ok:true,json:async()=>({accepted:true})};}; + let socket; + const capture=connectRoverEvidence('/api/v1/fleet/fixture/rover');capture.set(null,'local'); + const transport=new RoverTransport('/api/v1/fleet/fixture/rover',()=>socket={readyState:1,bufferedAmount:0,sent:[],send(raw){this.sent.push(JSON.parse(raw));},close(){}}); + try{ + socket.onmessage({data:JSON.stringify({type:'state',socket_id:'core-socket',clock_ms:1000,value:{fresh:true}})}); + const p=transport.command('command',{session_id:'session',sequence:3,left:0,right:0}); + assert.deepEqual(Object.keys(socket.sent[0]).sort(),['action','body','expires_ms','id']); + socket.onmessage({data:JSON.stringify({type:'reply',socket_id:'core-socket',id:socket.sent[0].id,value:{accepted_sequence:3}})}); + assert.equal((await p).accepted_sequence,3);await new Promise(r=>setTimeout(r,300)); + const rows=calls.flatMap(v=>v.events),sent=rows.find(r=>r.reason==='socket_send'),ack=rows.find(r=>r.reason==='reply_received'); + assert.equal(sent.sequence,3);assert.equal(sent.session_id,'session'); + assert.equal(sent.socket_id,ack.socket_id);assert.equal(sent.request_id,ack.request_id); + }finally{transport.close();capture.close();globalThis.fetch=oldFetch;globalThis.window=oldWindow;} +}); diff --git a/apps/control-station/test/roverLogSave.test.mjs b/apps/control-station/test/roverLogSave.test.mjs new file mode 100644 index 00000000..422cf10b --- /dev/null +++ b/apps/control-station/test/roverLogSave.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash,webcrypto} from 'node:crypto'; +import {build} from 'esbuild'; +const result=await build({stdin:{contents:"export * from './src/core/fleet/roverLogSave';export * from './src/core/fleet/roverLogTransfer';",resolveDir:process.cwd()},bundle:true,write:false,platform:'node',format:'esm'}); +const {saveRoverLog,readLogBlocks,transferRoverLog}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +if(!globalThis.crypto)globalThis.crypto=webcrypto; +const frame=(raw,offset=0,total=raw.length,extra={})=>JSON.stringify({capture_id:'a'.repeat(32),snapshot:'b'.repeat(64),offset,next:offset+raw.length,total_bytes:total,data:Buffer.from(raw).toString('base64'),sha256:createHash('sha256').update(raw).digest('hex'),...extra})+'\n'; + +test('save opens native chooser before network; closes only a verified complete file',async()=>{ + const oldWindow=globalThis.window,oldFetch=globalThis.fetch;const actions=[],chunks=[]; + globalThis.window={showSaveFilePicker:async(options)=>{actions.push(['picker',options.suggestedName]);return {createWritable:async()=>({write:async c=>chunks.push(Buffer.from(c)),close:async()=>actions.push(['closed']),abort:async()=>actions.push(['aborted'])})};}}; + globalThis.fetch=async url=>{actions.push(['fetch',url]);return new Response(frame('manifest\nrow1\nrow2\n'));}; + try{await saveRoverLog('/rover','session.jsonl');assert.deepEqual(actions,[['picker','session.jsonl'],['fetch','/rover/diagnostics/export?format=chunks'],['closed']]);assert.equal(Buffer.concat(chunks).toString(),'manifest\nrow1\nrow2\n');} + finally{globalThis.window=oldWindow;globalThis.fetch=oldFetch;} +}); +test('cancelled save dialog makes no export request',async()=>{ + const oldWindow=globalThis.window,oldFetch=globalThis.fetch; + globalThis.window={showSaveFilePicker:async()=>{throw new DOMException('cancel','AbortError');}}; + globalThis.fetch=()=>{throw Error('must not fetch');}; + try{await assert.rejects(saveRoverLog('/rover','session.jsonl'),{name:'AbortError'});} + finally{globalThis.window=oldWindow;globalThis.fetch=oldFetch;} +}); +test('interrupted response resumes exact snapshot after last verified written block',async()=>{ + const oldFetch=globalThis.fetch,urls=[],bytes=[]; + globalThis.fetch=async url=>{urls.push(url);return new Response(urls.length===1?frame('abc',0,6)+'{"partial":':frame('def',3,6));}; + try{ + await transferRoverLog('/rover',async data=>bytes.push(Buffer.from(data))); + assert.equal(Buffer.concat(bytes).toString(),'abcdef');assert.equal(urls.length,2); + const resumed=new URL(urls[1],'http://test').searchParams; + assert.equal(resumed.get('offset'),'3');assert.equal(resumed.get('total_bytes'),'6'); + assert.equal(resumed.get('snapshot'),'b'.repeat(64));assert.equal(resumed.get('capture_id'),'a'.repeat(32)); + }finally{globalThis.fetch=oldFetch;} +}); +test('corruption, identity drift, duplicates, oversize and early EOF never confirm bad bytes',async()=>{ + const cursor={capture_id:'a'.repeat(32),snapshot:'b'.repeat(64),total_bytes:6,offset:3}; + for(const text of [frame('def',3,6,{sha256:'0'.repeat(64)}),frame('def',3,6,{snapshot:'c'.repeat(64)}),frame('abc',0,6),frame('def',3,7),frame('x'.repeat(65537),3,65540),'x'.repeat(110000)]){ + let written=0;await assert.rejects(readLogBlocks(new Response(text),cursor,async()=>written++,()=>{}));assert.equal(written,0); + } + await assert.rejects(readLogBlocks(new Response(frame('abc',0,6)),undefined,async()=>{},()=>{})); +}); +test('HTTP segmentation, including split JSON lines, does not change file bytes',async()=>{ + const encoded=new TextEncoder().encode(frame('abc',0,6)+frame('def',3,6)),written=[]; + const response=new Response(new ReadableStream({start(c){for(let i=0;iwritten.push(Buffer.from(b)),()=>{}); + assert.equal(Buffer.concat(written).toString(),'abcdef'); +}); diff --git a/apps/control-station/test/roverObservationLifecycle.test.mjs b/apps/control-station/test/roverObservationLifecycle.test.mjs new file mode 100644 index 00000000..a5dca104 --- /dev/null +++ b/apps/control-station/test/roverObservationLifecycle.test.mjs @@ -0,0 +1,153 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {build} from 'esbuild'; + +// Real UI composition, with fixture transports/renderers. No hardware access. +async function component(relative, overrides={}) { + const path=new URL(relative,import.meta.url).pathname,source=readFileSync(path,'utf8'); + const imports=new Map([...source.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g)].map(([,names,path])=>[path,names.split(',').map(n=>n.trim()).filter(n=>!n.startsWith('type '))])); + const result=await build({entryPoints:[path],bundle:true,write:false,platform:'node',format:'esm',jsx:'automatic',plugins:[{name:'component-fixture',setup(b){ + b.onResolve({filter:/.*/},a=>a.kind==='entry-point'?undefined:{path:a.path,namespace:'fixture'}); + b.onLoad({filter:/.*/,namespace:'fixture'},({path})=>{ + if(path==='react/jsx-runtime')return {contents:'export const Fragment="Fragment";export const jsx=(type,props)=>({type,props});export const jsxs=jsx;'}; + if(path==='react')return {contents:`export const useState=v=>globalThis.roverUI.state(v),useRef=v=>globalThis.roverUI.ref(v),useEffect=(f,d)=>globalThis.roverUI.effect(f,d),useLayoutEffect=useEffect,useCallback=f=>f,useMemo=f=>f(),lazy=()=>"Lazy",Suspense="Suspense";`}; + if(path==='react-dom')return {contents:'export const createPortal=(children,target)=>({type:"Portal",props:{children,target}});'}; + return {contents:overrides[path]??(imports.get(path)??[]).map(name=>`export const ${name}=${JSON.stringify(name)};`).join('\n')}; + }); + }}]}); + return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +} +const {VehiclesWorkspace}=await component('../src/workspaces/fleet/VehiclesWorkspace.tsx',{ + '../../core/fleet/useFleet':'export const useFleet=()=>globalThis.roverUI.fleet;export const fleetRequest=()=>{};', + './NodeInvitationForm':'export const NodeInvitationForm="NodeInvitationForm",platformLabel=()=>"UGV";', +}); +const {BoardObservationCenter}=await component('../src/workspaces/fleet/observation/BoardObservationCenter.tsx',{ + '../../../core/device-plugins/DevicePluginHost':'export const useDevicePluginHost=()=>({registry:{sensorContributions:[]}});', + '../../../core/fleet/sensorTransport':'export const createFleetSensorTransport=()=>({});', + '../../../core/fleet/useVehicleObservation':'export const useVehicleObservation=()=>globalThis.roverUI.presets;', + '../../../core/fleet/observationLayout':'export const orderedObservationIDs=(_,ids)=>ids;export const moveObservation=()=>{},withObservationTree=()=>{},observationTree=()=>{};', + '../../../core/fleet/observationPresets':'export const observationArrangements=[],retainDormantObservationTree=()=>{};', + '../../../../../../packages/sensor-ui/src/observation':'export const cameraObservationViews=()=>[],observationKey=(d,v)=>d+v;', + '../../../../../../packages/sensor-ui/src/observationCatalog':'export const unboundObservationViews=()=>[];', + './useObservationInventory':'export const useObservationInventory=()=>globalThis.roverUI.inventory;', + '../../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});', + '../../../core/fleet/useRoverControl':'export const useRoverControl=(id,visible)=>{globalThis.roverUI.watches.push({id,visible});return {state:{fresh:true,snapshot:{}},stop:()=>{}};};', + '../../../core/fleet/useRoverDiagnostics':'export const useRoverDiagnostics=()=>({state:{active:false,closing:false}});', + '../../../components/rover/RoverTelemetry':'export const RoverTelemetry="RoverTelemetry",roverTelemetryMinimum=()=>({width:1,height:1});', +}); +const {RoverView}=await component('../src/components/rover/RoverView.tsx',{ + '../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});', + '../../core/fleet/roverInput':'export const keysFor=()=>[],roverSettings=()=>({mode:"tank",model:"",currentA:34.5,throttlePercent:20}),persistableRoverSettings=()=>false,roverNumberInput=Number;', + '../../core/fleet/roverDevEvents':'export const roverDevEvent=()=>{};', + '../../core/fleet/roverHoldInput':'export const bindRoverHoldInput=scope=>{globalThis.roverUI.inputScope=scope;return ({valid:()=>true,dispose:()=>{}});};', +}); +function find(tree,predicate){if(!tree||typeof tree!=='object')return; if(Array.isArray(tree)){for(const node of tree){const found=find(node,predicate);if(found)return found;}return;}if(predicate(tree))return tree;return find(tree.props?.children,predicate);} +function harness(){ + let slots=[],cursor=0,effects=[];const h={ + state(initial){const i=cursor++;if(!(i in slots))slots[i]=typeof initial==='function'?initial():initial;return [slots[i],v=>{slots[i]=typeof v==='function'?v(slots[i]):v;}];}, + ref(v){const i=cursor++;return slots[i]??={current:v};}, + effect(fn,deps){const i=cursor++,old=slots[i];if(!old||deps.some((v,j)=>!Object.is(v,old.deps[j])))effects.push(()=>{old?.cleanup?.();slots[i]={deps,cleanup:fn()};});}, + render(fn,props={}){cursor=0;return fn(props);}, + commit(){const list=effects;effects=[];list.forEach(f=>f());}, + reset(){slots=[];cursor=0;effects=[];}, + watches:[],presets:{layout:{hidden:[],layers:{}},presets:[],cameras:{},ready:true,setLayout(){}},inventory:{fresh:true,items:[]}, + };return h; +} +async function fixture(run){ + const keys=['roverUI','document','localStorage','requestAnimationFrame','cancelAnimationFrame'];const originals=new Map(keys.map(k=>[k,globalThis[k]])); + const h=harness(),frames=new Map();let frame=0; + globalThis.roverUI=h;globalThis.document={hidden:false,hasFocus:()=>true,querySelector:()=>null,createElement:()=>({append(){},remove(){}})}; + globalThis.localStorage={getItem:()=>null};globalThis.requestAnimationFrame=f=>{frames.set(++frame,f);return frame;};globalThis.cancelAnimationFrame=i=>frames.delete(i); + h.frame=()=>{const list=[...frames.values()];frames.clear();list.forEach(f=>f());}; + try{await run(h);}finally{for(const [key,value]of originals){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}} +} +test('registry error/offline cannot disable independently live rover channel; revocation still does',async()=>fixture(async h=>{ + const vehicle={id:'test-rover',name:'fixture',enrollment:'paired',connectivity:'online',platform:'ugv'};h.fleet={items:[vehicle],error:null}; + let tree=h.render(VehiclesWorkspace);find(tree,n=>n.type==='VehicleFleetRow').props.onObserve(); + const cases=[{error:null,connectivity:'online',paired:true},{error:'SSE failed',connectivity:'online',paired:true},{error:null,connectivity:'offline',paired:true},{error:null,connectivity:'online',paired:false}]; + const props=[]; + for(const c of cases){h.fleet.error=c.error;vehicle.connectivity=c.connectivity;vehicle.enrollment=c.paired?'paired':'revoked';tree=h.render(VehiclesWorkspace);props.push(find(tree,n=>n.type==='BoardObservationCenter').props);} + h.reset(); + for(let i=0;in.type==='StatusBadge').props.children,'Нет свежих сведений об оборудовании');assert.ok(find(tree,n=>n.type==='RoverTelemetry'));} + } +})); +test('hiding both rover panels releases channel independently of metadata',async()=>fixture(async h=>{ + const props={vehicleID:'fixture',name:'fixture',enabled:false,paired:true}; + for(const hidden of [[],['rover'],['telemetry'],['rover','telemetry']]){h.presets.layout.hidden=hidden;h.render(BoardObservationCenter,props);assert.equal(h.watches.at(-1).visible,hidden.length<2);} +})); +function controller(){return {connection:"connected",state:{fresh:true,snapshot:{supported:true}},controlMode:'duty',canArm:true,armed:false,ready:false,stop(){},setInputGuard(){},pauseInput(){},arm:async()=>true};} +test('verified initialization pulses the existing lamp and blocks arm without closing settings',async()=>fixture(async h=>{ + const props={vehicleID:'fixture',controller:controller(),header:{actionsTarget:{},statusTarget:{}},active:true,observation:{label:'Инициализация VESC',pulse:true}}; + const tree=h.render(RoverView,props); + assert.equal(find(tree,n=>n.type==='StatusBadge'&&n.props.variant==='indicator').props.pulse,true); + assert.equal(find(tree,n=>n.type==='h3').props.children,'Инициализация VESC'); + assert.equal(find(tree,n=>n.type==='Button'&&n.props.children==='Включить управление').props.disabled,true); + assert.equal(find(tree,n=>n.type==='IconButton'&&n.props.label==='Настройки управления ровером').props.disabled,undefined); +})); +async function armFixture(h,c,onFocus){ + const props={vehicleID:'fixture',controller:c,header:{actionsTarget:{},statusTarget:{}},active:true}; + let tree=h.render(RoverView,props);find(tree,n=>n.props?.className==='rover-view').props.ref.current={focus:onFocus,closest:()=>h.observationScope};h.commit(); + find(tree,n=>n.type==='IconButton'&&n.props.label==='Включить управление').props.onClick();tree=h.render(RoverView,props);h.commit(); + await find(tree,n=>n.type==='Button'&&n.props.children==='Включить управление').props.onClick(); + return props; +} +test('successful arm transfers focus after modal close; no repeat focus on telemetry updates',async()=>fixture(async h=>{ + const c=controller();let focused='opener';const props=await armFixture(h,c,()=>{focused='stage';}); + assert.equal(focused,'opener','must not focus under the open modal');c.armed=true;h.render(RoverView,props);h.commit(); + focused='modal-restored-opener';h.frame();assert.equal(focused,'stage'); + focused='another-panel';c.ready=true;h.render(RoverView,props);h.frame();assert.equal(focused,'another-panel'); +})); +test('delayed focus handoff does not steal focus from another window or dialog',async()=>{ + for(const blocked of ['hidden','blurred','dialog'])await fixture(async h=>{ + let calls=0;const props=await armFixture(h,controller(),()=>calls++);h.render(RoverView,props);h.commit(); + if(blocked==='hidden')document.hidden=true;if(blocked==='blurred')document.hasFocus=()=>false;if(blocked==='dialog')document.querySelector=()=>({}); + h.frame();assert.equal(calls,0); + }); +}); + +test('ready binding belongs to the observation center and header owns Play/Stop/status',async()=>fixture(async h=>{ + const c=controller();let stops=0;c.stop=()=>stops++; + h.observationScope={id:'observation'}; + const props=await armFixture(h,c,()=>{});c.ready=true;c.armed=true;c.state.snapshot.state='ready'; + const tree=h.render(RoverView,props);h.commit(); + assert.equal(h.inputScope,h.observationScope); + const action=find(tree,n=>n.type==='IconButton'&&n.props.label==='Остановить управление'); + assert.equal(action.props['aria-pressed'],true);assert.equal(action.props.children.props.name,'stop'); + assert.equal(find(tree,n=>n.type==='h3').props.children,'Управление вкл'); + assert.equal(find(tree,n=>n.props?.className==='rover-view__status'),undefined); + assert.equal(find(tree,n=>n.props?.className==='rover-view__authority'),undefined); + const before=stops;action.props.onClick();assert.equal(stops,before+1); +})); + +const {RoverDevWindow}=await component('../src/components/rover/RoverDevWindow.tsx',{ + '../../core/fleet/useRoverDiagnostics':'export const localDevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};', +}); +test('DEV opens configuration without beginning capture or retaining driving focus',async()=>fixture(async h=>{ + const props={vehicleID:'fixture',name:'fixture',paired:true,enabled:true}; + let tree=h.render(BoardObservationCenter,props); + assert.equal(find(tree,n=>n.type==='RoverDevWindow'),undefined); + find(tree,n=>n.type==='IconButton'&&n.props.label==='Включить DEV-запись').props.onClick(); + tree=h.render(BoardObservationCenter,props); + assert.ok(find(tree,n=>n.type==='RoverDevWindow')); + assert.equal(find(tree,n=>n.type==='RoverView').props.active,false); +})); +test('DEV defaults to board-only rows; options are explicit and start is capability gated',async()=>fixture(async h=>{ + const calls=[];let closed=0,started=0; + const capture={state:{options_supported:false},pending:false,toggle:async options=>{calls.push(options);return true;}}; + const props={capture,close:()=>closed++,started:()=>started++}; + let tree=h.render(RoverDevWindow,props); + assert.equal(find(tree.props.footer,n=>n.type==='Button'&&n.props.children==='Начать запись').props.disabled,true); + assert.equal(find(tree,n=>n.type==='Switch'&&n.props.label==='Показывать события онлайн').props.checked,false); + assert.equal(find(tree,n=>n.type==='Switch'&&n.props.label==='Добавлять события Core и браузера').props.checked,false); + tree.props.onClose();assert.equal(calls.length,0);assert.equal(closed,1); + capture.state.options_supported=true;tree=h.render(RoverDevWindow,props); + find(tree,n=>n.type==='Switch'&&n.props.label==='Подробные замеры моторов').props.onChange(false); + tree=h.render(RoverDevWindow,props); + find(tree.props.footer,n=>n.type==='Button'&&n.props.children==='Начать запись').props.onClick(); + await new Promise(resolve=>setImmediate(resolve)); + assert.deepEqual(calls,[{live:false,core_trace:false,motor_samples:false,network:true,live_kbps:16,core_kbps:16}]); + assert.equal(started,1);assert.equal(closed,2); +})); diff --git a/apps/control-station/test/roverObservationStatus.test.mjs b/apps/control-station/test/roverObservationStatus.test.mjs new file mode 100644 index 00000000..472fd43a --- /dev/null +++ b/apps/control-station/test/roverObservationStatus.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const built=await build({entryPoints:[new URL('../src/core/fleet/roverObservation.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {roverObservationStatus:status}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64')); +const empty={fresh:false,controlling:false,snapshot:{}}; +const board={fresh:true,controlling:false,snapshot:{supported:true,state:'observing',devices:[],profile:{bindings:{left:{device_id:'motor',uuid:'abc'}}}}}; +const initializing={...board,snapshot:{...board.snapshot,observation:{initializing_devices:['motor']}}}; +test('connecting to Core is different from receiving no fresh board telemetry',()=>{ + assert.equal(status(empty,'connecting').label,'Подключение к Mission Core'); + assert.equal(status(empty,'reconnecting').label,'Восстановление связи с Mission Core'); + assert.equal(status(empty,'connected').label,'Ожидание телеметрии с борта'); + assert.equal(status(empty,'connected').pulse,true); +}); +test('initialization requires a fresh explicit driver phase for every missing VESC',()=>{ + assert.deepEqual(status(initializing,'connected'),{label:'Инициализация VESC',pulse:true}); + for(const value of [board,{...initializing,fresh:false},{...board,snapshot:{...board.snapshot,observation:{initializing_devices:['other']}}}]){ + assert.notEqual(status(value,'connected').label,'Инициализация VESC'); + } +}); +test('ready readings end initialization; stale readings and actual faults cannot inherit it',()=>{ + const ready={...board,snapshot:{...board.snapshot,devices:[{id:'motor',uuid:'abc',age_ms:0}]}}; + assert.deepEqual(status(ready,'connected'),{label:null,pulse:false}); + assert.equal(status({...ready,snapshot:{...ready.snapshot,devices:[{id:'motor',uuid:'abc',age_ms:1000}]}},'connected').label,'Ожидание свежих показаний VESC'); + assert.deepEqual(status({...board,snapshot:{...board.snapshot,state:'fault',message:'Hardware failure'}},'connected'),{label:null,pulse:false}); + assert.equal(status({...board,snapshot:{}},'connected').pulse,false); +}); diff --git a/apps/control-station/test/roverOperatorCapture.test.mjs b/apps/control-station/test/roverOperatorCapture.test.mjs new file mode 100644 index 00000000..bdb77d7f --- /dev/null +++ b/apps/control-station/test/roverOperatorCapture.test.mjs @@ -0,0 +1,33 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const compiled=await build({stdin:{contents:"export * from './roverOperatorCapture';export * from './roverDevEvents';",resolveDir:new URL('../src/core/fleet/',import.meta.url).pathname,loader:'ts'},bundle:true,write:false,platform:'node',format:'esm'}); +const {saveOperatorCapture,connectRoverEvidence,roverPreviewEvidence}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64')); +test('local export flushes before requesting only Core and downloads the bounded snapshot',async()=>{ + const priorDocument=globalThis.document,priorFetch=globalThis.fetch,steps=[]; + let anchor; + globalThis.document={body:{append:a=>{anchor=a;steps.push('append');}},createElement:tag=>{assert.equal(tag,'a');return {click:()=>steps.push('click'),remove:()=>steps.push('remove')};}}; + globalThis.fetch=async(url)=>{assert.equal(url,'/rover/diagnostics/local/export?capture_id='+'a'.repeat(32));steps.push('fetch');return {ok:true,blob:async()=>new Blob(['sample'])};}; + try{await saveOperatorCapture('/rover','a'.repeat(32),async()=>steps.push('flush'));assert.deepEqual(steps,['flush','fetch','append','click','remove']);assert.equal(anchor.download,'rover-operator-'+ 'a'.repeat(32)+'.jsonl');assert.match(anchor.href,/^blob:/);} + finally{globalThis.document=priorDocument;globalThis.fetch=priorFetch;} +}); +test('invalid, failed and oversized exports never initiate a download or board request',async()=>{ + const priorDocument=globalThis.document,priorFetch=globalThis.fetch;let fetched=false; + globalThis.document={createElement:()=>{throw Error('must not download failed export');}}; + globalThis.fetch=async(url)=>{assert.ok(url.includes('/diagnostics/local/export'));fetched=true;return {ok:false};}; + try{await assert.rejects(saveOperatorCapture('/rover','invalid'),/изменилась/);assert.equal(fetched,false); + await assert.rejects(saveOperatorCapture('/rover','a'.repeat(32)),/выгрузить/);assert.equal(fetched,true); + globalThis.fetch=async()=>({ok:true,blob:async()=>new Blob([new Uint8Array(4*1024*1024+1)])}); + await assert.rejects(saveOperatorCapture('/rover','a'.repeat(32)),/Размер/); + }finally{globalThis.document=priorDocument;globalThis.fetch=priorFetch;} +}); +test('preview checkbox independently excludes metrics from both routes',async()=>{ + const previous=globalThis.fetch,calls=[]; + globalThis.fetch=async(url,options)=>{calls.push({url,body:JSON.parse(options.body)});return {ok:true,json:async()=>({accepted:true})};}; + const capture=connectRoverEvidence('/rover'); + try{capture.set('remote','local',false);roverPreviewEvidence('/rover',{encoder_bps:100});await capture.flush(); + assert.ok(!calls.flatMap(x=>x.body.events).some(x=>x.event==='preview')); + capture.set('remote','local',true);roverPreviewEvidence('/rover',{encoder_bps:101});await capture.flush(); + const entries=calls.filter(x=>x.body.events.some(y=>y.event==='preview'));assert.equal(entries.length,1);assert.equal(entries[0].url,'/rover/diagnostics/local/events'); + }finally{capture.close();globalThis.fetch=previous;} +}); diff --git a/apps/control-station/test/roverRecovery.test.mjs b/apps/control-station/test/roverRecovery.test.mjs new file mode 100644 index 00000000..09834669 --- /dev/null +++ b/apps/control-station/test/roverRecovery.test.mjs @@ -0,0 +1,162 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const settings={currentA:30,speed:70,mode:'duty'}; +const stopped={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'boot-A',state:'stopped',session_id:'old-session',release_confirmed:true,profile:{layout:'1x1',bindings:{left:{uuid:'left'},right:{uuid:'right'}}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}}; +function recovery(){const r=new RoverRecovery();r.remember(settings,stopped);r.interrupt(0,'old-session');return r;} +const change=patch=>({...stopped,snapshot:{...stopped.snapshot,...patch}}); +test('recovery requires consecutive fresh stopped evidence and preserves exact settings',()=>{ + const r=recovery();assert.equal(r.next(stopped,0,true),null); + assert.equal(r.next(stopped,499,true),null);assert.deepEqual(r.next(stopped,500,true),settings); + assert.equal(r.next(stopped,600,true),null);assert.equal(r.next(stopped,1200,true),null); + assert.deepEqual(r.next(stopped,1500,true),settings,'retry delay is bounded and increases'); +}); +test('no retry with stale telemetry, moving/stale/faulted motors, missing devices or hidden UI',()=>{ + for(const bad of [{...stopped,fresh:false},change({state:'stopping'}),...['age_ms','erpm','fault_code'].map(k=>change({devices:stopped.snapshot.devices.map(d=>({...d,age_ms:k==='age_ms'?501:10,values:{...d.values,[k]:k==='erpm'?60:1}}))}))]){ + const r=recovery();r.next(stopped,0,true);assert.equal(r.next(bad,600,true),null);assert.equal(r.next(stopped,700,true),null);assert.deepEqual(r.next(stopped,1200,true),settings); + } + const r=recovery();r.next(stopped,0,true);assert.equal(r.next(stopped,600,false),null);assert.equal(r.next(stopped,700,true),null); +}); +test('restart, motor reassignment, RC, hardware fault and another owner prohibit recovery',()=>{ + for(const bad of [change({devices:[]}),change({instance:'boot-B'}),change({profile:{layout:'2x2'}}),change({state:'receiver'}),change({state:'fault'}),change({release_confirmed:false}),change({control_modes:['rpm']}),{...change({session_id:'other-session'}),controlling:true}]){ + const r=recovery();assert.ok(r.blocker(bad));assert.equal(r.next(bad,9000,true),null); + } +}); +test('newly acquired own session is not mistaken for another operator',()=>{ + const r=recovery(),v={...change({session_id:'new-session',state:'preparing'}),controlling:true}; + assert.equal(r.blocker(v,'new-session'),null);assert.ok(r.blocker(v));r.connected(1000);assert.equal(r.waiting,false);assert.equal(r.next(stopped,9000,true),null); +}); +test('explicit Stop and reload cannot restore an old request',()=>{ + const r=recovery();r.clear();assert.equal(r.next(stopped,9000,true),null);assert.equal(r.interrupt(10000,'old-session'),false); + assert.equal(new RoverRecovery().next(stopped,9000,true),null); +}); +test('unconfirmed stopping waits without cancelling request; settled stop starts a fresh quiet interval',()=>{ + const r=recovery(),pending=change({state:'stopping',release_confirmed:false,message:'Release not yet observed',last_stop:{session_id:'old-session',state:'stopping',message:'Release not yet observed'}}); + for(const at of [0,500,2000,60000]){ + assert.equal(r.blocker(pending),null); + assert.equal(r.next(pending,at,true),null,'pending release never grants authority'); + assert.equal(r.waiting,true); + } + const settled=change({last_stop:{...pending.snapshot.last_stop,recovered_at:'fixture'}}); + assert.equal(r.next(settled,60100,true),null); + assert.equal(r.next(settled,60599,true),null); + assert.deepEqual(r.next(settled,60600,true),settings); +}); +test('pending release never masks device faults, identity changes, receiver or explicit Stop',()=>{ + const pending=change({state:'stopping',release_confirmed:false}); + for(const bad of [change({state:'fault',release_confirmed:false}),change({state:'stopped',last_stop:{session_id:'old-session',state:'fault',message:'Hardware fault',recovered_at:'later'}}),change({state:'receiver'}),change({state:'stopping',instance:'other-boot'}),change({state:'stopping',devices:stopped.snapshot.devices.map(d=>({...d,session_id:'reattached'}))})]){ + const r=recovery();assert.equal(r.blocker(pending),null);assert.ok(r.blocker(bad));assert.equal(r.next(bad,90000,true),null); + } + const r=recovery();r.next(pending,0,true);r.clear();assert.equal(r.next(stopped,90000,true),null); +}); +test('a recovered neutral snapshot retains terminal history and cannot auto-rearm its failed session',()=>{ + const r=recovery(),settled=change({state:'stopped',message:null,last_stop:{session_id:'old-session',state:'fault',message:'USB lost',recovered_at:'fixture'}}); + assert.equal(r.blocker(settled),'USB lost');assert.equal(r.next(settled,9000,true),null); + r.remember(settings,settled);r.started('new-session'); + assert.equal(r.blocker({...change({state:'preparing',session_id:'new-session',last_stop:settled.snapshot.last_stop}),controlling:true},'new-session'),null); +}); +test('explicit retry can await its own preparation after a previous terminal fault',()=>{ + const failed=change({state:'fault',release_confirmed:false,message:'Old USB disconnect'}),r=new RoverRecovery(); + r.remember(settings,failed);r.started('new-session'); + assert.equal(r.blocker({...failed,controlling:true},'new-session'),null); + assert.ok(r.blocker(failed,'new-session'),'without a live Core lease the old fault still blocks'); + assert.ok(r.blocker({...failed,controlling:true,snapshot:{...failed.snapshot,instance:'boot-B'}},'new-session')); + const preparing={...change({session_id:'new-session',state:'preparing',release_confirmed:null}),controlling:true}; + assert.equal(r.blocker(preparing,'new-session'),null); + assert.ok(r.blocker({...failed,controlling:true},'new-session'),'after acknowledgement old states cannot be ignored'); + assert.ok(r.blocker({...preparing,snapshot:{...preparing.snapshot,state:'fault',message:'New failure'}},'new-session')); +}); +test('explicit retry never permits automatic recovery from unconfirmed release',()=>{ + const failed=change({state:'fault',release_confirmed:false}),r=new RoverRecovery(); + r.remember(settings,failed);r.started('new-session');r.interrupt(0,'new-session'); + assert.ok(r.blocker({...failed,controlling:true},'new-session')); + assert.equal(r.next(failed,9000,true),null); +}); + + +test('same UUID after USB reconnect requires explicit arm and never auto-recovers',()=>{ + const r=recovery(),reconnected=change({devices:stopped.snapshot.devices.map(d=>({...d,session_id:d.session_id+'-new'}))}); + assert.ok(r.blocker(reconnected));assert.equal(r.next(reconnected,9000,true),null); + const missing=change({devices:stopped.snapshot.devices.slice(0,1)});assert.ok(recovery().blocker(missing)); + assert.equal(r.next(stopped,15000,true),null); +}); +test('legacy snapshots without attachment sessions cannot opt into automatic recovery',()=>{ + const r=new RoverRecovery();r.remember(settings,change({devices:stopped.snapshot.devices.map(({session_id,...d})=>d)})); + assert.equal(r.interrupt(0,'old-session'),false); +}); + + +test('unknown release evidence never admits an automatic rearm',()=>{ + for(const release_confirmed of [null,undefined]){ + const r=recovery(),unknown=change({release_confirmed}); + assert.equal(r.next(unknown,0,true),null); + assert.equal(r.next(unknown,1000,true),null); + assert.equal(r.next(stopped,1100,true),null,'confirmed evidence starts its own quiet interval'); + assert.deepEqual(r.next(stopped,1600,true),settings); + } +}); +test('brief ready states cannot reset the automatic recovery budget',()=>{ + const r=recovery(); + for(let attempt=0;attempt<3;attempt++){ + const base=attempt*10000; + assert.equal(r.next(stopped,base,true),null); + assert.deepEqual(r.next(stopped,base+5000,true),settings); + r.connected(base+5100);r.connected(base+6000); + assert.equal(r.interrupt(base+7000,'session-'+attempt),true); + } + assert.equal(r.waiting,true,'backoff retains operator request'); + assert.equal(r.next(stopped,1000000,true),null,'first stopped observation alone cannot grant another lease'); + r.remember(settings,stopped); + assert.equal(r.waiting,false); + assert.equal(r.interrupt(1000100,'explicit-new'),true); +}); +test('only thirty seconds of continuously ready observation restores retry budget',()=>{ + const r=recovery();r.next(stopped,0,true);assert.deepEqual(r.next(stopped,500,true),settings); + for(let at=600;at<=30600;at+=200)r.connected(at); + assert.equal(r.interrupt(30700,'stable-session'),true); + for(let attempt=0;attempt<3;attempt++){ + const base=40000+attempt*10000; + assert.equal(r.next(stopped,base,true),null); + assert.deepEqual(r.next(stopped,base+5000,true),settings); + r.connected(base+5100); + assert.equal(r.interrupt(base+7000,'short-'+attempt),true); + } +}); +test('separate short connections cannot add up to a stable connection',()=>{ + const r=recovery(); + for(let attempt=0;attempt<3;attempt++){ + const base=attempt*50000; + assert.equal(r.next(stopped,base,true),null); + assert.deepEqual(r.next(stopped,base+5000,true),settings); + for(let at=base+5100;at<=base+34100;at+=200)r.connected(at); + assert.equal(r.interrupt(base+35000,'short-'+attempt),true); + } + assert.equal(r.waiting,true); +}); + + +test('a long unobserved gap cannot count as thirty seconds of stable connection',()=>{ + const r=recovery(); + for(let attempt=0;attempt<3;attempt++){ + const base=attempt*60000; + assert.equal(r.next(stopped,base,true),null); + assert.deepEqual(r.next(stopped,base+5000,true),settings); + r.connected(base+5100);r.connected(base+36000); + assert.equal(r.interrupt(base+37000,'gap-'+attempt),true); + } + assert.equal(r.waiting,true); +}); + + +test('retry admission without a start result remains delayed and never ends request',()=>{ + const r=recovery(); + for(let attempt=0;attempt<3;attempt++){ + const base=attempt*10000; + assert.equal(r.next(stopped,base,true),null); + assert.deepEqual(r.next(stopped,base+5000,true),settings); + } + assert.equal(r.next(stopped,30000,true),null); + assert.equal(r.waiting,true);assert.deepEqual(r.next(stopped,38000,true),settings,'capped retry preserves request'); +}); diff --git a/apps/control-station/test/roverRecoveryContinuity.test.mjs b/apps/control-station/test/roverRecoveryContinuity.test.mjs new file mode 100644 index 00000000..5fc07fcc --- /dev/null +++ b/apps/control-station/test/roverRecoveryContinuity.test.mjs @@ -0,0 +1,50 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +const settings={currentA:30,speed:70,mode:'duty'}; +const stopped={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'boot-A',state:'stopped',session_id:'old-session',release_confirmed:true,profile:{layout:'1x1',bindings:{left:{uuid:'left'},right:{uuid:'right'}}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}}; +function recovery(){const r=new RoverRecovery();r.remember(settings,stopped);r.interrupt(0,'old-session');return r;} +const change=patch=>({...stopped,snapshot:{...stopped.snapshot,...patch}}); +// Owner amendment 2026-10-27: retain operator intent through transport faults. +// These are additional cases; pre-existing safety regressions stay in place. +test('repeated transport faults retain request with bounded retry frequency',()=>{ + const r=recovery(),admissions=[]; + for(let at=0;at<=60000;at+=100){ + if(r.next(stopped,at,true)){ + admissions.push(at);r.connected(at+1);assert.equal(r.interrupt(at+2,'session-'+at),true); + } + } + assert.ok(admissions.length>=5&&admissions.length<=11); + for(let i=1;i=Math.min(8000,1000*2**Math.min(i-1,3))); + assert.equal(r.waiting,true,'network retries cannot erase the operator request'); +}); +test('thirty seconds of observed ready resets backoff; short connections do not',()=>{ + const r=recovery();r.next(stopped,0,true);assert.deepEqual(r.next(stopped,500,true),settings); + r.connected(501);r.interrupt(502,'short');r.next(stopped,503,true); + assert.equal(r.next(stopped,1003,true),null,'brief readiness must not bypass backoff'); + assert.deepEqual(r.next(stopped,1500,true),settings); + for(let at=1600;at<=31600;at+=200)r.connected(at); + r.interrupt(31700,'stable');r.next(stopped,31700,true); + assert.deepEqual(r.next(stopped,32200,true),settings); +}); +test('long total outage creates no arm attempts and preserves original settings',()=>{ + const r=recovery(); + for(let at=0;at<600000;at+=200)assert.equal(r.next({fresh:false,controlling:false,snapshot:{}},at,true),null); + assert.equal(r.waiting,true); + assert.equal(r.next(stopped,600000,true),null);assert.deepEqual(r.next(stopped,600500,true),settings); + r.clear();assert.equal(r.next(stopped,900000,true),null,'explicit stop always cancels recovery'); +}); +test('failed admission stays rate bounded without ever getting a start result',()=>{ + const r=recovery(),admissions=[]; + for(let at=0;at<=60000;at+=100)if(r.next(stopped,at,true))admissions.push(at); + assert.equal(admissions.length,10);assert.equal(r.waiting,true); + assert.equal(r.next({...stopped,fresh:false},100000,true),null); +}); + +test('explicit new operator request does not inherit the old retry delay',()=>{ + const r=recovery();for(let at=0;at<=8000;at+=100)r.next(stopped,at,true); + r.clear();r.remember(settings,stopped);r.interrupt(8100,'explicit-new'); + assert.equal(r.next(stopped,8100,true),null);assert.deepEqual(r.next(stopped,8600,true),settings); +}); diff --git a/apps/control-station/test/roverStopRecoveryBench.test.mjs b/apps/control-station/test/roverStopRecoveryBench.test.mjs new file mode 100644 index 00000000..f94637b4 --- /dev/null +++ b/apps/control-station/test/roverStopRecoveryBench.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const compiled=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64')); +const settings={currentA:30,speed:70,mode:'duty'}; +const initial={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'stable-driver',state:'stopped',release_confirmed:true,session_id:null,profile:{layout:'1x1',bindings:{}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}}; + +test('ten consecutive network stops keep one operator request and never rearm before settled release',()=>{ + const r=new RoverRecovery();r.remember(settings,initial); + for(let run=0;run<10;run++){ + const id='session-'+run,at=run*20000; + r.started(id);r.connected(at);assert.equal(r.interrupt(at+100,id),true); + const stopping={...initial,snapshot:{...initial.snapshot,session_id:id,state:'stopping',release_confirmed:false,last_stop:{session_id:id,state:'stopping',message:'Release not yet observed'}}}; + for(let t=at+200;t{const s={url,readyState:1,bufferedAmount:0,sent:[],send(raw){this.sent.push(JSON.parse(raw));},close(){this.readyState=3;this.onclose?.();},message(value){this.onmessage?.({data:JSON.stringify(value)});}};sockets.push(s);return s;}); + const s=sockets[0],state={fresh:true,controlling:false,snapshot:{state:'observing'}}; + try{await run({transport,s,sockets,state,ready:()=>s.message({type:'state',clock_ms:10000,value:state})});}finally{transport.close();globalThis.window=previous;} +} +test('independent socket supplies state and acknowledgements without an HTTP fetch',async()=>fixture(async({transport,s,state,ready})=>{ + assert.equal(s.url,'ws://127.0.0.1:8000/api/v1/fleet/fixture/rover-channel'); + const pending=transport.view();ready();assert.deepEqual(await pending,state); + const result=transport.command('command',{sequence:1});assert.equal(s.sent.length,1);assert.ok(s.sent[0].expires_ms>=10400&&s.sent[0].expires_ms<10420); + s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:1}});assert.deepEqual(await result,{accepted_sequence:1}); +})); +test('unconfirmed connection and backpressure never queue a command',async()=>fixture(async({transport,s,ready})=>{ + await assert.rejects(transport.command('arm',{}));assert.equal(s.sent.length,0);ready();s.bufferedAmount=4097; + await assert.rejects(transport.command('command',{}));assert.equal(s.sent.length,0); +})); +test('disconnect rejects in-flight work and reconnect never replays it',async()=>fixture(async({transport,s,sockets,ready})=>{ + ready();const p=transport.command('command',{sequence:1});s.close();await assert.rejects(p); + await new Promise(resolve=>setTimeout(resolve,280));assert.equal(sockets.length,2);assert.equal(sockets[1].sent.length,0); + await assert.rejects(transport.command('command',{sequence:2}));assert.equal(sockets[1].sent.length,0); +})); +test('late replies cannot acknowledge a timed-out command',async()=>fixture(async({transport,s,ready})=>{ + ready();const p=transport.command('command',{sequence:1});await assert.rejects(p,/не подтверждена/); + s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:1}});assert.equal(s.sent.length,1); +})); +test('arm acknowledgement replaces the cached pre-arm view before caller can poll',async()=>fixture(async({transport,s,state,ready})=>{ + ready();assert.equal((await transport.view()).controlling,false); + const p=transport.command('arm',{}),postArm={...state,controlling:true}; + s.message({type:'reply',id:s.sent[0].id,value:{session_id:'new'},state:postArm,clock_ms:10002}); + assert.equal((await p).session_id,'new');assert.equal((await transport.view()).controlling,true); +})); + +test('neutral handoff is an explicit acknowledged owner action with a deadline',async()=>fixture(async({transport,s,ready})=>{ + ready();const p=transport.command('hold',{session_id:'owner',sequence:5}); + assert.equal(s.sent[0].action,'hold');assert.deepEqual(s.sent[0].body,{session_id:'owner',sequence:5}); + assert.ok(s.sent[0].expires_ms>=10400&&s.sent[0].expires_ms<10420); + s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:5}}); + assert.equal((await p).accepted_sequence,5); +})); + + +test('silent OPEN channel is retired and reconnect cannot replay commands',async()=>fixture(async({transport,s,sockets,ready})=>{ + ready();s.close=()=>{s.readyState=2;}; // Browser supplies no close callback. + await new Promise(resolve=>setTimeout(resolve,1790)); + assert.equal(sockets.length,2);assert.equal(s.readyState,2); + s.message({type:'state',clock_ms:1,value:{fresh:true}}); + await assert.rejects(transport.command('arm',{})); + assert.equal(sockets[1].sent.length,0); +})); + + + +test('each fresh sample keeps its own 400ms expiry with bounded in-flight work',async()=>fixture(async({transport,s,ready})=>{ + const original=globalThis.performance;let now=0;globalThis.performance={now:()=>now}; + const pending=[]; + try{ + ready(); + for(let sequence=1;sequence<=4;sequence++){now=(sequence-1)*50;pending.push(transport.command('command',{sequence,left:0,right:0}));} + assert.deepEqual(s.sent.map(x=>x.expires_ms),[10400,10450,10500,10550]); + now=200;await assert.rejects(transport.command('command',{sequence:5}));assert.equal(s.sent.length,4); + s.message({type:'reply',id:s.sent[3].id,value:{accepted_sequence:4}});await pending[3]; + pending.push(transport.command('command',{sequence:5,left:0,right:0})); + assert.equal(s.sent[4].expires_ms,10600);assert.equal(s.sent[0].expires_ms,10400,'new sample must not extend old frame'); + for(const frame of s.sent)s.message({type:'reply',id:frame.id,value:{accepted_sequence:frame.body.sequence}}); + await Promise.all(pending); + }finally{globalThis.performance=original;} +})); diff --git a/apps/control-station/test/roverTransportStartup.test.mjs b/apps/control-station/test/roverTransportStartup.test.mjs new file mode 100644 index 00000000..b2cbbee4 --- /dev/null +++ b/apps/control-station/test/roverTransportStartup.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const built=await build({entryPoints:[new URL('../src/core/fleet/roverTransport.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'}); +const {RoverTransport}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64')); + +// Deterministic browser handshake/scheduler, no network or motor commands. +async function fixture(run){ + const keys=['window','performance','setTimeout','clearTimeout'],previous=Object.fromEntries(keys.map(k=>[k,globalThis[k]])); + let now=0,next=0;const timers=new Map(),sockets=[]; + globalThis.window={location:{href:'http://127.0.0.1:8000/'}};globalThis.performance={now:()=>now}; + globalThis.setTimeout=(fn,ms)=>{const id=++next;timers.set(id,{fn,at:now+ms});return id;};globalThis.clearTimeout=id=>timers.delete(id); + const advance=ms=>{const end=now+ms;while(true){const item=[...timers].filter(([,t])=>t.at<=end).sort((a,b)=>a[1].at-b[1].at)[0];if(!item)break;now=item[1].at;timers.delete(item[0]);item[1].fn();}now=end;}; + const transport=new RoverTransport('/api/v1/fleet/fixture/rover',()=>{ + const socket={readyState:0,bufferedAmount:0,sent:[],send(raw){this.sent.push(raw);},close(){this.readyState=3;},open(){if(this.readyState!==0)return;this.readyState=1;this.onopen?.();},state(){this.onmessage?.({data:JSON.stringify({type:'state',clock_ms:10000+now,value:{fresh:true,controlling:false,snapshot:{state:'observing'}}})});}}; + sockets.push(socket);return socket; + }); + try{await run({transport,sockets,advance,timers});}finally{transport.close();for(const k of keys)globalThis[k]=previous[k];} +} + +test('a two-second initial handshake can finish without being killed by the live-state watchdog',async()=>fixture(async f=>{ + const first=f.sockets[0];f.advance(2000); + assert.equal(first.readyState,0,'handshake was cancelled before any live state existed'); + await assert.rejects(f.transport.command('arm',{}));assert.equal(first.sent.length,0); + first.open();first.state();assert.equal((await f.transport.view()).fresh,true); + assert.equal(f.sockets.length,1); +})); + +test('an opened socket without state still has the original 1.5-second watchdog',async()=>fixture(async f=>{ + f.sockets[0].open();f.advance(1500);assert.equal(f.sockets[0].readyState,3); + await assert.rejects(f.transport.command('arm',{})); + f.advance(250);assert.equal(f.sockets.length,2);assert.equal(f.sockets[1].sent.length,0); +})); + +test('a never-opening handshake has a bounded retry and close removes every timer',async()=>fixture(async f=>{ + f.advance(10250);assert.equal(f.sockets.length,2);assert.equal(f.sockets[0].readyState,3); + f.transport.close();assert.equal(f.timers.size,0);f.advance(30000);assert.equal(f.sockets.length,2); +})); + +for(let run=1;run<=10;run++)test(`startup/recovery cycle ${run}: delayed handshake, stale input refusal, new connection`,async()=>fixture(async f=>{ + const first=f.sockets[0];f.advance(1500+run*400);first.open();first.state(); + assert.equal((await f.transport.view()).fresh,true);assert.equal(f.sockets.length,1); + f.advance(601);await assert.rejects(f.transport.command('arm',{})); + f.advance(1149);assert.equal(f.sockets.length,2);assert.equal(first.readyState,3); + const second=f.sockets[1];f.advance(2000);second.open();second.state(); + assert.equal((await f.transport.view()).fresh,true); + assert.ok(f.sockets.every(s=>s.sent.length===0),'observation never sends a motor command'); + f.transport.close();assert.equal(f.timers.size,0); +})); diff --git a/apps/control-station/test/sensorTransportFreshness.test.mjs b/apps/control-station/test/sensorTransportFreshness.test.mjs new file mode 100644 index 00000000..b80adf6c --- /dev/null +++ b/apps/control-station/test/sensorTransportFreshness.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const result=await build({entryPoints:[new URL('../src/core/fleet/sensorTransport.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){ + b.onResolve({filter:/^\.\/useFleet$/},()=>({path:'fleet',namespace:'fixture'})); + b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:'export const fleetRequest=async()=>globalThis.sensorFleet;'})); +}}]}); +const {createFleetSensorTransport}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64')); +test('lightweight presence cannot make stale equipment writable for camera activation',async()=>{ + const previous=globalThis.sensorFleet; + try{ + const row={id:'rover',connectivity:'online',enrollment:'paired',inventory_fresh:false,sensor_state:{items:[],operations:[]}}; + globalThis.sensorFleet={items:[row]};const t=createFleetSensorTransport('rover'); + assert.equal((await t.inventory()).fresh,false);row.inventory_fresh=true;assert.equal((await t.inventory()).fresh,true); + row.enrollment='revoked';assert.equal((await t.inventory()).fresh,false); + }finally{if(previous===undefined)delete globalThis.sensorFleet;else globalThis.sensorFleet=previous;} +}); diff --git a/apps/node-agent/cmd/node-agent/main.go b/apps/node-agent/cmd/node-agent/main.go index c76dfebd..6c8b2482 100644 --- a/apps/node-agent/cmd/node-agent/main.go +++ b/apps/node-agent/cmd/node-agent/main.go @@ -18,6 +18,7 @@ import ( "time" "nodedc.local/mission-core/node-agent/internal/node" + "nodedc.local/mission-core/node-agent/internal/routers" "nodedc.local/mission-core/node-agent/web" ) @@ -69,6 +70,10 @@ func run() error { return err } app := &node.Server{Store: store, Assets: assets, Origin: "http://" + *listen, Version: version, Inventory: func() node.Inventory { return node.Host("/") }} + app.Budget, err = node.OpenLinkBudget(*dir) + if err != nil { + return err + } app.Monitor = node.NewMonitor() app.Presentation = node.NewPresentationStore(*dir) pairing, err := node.OpenPairing(store, *dir, version, app.Inventory) @@ -76,7 +81,9 @@ func run() error { return err } app.Pairing = pairing + pairing.Budget = app.Budget pairing.Monitor = app.Monitor + pairing.Routers = routers.Open(*dir) nodeID, _ := store.Public() app.Sensors, err = node.OpenSensors(*dir, nodeID) if err != nil { @@ -90,7 +97,7 @@ func run() error { pairing.DeviceEnrollment = app.DeviceEnrollment app.Sensors.NetworkDevices = app.DeviceEnrollment app.Access = &node.AccessStore{Path: filepath.Join(*dir, "ssh-keys.json"), Users: func() []string { return node.LocalAdmins("/") }} - if err := os.MkdirAll(filepath.Dir(*socket), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(*socket), 0750); err != nil { return err } if info, e := os.Lstat(*socket); e == nil { @@ -119,12 +126,36 @@ func run() error { }) public := &http.Server{Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 8192} private := &http.Server{Handler: admin, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 10 * time.Second, MaxHeaderBytes: 8192} - errs := make(chan error, 2) + // Separate local capability: media can request capacity, never obtain login. + budgetPath := filepath.Join(filepath.Dir(*socket), "budget.sock") + if info, e := os.Lstat(budgetPath); e == nil { + if info.Mode()&os.ModeSocket == 0 { + return errors.New("budget path is not a socket") + } + if e = os.Remove(budgetPath); e != nil { + return e + } + } else if !os.IsNotExist(e) { + return e + } + budgetListener, err := net.Listen("unix", budgetPath) + if err != nil { + return err + } + defer budgetListener.Close() + defer os.Remove(budgetPath) + if err := os.Chmod(budgetPath, 0660); err != nil { + return err + } + budgetServer := &http.Server{Handler: app.Budget.Handler(), ReadHeaderTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 1024} + errs := make(chan error, 3) + go func() { errs <- budgetServer.Serve(budgetListener) }() go func() { errs <- public.Serve(tcp) }() go func() { errs <- private.Serve(unix) }() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go app.Monitor.Run(ctx) + go pairing.Routers.Run(ctx) go app.Sensors.WatchUSB(ctx) go pairing.Run(ctx) log.Print("Mission Core Node " + version + " listening on loopback") @@ -136,6 +167,7 @@ func run() error { defer cancel() public.Shutdown(shutdown) private.Shutdown(shutdown) + budgetServer.Shutdown(shutdown) if errors.Is(err, http.ErrServerClosed) { return nil } diff --git a/apps/node-agent/internal/node/link_budget.go b/apps/node-agent/internal/node/link_budget.go new file mode 100644 index 00000000..2c0a6c9b --- /dev/null +++ b/apps/node-agent/internal/node/link_budget.go @@ -0,0 +1,284 @@ +package node + +// One egress budget for optional application traffic. Control and critical +// telemetry never acquire permits. No OS routes, queues or motor leases change. +import ( + "encoding/json" + "errors" + "math" + "net/http" + "os" + "path/filepath" + "sync" + "time" +) + +// The aggregate burst covers the four bounded class buckets. A smaller +// shared bucket allows an always-first video requester to starve bulk even +// when bulk has earned tokens (packetization/rounding). No per-peer queues. +const linkClassBurst = 4096 +const linkBurst = 4 * linkClassBurst +const linkPacket = 2048 +const linkOverhead = 256 + +// Inventory cannot compete packet-by-packet with short DEV polls. Both remain +// optional: these are shares of the same aggregate, not extra bandwidth. +var linkWeights = map[string]float64{"video": 7, "cloud": 2, "bulk": 1, "inventory": 1} + +type LinkPolicy struct { + Schema string `json:"schema"` + CeilingKbps int `json:"ceiling_kbps"` + ReserveKbps int `json:"reserve_kbps"` +} +type linkClass struct { + wanted float64 + tokens float64 + seen time.Time + bytes uint64 + deferred uint64 +} +type LinkBudget struct { + mu sync.Mutex + policy LinkPolicy + path string + now func() time.Time + at time.Time + tokens float64 + classes map[string]*linkClass + producers map[string]linkProducer + effective float64 + baseline time.Duration + baselineAt time.Time + changed time.Time + healthy time.Time + runtime linkRuntime +} + +func OpenLinkBudget(dir string) (*LinkBudget, error) { + b := &LinkBudget{policy: LinkPolicy{"missioncore.link-budget/v1", 0, 512}, now: time.Now, + classes: map[string]*linkClass{"video": {}, "cloud": {}, "bulk": {}, "inventory": {}}, + producers: map[string]linkProducer{}, runtime: linkRuntime{lastProtected: true, reason: "startup"}} + if dir != "" { + b.path = filepath.Join(dir, "link-budget.json") + data, err := os.ReadFile(b.path) + if err == nil { + if len(data) > 1024 || json.Unmarshal(data, &b.policy) != nil { + return nil, errors.New("invalid link budget") + } + } else if !os.IsNotExist(err) { + return nil, err + } + } + if err := validLinkPolicy(b.policy); err != nil { + return nil, err + } + b.effective = math.Min(4000, b.ceiling()) + b.at = b.now() + return b, nil +} +func validLinkPolicy(p LinkPolicy) error { + if p.Schema != "missioncore.link-budget/v1" || (p.CeilingKbps != 0 && (p.CeilingKbps < 1024 || p.CeilingKbps > 100000)) || p.ReserveKbps < 512 || p.ReserveKbps > 50000 || (p.CeilingKbps != 0 && p.ReserveKbps > p.CeilingKbps/2) { + return errors.New("link budget requires ceiling 0 (automatic) or 1024..100000 kbps and reserve 512..ceiling/2 kbps") + } + return nil +} +func (b *LinkBudget) Configure(p LinkPolicy) error { + if err := validLinkPolicy(p); err != nil { + return err + } + b.mu.Lock() + defer b.mu.Unlock() + if b.path != "" { + raw, _ := json.Marshal(p) + if err := os.WriteFile(b.path+".tmp", raw, 0600); err != nil { + return err + } + if err := os.Rename(b.path+".tmp", b.path); err != nil { + return err + } + } + b.policy = p + // Raising the configured ceiling does not erase observed congestion. + b.effective = math.Min(b.effective, b.ceiling()) + b.effective = math.Max(b.effective, float64(p.ReserveKbps+128)) + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + b.at = b.now() + return nil +} +func (b *LinkBudget) refill(now time.Time) { + dt := math.Max(0, now.Sub(b.at).Seconds()) + protected := b.protected(now) + if protected && !b.runtime.lastProtected { + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + } + b.runtime.lastProtected = protected + rates := b.classRates(now) + rate := b.optional(now) * 125 + b.tokens = math.Min(linkBurst, b.tokens+dt*rate) + for k, c := range b.classes { + if rates[k] == 0 { + c.tokens = 0 + continue + } + c.tokens = math.Min(linkClassBurst, c.tokens+dt*rates[k]/8) + } + b.at = now +} + +// Try is nonblocking, consumes actual bytes plus conservative packet overhead, +// and has fixed memory regardless of peer/request count. Denials are not queued. +func (b *LinkBudget) Try(class string, size int) (bool, time.Duration) { + if b == nil { + return true, 0 + } // Unwired unit fixtures only; production always owns a budget. + b.mu.Lock() + defer b.mu.Unlock() + return b.tryLocked(class, size) +} + +func (b *LinkBudget) tryLocked(class string, size int) (bool, time.Duration) { + c := b.classes[class] + if c == nil || size <= 0 || size > linkPacket { + return false, time.Second + } + now := b.now() + b.refill(now) + c.seen = now + if b.commandLimited(now) && class != "video" { + c.deferred++ + return false, 10 * time.Millisecond + } + cost := float64(size + linkOverhead) // UDP/IP, encryption and overlay allowance; not a wire measurement. + // Borrow idle optional credit only; the aggregate and control reserve remain + // hard gates. Preserve a packet of credit for each donor's next useful burst. + if c.tokens < cost && b.tokens >= cost { + for k, other := range b.classes { + if k != class && now.Sub(other.seen) > 100*time.Millisecond { + take := math.Min(math.Max(0, other.tokens-float64(linkPacket+linkOverhead)), cost-c.tokens) + other.tokens -= take + c.tokens += take + } + } + } + if h := &b.runtime.feedback; h.enabled && h.sent-h.acknowledged+uint64(cost) > h.window { + c.deferred++ + return false, 10 * time.Millisecond + } + if b.tokens >= cost && c.tokens >= cost { + if b.runtime.feedback.enabled { + b.runtime.feedback.sent += uint64(cost) + } + b.tokens -= cost + c.tokens -= cost + c.bytes += uint64(size) + return true, 0 + } + c.deferred++ + return false, 10 * time.Millisecond +} + +func (b *LinkBudget) Snapshot() map[string]any { + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + rates := b.classRates(now) + classes := map[string]any{} + counts := map[string]int{} + for _, p := range b.producers { + if b.now().Sub(p.seen) < producerTTL { + counts[p.class]++ + } + } + for k, c := range b.classes { + classes[k] = map[string]any{"granted_bytes": c.bytes, "deferrals": c.deferred, "producers": counts[k], "allocation_bps": int(rates[k])} + } + return map[string]any{"policy": b.policy, "effective_kbps": int(b.effective), "optional_kbps": int(b.optional(now)), "runtime": b.runtimeView(now), + "baseline_rtt_ms": b.baseline.Milliseconds(), "burst_bytes": linkBurst, "max_packet_bytes": linkPacket, "classes": classes} +} + +// Trusted local plugin socket exposes permits/status only, no configuration or +// control authority. The existing authenticated UI API owns policy changes. +func (b *LinkBudget) Handler() http.Handler { + mux := http.NewServeMux() + b.producerRoutes(mux) + mux.HandleFunc("GET /status", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, b.Snapshot()) }) + mux.HandleFunc("GET /events", func(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + events := append([]linkDecision{}, b.runtime.events...) + b.mu.Unlock() + reply(w, 200, events) + }) + mux.HandleFunc("POST /permit", func(w http.ResponseWriter, r *http.Request) { + var v struct { + Class string `json:"class"` + Bytes int `json:"bytes"` + Producer string `json:"producer_id"` + } + d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256)) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || (v.Class != "video" && v.Class != "cloud" && v.Class != "bulk") || v.Bytes <= 0 || v.Bytes > linkPacket { + reply(w, 400, map[string]string{"error": "invalid permit"}) + return + } + b.mu.Lock() + valid := true + if v.Producer != "" { + p, exists := b.producers[v.Producer] + valid = exists && p.class == v.Class && b.now().Sub(p.seen) < producerTTL + } + if b.commandLimited(b.now()) && v.Class == "video" { + valid = valid && v.Producer != "" && v.Producer == b.primaryVideo(b.now()) + } + granted, delay := false, 10*time.Millisecond + if valid { + granted, delay = b.tryLocked(v.Class, v.Bytes) + } + b.mu.Unlock() + reply(w, 200, map[string]any{"granted": granted, "retry_ms": delay.Milliseconds()}) + }) + return mux +} +func (s *Server) linkBudgetRoutes(mux *http.ServeMux) { + if s.Budget == nil { + return + } + mux.HandleFunc("GET /api/network/budget", func(w http.ResponseWriter, r *http.Request) { + if s.authorized(w, r) { + reply(w, 200, s.Budget.Snapshot()) + } + }) + mux.HandleFunc("PUT /api/network/budget", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + var p LinkPolicy + if !decode(w, r, &p) { + return + } + if err := s.Budget.Configure(p); err != nil { + reply(w, 400, map[string]string{"error": err.Error()}) + return + } + reply(w, 200, s.Budget.Snapshot()) + }) +} + +// Budget waits are part of upload time, not network failure. Size includes +// every paced packet's overhead at the lowest allocation with all classes busy. +// This is a per-request bound, never a recording/session duration limit. +func pacedTimeout(size int) time.Duration { + packets := (size + linkPacket - 1) / linkPacket + cost := size + packets*linkOverhead + total := 0.0 + for _, weight := range linkWeights { + total += weight + } + seconds := float64(cost) / (128 * 125 / total) + return 8*time.Second + time.Duration(math.Ceil(seconds*1.25))*time.Second +} diff --git a/apps/node-agent/internal/node/link_budget_test.go b/apps/node-agent/internal/node/link_budget_test.go new file mode 100644 index 00000000..54e10ec0 --- /dev/null +++ b/apps/node-agent/internal/node/link_budget_test.go @@ -0,0 +1,152 @@ +package node + +import ( + "bytes" + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func testBudget(t *testing.T) (*LinkBudget, *time.Time) { + t.Helper() + b, err := OpenLinkBudget("") + if err != nil { + t.Fatal(err) + } + now := time.Now() + b.now = func() time.Time { return now } + b.at = now + return b, &now +} +func TestLinkAggregateAndWeightedProgress(t *testing.T) { + b, now := testBudget(t) + counts := map[string]int{} + // Deterministic virtual time, no host/network load or sleeping. + for tick := 0; tick < 1000; tick++ { + *now = now.Add(10 * time.Millisecond) + for _, k := range []string{"video", "cloud", "bulk"} { + for attempt := 0; attempt < 10; attempt++ { + if ok, _ := b.Try(k, 1000); ok { + counts[k]++ + } + } + } + } + total := counts["video"] + counts["cloud"] + counts["bulk"] + if total*(1000+linkOverhead) > (4000-512)*125*10+linkBurst { + t.Fatal("aggregate budget exceeded", counts) + } + if counts["bulk"] < 100 || counts["cloud"] < counts["bulk"] || counts["video"] < 2*counts["cloud"] { + t.Fatal("class starvation/priority", counts) + } +} +func TestLinkCongestionDoesNotChangeMotionState(t *testing.T) { + b, now := testBudget(t) + s := newRoverStreamState(*now) + s.budget = b + b.Observe(300*time.Millisecond, true) + *now = now.Add(time.Second) + b.Observe(600*time.Millisecond, true) + if b.effective != 4000 { + t.Fatal("isolated delay reduced budget") + } + for i := 0; i < 15; i++ { + *now = now.Add(200 * time.Millisecond) + b.Observe(600*time.Millisecond, true) + } + if b.effective >= 4000 { + t.Fatal("sustained congestion ignored") + } + low := b.effective + for i := 0; i < 100; i++ { + *now = now.Add(100 * time.Millisecond) + b.Try("video", 1000) + b.Observe(300*time.Millisecond, true) + } + if b.effective <= low { + t.Fatal("recovery missing") + } + if s.command != nil || s.stopRevision != 1 || !s.stopPending { + t.Fatal("budget changed authority") + } +} +func TestLinkConfigAndLocalCapability(t *testing.T) { + b, _ := OpenLinkBudget(t.TempDir()) + p := LinkPolicy{"missioncore.link-budget/v1", 8000, 512} + if err := b.Configure(p); err != nil { + t.Fatal(err) + } + restored, err := OpenLinkBudget(b.path[:len(b.path)-len("/link-budget.json")]) + if err != nil || restored.policy != p { + t.Fatal("policy not durable", err) + } + for _, body := range []string{`{"class":"control","bytes":100}`, `{"class":"video","bytes":99999}`, `{"class":"bulk","bytes":0}`} { + r := httptest.NewRequest("POST", "/permit", bytes.NewBufferString(body)) + w := httptest.NewRecorder() + b.Handler().ServeHTTP(w, r) + if w.Code != 400 { + t.Fatal("untrusted permit accepted") + } + } + w := httptest.NewRecorder() + b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/login", nil)) + if w.Code != 404 { + t.Fatal("media socket acquired launcher authority") + } +} +func TestBudgetReaderCancellationAndDevBound(t *testing.T) { + b, _ := testBudget(t) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + r := &budgetReader{ctx: ctx, budget: b, class: "bulk", source: bytes.NewReader(make([]byte, 100))} + if _, err := r.Read(make([]byte, 4096)); err != context.Canceled { + t.Fatal("blocked cancellation", err) + } + rows := []any{} + for i := 0; i < 24; i++ { + rows = append(rows, map[string]any{"record_sequence": i, "value": strings.Repeat("x", 1000)}) + } + packet := map[string]any{"id": "capture", "frames": rows, "storage": map[string]any{"closed": false}, "export": map[string]any{"data": "data"}} + bounded := boundedDevPacket(packet) + raw, _ := json.Marshal(bounded) + if len(raw) > 12*1024 || len(bounded["frames"].([]any)) == 0 || len(packet["frames"].([]any)) != 24 || bounded["export"] == nil { + t.Fatal("invalid network view") + } +} + +func TestLinkBaselineRelearnsAfterNetworkHandover(t *testing.T) { + b, now := testBudget(t) + b.Observe(10*time.Millisecond, true) + for i := 0; i < 15; i++ { + *now = now.Add(200 * time.Millisecond) + b.Observe(300*time.Millisecond, true) + } + low := b.effective + *now = now.Add(31 * time.Second) + for i := 0; i < 60; i++ { + *now = now.Add(100 * time.Millisecond) + b.Try("video", 1000) + b.Observe(300*time.Millisecond, true) + } + if b.baseline != 300*time.Millisecond || b.effective <= low { + t.Fatal("old LAN minimum pinned new route", b.baseline, b.effective) + } +} + +func TestDevLargeExportDoesNotRemoveLiveRowsOrExceedRequestLimit(t *testing.T) { + rows := []any{map[string]any{"record_sequence": 1, "event": "sample"}} + for _, size := range []int{87384, 200000} { + packet := map[string]any{"id": "capture", "frames": rows, "export": map[string]any{"data": strings.Repeat("A", size)}} + bounded := boundedDevPacket(packet) + raw, _ := json.Marshal(bounded) + if len(raw) > 108*1024 || len(bounded["frames"].([]any)) != 1 { + t.Fatal("export exceeded bounded lane or starved live evidence") + } + if size == 87384 && bounded["export"] == nil { + t.Fatal("valid export lost") + } + } +} diff --git a/apps/node-agent/internal/node/link_command_health.go b/apps/node-agent/internal/node/link_command_health.go new file mode 100644 index 00000000..37c04537 --- /dev/null +++ b/apps/node-agent/internal/node/link_command_health.go @@ -0,0 +1,99 @@ +package node + +import "time" + +// This is optional-traffic admission, never a motor lease or a replacement for +// the stream watchdog. A healthy telemetry socket cannot certify command flow. +const commandPressureAfter = 150 * time.Millisecond +const commandRecoveryWindow = 200 * time.Millisecond +const commandBackoffAfter = 200 * time.Millisecond + +type linkCommandHealth struct { + seen, healthy, pressure time.Time + gap, age time.Duration + limited bool +} + +func (b *LinkBudget) commandPressure(now time.Time, reason string) { + h := &b.runtime.command + // Invalidate old credit once on entering pressure. Repeated moderate-age + // samples must not erase the selected camera's low-rate packet credit every + // 50 ms: at 128 kbps a 1100-byte datagram needs longer than one sample period. + // Moving the refill anchor prevents pre-pressure time recreating that credit. + if !h.limited { + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + b.at = now + } + h.limited = true + h.healthy = time.Time{} + if h.pressure.IsZero() { + h.pressure = now + } + // An isolated jitter sample is reason to yield, not evidence that the + // sustainable channel capacity fell by 25%. Require continuing pressure + // for an estimate reduction; fresh receipt ends that evidence immediately. + if now.Sub(h.pressure) < commandBackoffAfter { + return + } + b.healthy = time.Time{} + if now.Sub(b.changed) >= time.Second { + next := max(float64(b.policy.ReserveKbps+128), b.effective*.75) + if next < b.effective { + b.decision(now, reason, next) + } + } +} + +// age is the conservative Core-clock upper bound, not synchronized wall-clock +// latency. It can safely overestimate pressure but cannot grant motion authority. +func (b *LinkBudget) ObserveCommandFrame(gap, age time.Duration) { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + h := &b.runtime.command + h.seen, h.gap, h.age = now, gap, age + if !b.protected(now) { + h.limited, h.healthy, h.pressure = false, time.Time{}, time.Time{} + return + } + if gap >= commandPressureAfter || age >= commandPressureAfter { + b.commandPressure(now, "command_stream_pressure") + return + } + h.pressure = time.Time{} + if h.limited { + if h.healthy.IsZero() { + h.healthy = now + } + if now.Sub(h.healthy) >= commandRecoveryWindow { + h.limited = false + // Several fresh arrivals over real elapsed time are required: a + // queued burst cannot reopen optional traffic in a single instant. + // Isolated jitter must not erase the independent exchange estimator's + // recovery progress either. Sustained pressure resets it above. + } + } +} + +// Called by the existing local tick, even while the stream reader is blocked. +func (b *LinkBudget) ObserveCommandSilence() { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + if b.protected(now) && !b.runtime.command.seen.IsZero() && now.Sub(b.runtime.command.seen) >= commandPressureAfter { + b.commandPressure(now, "command_stream_silence") + } +} + +func (b *LinkBudget) commandLimited(now time.Time) bool { + return b.protected(now) && b.runtime.command.limited +} diff --git a/apps/node-agent/internal/node/link_command_health_test.go b/apps/node-agent/internal/node/link_command_health_test.go new file mode 100644 index 00000000..53a6e120 --- /dev/null +++ b/apps/node-agent/internal/node/link_command_health_test.go @@ -0,0 +1,264 @@ +package node + +import ( + "context" + "encoding/json" + "net/http" + "os" + "testing" + "time" +) + +func TestRedactedCommandJitterReplayPreservesAvailableCapacity(t *testing.T) { + // Timings only: no UTC, identities, commands, locations or device values. + // Replay the real admission code in virtual time, without sockets/motors. + raw, err := os.ReadFile("testdata/command-jitter-redacted.json") + if err != nil { + t.Fatal(err) + } + var rows [][3]float64 // elapsed receipt ms, inter-frame gap ms, conservative age ms + if err = json.Unmarshal(raw, &rows); err != nil || len(rows) < 1000 { + t.Fatal("invalid receipt fixture", err) + } + b, now := testBudget(t) + start := *now + initial := b.effective + b.SetControl(true) + blocked, total := time.Duration(0), time.Duration(0) + // Independent 50 ms local watchdog ticks, just as on Node. They may pause + // admission while the stream reader is blocked; fresh telemetry cannot hide it. + nextTick := start.Add(50 * time.Millisecond) + advance := func(at time.Time) { + delta := at.Sub(*now) + total += delta + if b.commandLimited(*now) { + blocked += delta + } + *now = at + b.SetControl(true) + } + for _, row := range rows { + at := start.Add(time.Duration(row[0] * float64(time.Millisecond))) + for !nextTick.After(at) { + advance(nextTick) + b.ObserveCommandSilence() + nextTick = nextTick.Add(50 * time.Millisecond) + } + advance(at) + b.ObserveCommandFrame(time.Duration(row[1]*float64(time.Millisecond)), time.Duration(row[2]*float64(time.Millisecond))) + } + ratio := float64(blocked) / float64(total) + t.Logf("optional admission paused %.1f%%; capacity %.0f -> %.0f kbps", ratio*100, initial, b.effective) + if ratio > .35 || b.effective < initial*.9 { + t.Fatal("isolated jitter still starves media", ratio, b.effective) + } +} + +func TestBudgetDiagnosticsAreBoundedAndDevOnly(t *testing.T) { + b, now := testBudget(t) + s := newRoverStreamState(*now) + s.budget = b + s.recordBudgetDev(*now) + if len(s.devEvents) != 0 { + t.Fatal("DEV-off recorded budget") + } + s.setDev(map[string]any{"id": testClockID, "enabled": true}) + for i := 0; i < 20; i++ { + s.recordBudgetDev(now.Add(time.Duration(i) * 100 * time.Millisecond)) + } + if len(s.devEvents) != 2 || s.devEvents[0]["event"] != "link_budget" { + t.Fatal("budget evidence rate is not bounded", len(s.devEvents)) + } + s.setDev(map[string]any{"id": testClockID, "enabled": false}) + s.recordBudgetDev(now.Add(3 * time.Second)) + if len(s.devEvents) != 2 { + t.Fatal("recording continued after DEV stop") + } +} + +func TestCommandSilenceBlocksOptionalBytesDespiteHealthyTelemetry(t *testing.T) { + b, now := testBudget(t) + b.SetControl(true) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + for _, class := range []string{"video", "cloud", "inventory", "bulk"} { + b.Try(class, 1000) + } + *now = now.Add(150 * time.Millisecond) + b.ObserveExchange(50*time.Millisecond, 0, true) + b.ObserveCommandSilence() + for _, class := range []string{"video", "cloud", "inventory", "bulk"} { + if ok, _ := b.Try(class, 100); ok { + t.Fatal("optional cached credit escaped command pressure", class) + } + } + if b.optional(*now) != 0 || b.reserve(*now) < 512 || !b.commandLimited(*now) { + t.Fatal("critical stream was not independently protected") + } + // A reply on another socket cannot reopen the gate or raise the estimate. + low := b.effective + for i := 0; i < 40; i++ { + *now = now.Add(100 * time.Millisecond) + b.SetControl(true) + b.ObserveExchange(20*time.Millisecond, 0, true) + } + if b.optional(*now) != 0 || b.effective > low { + t.Fatal("healthy telemetry concealed absent commands") + } +} + +func TestCommandRecoveryNeedsContinuousFreshFramesNotOneLateBurst(t *testing.T) { + b, now := testBudget(t) + b.SetControl(true) + b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond) + low := b.effective + for i := 0; i < 30; i++ { + *now = now.Add(10 * time.Millisecond) + b.ObserveCommandFrame(0, 200*time.Millisecond) + } + if !b.commandLimited(*now) { + t.Fatal("buffered old frames reopened optional traffic") + } + for i := 0; i < 21; i++ { + *now = now.Add(50 * time.Millisecond) + b.SetControl(true) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + if i < 4 && !b.commandLimited(*now) { + t.Fatal("recovery dwell skipped", i) + } + } + if b.commandLimited(*now) || b.effective > low || b.optional(*now) <= 0 { + t.Fatal("fresh recovery did not resume at reduced budget") + } +} + +func TestIsolatedCommandJitterYieldsWithoutCollapsingCapacity(t *testing.T) { + b, now := testBudget(t) + b.SetControl(true) + initial := b.effective + // One delayed frame per second, with fresh command flow in between. This + // formerly held the gate shut forever and drove capacity to its floor. + for cycle := 0; cycle < 20; cycle++ { + *now = now.Add(150 * time.Millisecond) + b.SetControl(true) + b.ObserveCommandFrame(150*time.Millisecond, 170*time.Millisecond) + if ok, _ := b.Try("video", 100); ok { + t.Fatal("delayed command did not yield optional traffic") + } + for i := 0; i < 17; i++ { + *now = now.Add(50 * time.Millisecond) + b.ObserveCommandFrame(50*time.Millisecond, 80*time.Millisecond) + } + if b.commandLimited(*now) || b.effective != initial { + t.Fatal("isolated jitter was mistaken for sustained congestion", cycle, b.effective) + } + if ok, _ := b.Try("video", 100); !ok { + t.Fatal("fresh command flow did not return optional capacity") + } + } +} + +func TestSustainedCommandPressureStillReducesCapacity(t *testing.T) { + for _, silence := range []bool{false, true} { + b, now := testBudget(t) + b.SetControl(true) + initial := b.effective + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + for i := 0; i < 30; i++ { + *now = now.Add(50 * time.Millisecond) + b.SetControl(true) + if silence { + b.ObserveCommandSilence() + } else { + b.ObserveCommandFrame(50*time.Millisecond, 200*time.Millisecond) + } + } + if !b.commandLimited(*now) || b.effective >= initial || b.optional(*now) != 0 { + t.Fatal("sustained command pressure was ignored", silence) + } + } +} + +func TestIsolatedCommandJitterDoesNotEraseCapacityRecovery(t *testing.T) { + b, now := testBudget(t) + b.effective = 1000 + for i := 0; i < 400; i++ { + *now = now.Add(50 * time.Millisecond) + b.SetControl(true) + b.allocateDemand(testClockID, "video", true, 5000000) + age := 80 * time.Millisecond + if i%20 == 0 { + age = 170 * time.Millisecond + } + b.ObserveCommandFrame(50*time.Millisecond, age) + b.ObserveExchange(80*time.Millisecond, 0, true) + } + if b.effective < 4000 || b.reserve(*now) < 512 { + t.Fatal("isolated command jitter erased measured exchange recovery", b.effective) + } +} + +func TestIdleObservationDoesNotSacrificeVideoForCommandJitter(t *testing.T) { + b, now := testBudget(t) + b.SetControl(false) + before := b.optional(*now) + b.ObserveCommandFrame(time.Second, time.Second) + *now = now.Add(time.Second) + b.ObserveCommandSilence() + if b.commandLimited(*now) || b.optional(*now) != before { + t.Fatal("idle command gap degraded observation") + } +} + +func TestLocalCommandPressurePreservesExpiryAndNoAutomaticRearm(t *testing.T) { + sensors, model, s, at := localDeliveryFixture(t) + b, now := testBudget(t) + *now = at + b.at = at + s.budget = b + s.devID, s.devEnabled = testClockID, true + s.receivedFrame(streamIntent(1331, 10000, 10400), at) + calls := 0 + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + calls++ + return testSensorReply(map[string]any{"state": "driving"}), nil + }) + var d roverLocalDelivery + d.run(context.Background(), sensors, model, s, "relay", at) + *now = at.Add(160 * time.Millisecond) + d.run(context.Background(), sensors, model, s, "relay", *now) + if calls != 1 || !b.commandLimited(*now) { + t.Fatal("pressure changed duplicate delivery or ignored local tick") + } + *now = at.Add(401 * time.Millisecond) + d.run(context.Background(), sensors, model, s, "relay", *now) + if calls != 2 || s.stopCause != "command_deadline_expired" { + t.Fatal("command expiry changed") + } + late := streamIntent(1332, 10401, 10801) + s.accept(late) + s.receivedFrame(late, *now) + _, command, _ := s.delivery(*now) + if command != nil || s.devEvents[len(s.devEvents)-1]["retired"] != true { + t.Fatal("late input revived authority or missing receipt evidence") + } +} + +func TestReceiptEvidenceIsDevOnlyAndUsesCoreClockBound(t *testing.T) { + for _, enabled := range []bool{false, true} { + at := time.Now() + s := newRoverStreamState(at) + s.sampleClock(roverClock{testClockID, 10020}, at, at.Add(40*time.Millisecond)) + acknowledgeStop(s, at) + s.devID, s.devEnabled = testClockID, enabled + s.receivedFrame(streamIntent(1, 10050, 10400), at.Add(100*time.Millisecond)) + if !enabled && len(s.devEvents) != 0 { + t.Fatal("DEV-off stored per-frame evidence") + } + if enabled { + row := s.devEvents[0] + if row["age_upper_ms"].(float64) < 70 || row["received_mono_ms"] != float64(100) { + t.Fatal("receipt clock bound lost", row) + } + } + } +} diff --git a/apps/node-agent/internal/node/link_datagram_feedback.go b/apps/node-agent/internal/node/link_datagram_feedback.go new file mode 100644 index 00000000..70e748f3 --- /dev/null +++ b/apps/node-agent/internal/node/link_datagram_feedback.go @@ -0,0 +1,164 @@ +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" + +const feedbackMinWindow = uint64(linkPacket + linkOverhead) +const feedbackMaxWindow = uint64(128 * 1024) + +type linkDatagramFeedback struct { + enabled bool + seen, adjusted, healthy, delayed time.Time + sent, acknowledged, window uint64 + rtt time.Duration + limited bool + pressure linkFeedbackPressure +} + +// Retain only the last initiating pressure event. Later healthy samples must +// not erase why media was paused; this is evidence, never admission credit. +type linkFeedbackPressure struct { + count uint64 + at time.Time + reason string + gap, rtt, threshold time.Duration + window uint64 +} + +func (h *linkDatagramFeedback) recordPressure(now time.Time, reason string, gap, rtt, threshold time.Duration) { + if h.limited { + return + } + h.pressure = linkFeedbackPressure{count: h.pressure.count + 1, at: now, + reason: reason, gap: gap, rtt: rtt, threshold: threshold, window: h.window} +} + +func (h *linkDatagramFeedback) pressureView(now time.Time) any { + p := h.pressure + if p.at.IsZero() { + return nil + } + return map[string]any{"count": p.count, "reason": p.reason, "age_ms": now.Sub(p.at).Milliseconds(), + "gap_ms": p.gap.Milliseconds(), "rtt_ms": p.rtt.Milliseconds(), + "threshold_ms": p.threshold.Milliseconds(), "window_bytes": p.window} +} + +func (b *LinkBudget) EnableDatagramFeedback() { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + if !b.runtime.feedback.enabled { + b.runtime.feedback = linkDatagramFeedback{enabled: true, seen: b.now(), window: linkClassBurst} + } +} +func (b *LinkBudget) DisableDatagramFeedback() { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + b.runtime.feedback = linkDatagramFeedback{} +} +func (b *LinkBudget) DatagramFeedbackMark() uint64 { + if b == nil { + return 0 + } + b.mu.Lock() + defer b.mu.Unlock() + return b.runtime.feedback.sent +} +func (b *LinkBudget) feedbackLimited(now time.Time) bool { + h := &b.runtime.feedback + if !h.enabled { + return false + } + if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) { + 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 + // must not release old optional credit as a burst. Caller holds b.mu. + h.limited = true + h.healthy = time.Time{} + h.window = min(h.window, uint64(linkClassBurst)) + h.adjusted = now + b.healthy = time.Time{} + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + b.at = now + } + return h.limited +} +func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float64, mark uint64) { + if b == nil { + return + } + // Use the existing exchange estimator with the measured Core scheduling wait + // removed. No RTT/2 correction is used for command or observation clocks. + b.ObserveExchange(elapsed, coreMS, true) + b.mu.Lock() + defer b.mu.Unlock() + h := &b.runtime.feedback + if !h.enabled || mark > h.sent || mark < h.acknowledged { + return + } + now := b.now() + b.feedbackLimited(now) + outstanding := h.sent - h.acknowledged + gap := now.Sub(h.seen) + h.acknowledged = mark + h.seen = now + if coreMS >= 0 && coreMS <= float64(elapsed.Microseconds())/1000 { + elapsed -= time.Duration(coreMS * float64(time.Millisecond)) + } + h.rtt = elapsed + if elapsed > b.baseline+75*time.Millisecond { + if h.delayed.IsZero() { + h.delayed = now + } + // 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. + if elapsed > max(250*time.Millisecond, b.baseline+150*time.Millisecond) { + h.recordPressure(now, "feedback_rtt", gap, elapsed, max(250*time.Millisecond, b.baseline+150*time.Millisecond)) + h.limited = true + h.healthy = time.Time{} + } + b.healthy = time.Time{} + // Delay-based admission must not mistake isolated RTT jitter for a + // growing queue. Require a sustained trend before reducing its window; + // severe delay and silence still suspend optional traffic immediately. + if h.limited || now.Sub(h.delayed) >= 200*time.Millisecond { + if h.adjusted.IsZero() || now.Sub(h.adjusted) >= 200*time.Millisecond { + h.window = max(feedbackMinWindow, h.window/2) + h.adjusted = now + } + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + b.at = now + } + return + } + h.delayed = time.Time{} + if h.limited { + if h.healthy.IsZero() { + h.healthy = now + } + if now.Sub(h.healthy) < 200*time.Millisecond { + return + } + 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) + h.adjusted = now + } +} diff --git a/apps/node-agent/internal/node/link_datagram_feedback_test.go b/apps/node-agent/internal/node/link_datagram_feedback_test.go new file mode 100644 index 00000000..48bcb3ff --- /dev/null +++ b/apps/node-agent/internal/node/link_datagram_feedback_test.go @@ -0,0 +1,157 @@ +package node + +import ( + "testing" + "time" +) + +func TestDatagramFeedbackBoundsOptionalBytesDespiteHealthyDownlink(t *testing.T) { + b, now := testBudget(t) + b.EnableDatagramFeedback() + b.SetControl(true) + b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0) + initial := b.runtime.feedback.window + // Pre-fill tokens as an already active producer; acknowledgement credit + // remains the independent upper bound across all optional classes. + for _, class := range []string{"video", "bulk", "cloud", "inventory"} { + b.classes[class].tokens = linkClassBurst + b.classes[class].seen = *now + b.classes[class].wanted = 1000000 + } + b.tokens = linkBurst + for i := 0; i < 20; i++ { + b.Try("video", 1100) + } + sent := b.DatagramFeedbackMark() + if sent == 0 || sent > initial { + t.Fatal("window bypass", sent, initial) + } + *now = now.Add(300 * time.Millisecond) + b.ObserveCommandFrame(50*time.Millisecond, 10*time.Millisecond) + if !b.feedbackLimited(*now) { + t.Fatal("fresh downlink erased return-path silence") + } + if ok, _ := b.Try("video", 1100); ok { + t.Fatal("video bypassed feedback silence") + } + b.ObserveDatagramFeedback(300*time.Millisecond, 0, sent) + if !b.runtime.feedback.limited { + t.Fatal("delayed echo did not apply pressure") + } + for i := 0; i < 3; i++ { + b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent) + } + if !b.runtime.feedback.limited { + t.Fatal("queued ACK burst reopened video") + } + *now = now.Add(201 * time.Millisecond) + b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent) + if b.runtime.feedback.limited { + t.Fatal("sustained fresh feedback did not recover") + } + if b.runtime.feedback.window < feedbackMinWindow { + t.Fatal("packet cannot fit") + } + b.DisableDatagramFeedback() + if b.feedbackLimited(now.Add(time.Hour)) { + t.Fatal("closed channel retained feedback gate") + } +} + +func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) { + for _, poll := range []bool{false, true} { + t.Run(map[bool]string{false: "idle-budget", true: "active-producer"}[poll], func(t *testing.T) { + b, now := testBudget(t) + b.EnableDatagramFeedback() + b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0) + b.runtime.feedback.window = feedbackMaxWindow + b.tokens = linkBurst + b.classes["video"].tokens = linkClassBurst + *now = now.Add(time.Second) + if poll { + b.Snapshot() + } + b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0) + if !b.runtime.feedback.limited || b.runtime.feedback.window > linkClassBurst { + t.Fatal("fresh echo restored the old send window", b.runtime.feedback) + } + if b.tokens != 0 || b.classes["video"].tokens != 0 { + t.Fatal("old burst credit survived silence") + } + for i := 0; i < 20; i++ { + b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0) + } + if !b.runtime.feedback.limited { + t.Fatal("ACK burst recovered without elapsed healthy time") + } + *now = now.Add(201 * time.Millisecond) + b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0) + if b.runtime.feedback.limited { + t.Fatal("continuous healthy feedback did not recover") + } + }) + } +} + +func TestDatagramFeedbackModerateJitterPreservesVideoAllocation(t *testing.T) { + b, now := testBudget(t) + b.EnableDatagramFeedback() + b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0) + b.runtime.feedback.window = 32768 + *now = now.Add(100 * time.Millisecond) + b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0) + if b.runtime.feedback.limited || b.optional(*now) <= 0 { + t.Fatal("one moderate delay disabled optional media") + } + if b.runtime.feedback.window != 32768 { + t.Fatal("isolated jitter collapsed the media window") + } + for i := 0; i < 2; i++ { + *now = now.Add(100 * time.Millisecond) + b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0) + } + if b.runtime.feedback.window >= 32768 || b.optional(*now) <= 0 { + t.Fatal("sustained moderate delay must reduce, not disable, media") + } + *now = now.Add(100 * time.Millisecond) + b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0) + if !b.runtime.feedback.limited || b.optional(*now) != 0 { + t.Fatal("severe return delay did not suspend media") + } +} + +func TestDatagramFeedbackRetainsInitiatingPressureAcrossRecovery(t *testing.T) { + b, now := testBudget(t) + b.EnableDatagramFeedback() + b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0) + if b.runtime.feedback.pressureView(*now) != nil { + t.Fatal("invented pressure") + } + *now = now.Add(300 * time.Millisecond) + b.feedbackLimited(*now) + first := b.runtime.feedback.pressure + if first.count != 1 || first.reason != "feedback_silence" || first.gap != 300*time.Millisecond || first.threshold != 250*time.Millisecond { + t.Fatal("missing initiating silence", first) + } + b.feedbackLimited(*now) + b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0) + if b.runtime.feedback.pressure != first { + t.Fatal("poll or delayed ACK overwrote initiating event") + } + b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0) + *now = now.Add(201 * time.Millisecond) + b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0) + if b.runtime.feedback.limited || b.runtime.feedback.pressure != first { + t.Fatal("recovery lost evidence or retained gate") + } + *now = now.Add(100 * time.Millisecond) + b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0) + second := b.runtime.feedback.pressure + if second.count != 2 || second.reason != "feedback_rtt" || second.rtt != 300*time.Millisecond || second.gap != 100*time.Millisecond { + t.Fatal("new pressure not retained", second) + } + b.DisableDatagramFeedback() + if b.runtime.feedback.pressureView(*now) != nil { + t.Fatal("new transport would inherit old diagnostic identity") + } +} diff --git a/apps/node-agent/internal/node/link_operator_view_test.go b/apps/node-agent/internal/node/link_operator_view_test.go new file mode 100644 index 00000000..d4a7dcc3 --- /dev/null +++ b/apps/node-agent/internal/node/link_operator_view_test.go @@ -0,0 +1,183 @@ +package node + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestExplicitOperatorViewPrecedesResidualTraffic(t *testing.T) { + b, now := testBudget(t) + primary, secondary, cloud := "11111111111111111111111111111111", "22222222222222222222222222222222", "33333333333333333333333333333333" + b.allocateRole(secondary, "video", true, 5000000, false) + b.allocateRole(primary, "video", true, 5000000, true) + b.allocateRole(cloud, "cloud", true, 2000000, false) + b.RequestDemand("inventory", 1000) + b.Try("inventory", 1000) + b.RequestDemand("bulk", 1000) + b.Try("bulk", 1000) + a, _ := b.allocateRole(primary, "video", true, 5000000, true) + c, _ := b.allocateRole(secondary, "video", true, 5000000, false) + rates := b.classRates(*now) + if a["allocation_bps"].(int) <= 0 || c["allocation_bps"] != 0 || rates["cloud"] != 0 || rates["bulk"] != 0 || rates["inventory"] <= 0 || a["class_producers"] != 2 { + t.Fatal(a, c, rates) + } + *now = now.Add(time.Millisecond) + b.allocateRole(secondary, "video", true, 5000000, true) + if b.primaryVideo(*now) != secondary { + t.Fatal("selection did not supersede earlier primary") + } + b.allocateRole(secondary, "video", false, 5000000, true) + if b.primaryVideo(*now) != primary { + t.Fatal("released view retained priority") + } + *now = now.Add(producerTTL) + if b.primaryVideo(*now) != "" { + t.Fatal("expired view retained priority") + } +} + +func TestSelectedViewHasBoundedModerateJitterProfileAndEmergencyYield(t *testing.T) { + b, now := testBudget(t) + primary := "11111111111111111111111111111111" + b.allocateRole(primary, "video", true, 5000000, true) + b.SetControl(true) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + *now = now.Add(160 * time.Millisecond) + b.ObserveCommandSilence() + if rate := b.optional(*now); rate <= 0 || rate > 384 { + t.Fatal("invalid low profile", rate) + } + permit := func(id string) bool { + raw, _ := json.Marshal(map[string]any{"class": "video", "bytes": 100, "producer_id": id}) + w := httptest.NewRecorder() + b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/permit", bytes.NewReader(raw))) + var reply map[string]any + json.Unmarshal(w.Body.Bytes(), &reply) + return reply["granted"] == true + } + if permit("") { + t.Fatal("unidentified video borrowed priority") + } + if permit(primary) { + t.Fatal("pre-pressure time restored discarded credit") + } + *now = now.Add(20 * time.Millisecond) + if !permit(primary) { + t.Fatal("selected video could not use low profile") + } + for _, class := range []string{"cloud", "bulk", "inventory"} { + if ok, _ := b.Try(class, 100); ok { + t.Fatal("background escaped pressure", class) + } + } + *now = now.Add(70 * time.Millisecond) + b.ObserveCommandSilence() + if b.optional(*now) != 0 || permit(primary) { + t.Fatal("video escaped 250 ms emergency yield") + } +} + +func TestLocalRecorderSendsOnlyLifecycleAndStopsPollingClosedFile(t *testing.T) { + s := newRoverStreamState(time.Now()) + options := map[string]any{"live": false, "network": true} + s.setDev(map[string]any{"id": testClockID, "enabled": true, "options": options}) + s.recordDev("network", map[string]any{}) + if len(s.devRequest()["relay_events"].([]map[string]any)) != 1 { + t.Fatal("local evidence omitted") + } + p := s.devPayload() + if len(p["relay_events"].([]any)) != 0 || len(p["frames"].([]any)) != 0 || diagnosticTrafficClass(p) != "inventory" { + t.Fatal("local recording streamed events", p) + } + s.devPacket = map[string]any{"sequence": 100, "storage": map[string]any{"closed": true}} + s.setDev(map[string]any{"id": testClockID, "enabled": false, "options": options, "after": 0}) + if s.devRequest() != nil { + t.Fatal("closed local recording kept polling") + } + if diagnosticTrafficClass(map[string]any{"export": map[string]any{"data": "abc"}}) != "bulk" { + t.Fatal("export escaped bulk lane") + } +} + +// Real-drive regression: a selected view used all optional capacity forever, +// so a closed local recording could not export even with control inactive. +func TestObservedPrimaryAllowsBoundedExportAtCongestedFloor(t *testing.T) { + b, now := testBudget(t) + b.effective = 640 + primary := "11111111111111111111111111111111" + left, inventory, video := 108*1024, 0, 0 + b.RequestDemand("bulk", left) + b.RequestDemand("inventory", 40*1024) + deadline := pacedTimeout(left) + for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond { + *now = now.Add(10 * time.Millisecond) + b.SetControl(false) + b.allocateRole(primary, "video", true, 5000000, true) + // Persistent demand, including primary video always attempting first. + for n := 0; n < 4; n++ { + if ok, _ := b.Try("video", 1200); ok { + video += 1200 + } + } + if inventory < 40*1024 { + size := min(linkPacket, 40*1024-inventory) + if ok, _ := b.Try("inventory", size); ok { + inventory += size + } + } + if left > 0 { + if ok, _ := b.Try("bulk", min(linkPacket, left)); ok { + left -= min(linkPacket, left) + } + } + } + if left != 0 || inventory != 40*1024 || video == 0 { + t.Fatal("observer export/metadata starved", left, inventory, video) + } + var bytes uint64 + for _, c := range b.classes { + bytes += c.bytes + } + if float64(bytes) > 128*125*deadline.Seconds()+linkBurst { + t.Fatal("shared budget exceeded", bytes) + } + b.SetControl(true) + b.Try("bulk", 1000) + if b.classRates(*now)["bulk"] != 0 { + t.Fatal("export displaced primary during active control") + } +} + +func TestCommandPrimaryLowRateProgressUnderPersistentModerateAge(t *testing.T) { + b, now := testBudget(t) + b.effective = 640 // Existing floor: 512 reserved + 128 optional kbps. + primary := "11111111111111111111111111111111" + b.allocateRole(primary, "video", true, 4000000, true) + b.SetControl(true) + handler := b.Handler() + admitted := 0 + for step := 0; step < 400; step++ { + *now = now.Add(5 * time.Millisecond) + if step%10 == 0 { + b.SetControl(true) + b.ObserveCommandFrame(50*time.Millisecond, 180*time.Millisecond) + } + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, httptest.NewRequest("POST", "/permit", strings.NewReader(`{"class":"video","bytes":1100,"producer_id":"11111111111111111111111111111111"}`))) + var reply struct { + Granted bool `json:"granted"` + } + json.Unmarshal(rr.Body.Bytes(), &reply) + if reply.Granted { + admitted += 1100 + } + } + t.Logf("moderate-age primary payload over 2 s: %d bytes; optional %.0f kbps", admitted, b.optional(*now)) + if admitted < 1100 || admitted+admitted/1100*linkOverhead > 32000 { + t.Fatal("declared low profile starved or exceeded its aggregate budget", admitted) + } +} diff --git a/apps/node-agent/internal/node/link_producers.go b/apps/node-agent/internal/node/link_producers.go new file mode 100644 index 00000000..09b0cf3f --- /dev/null +++ b/apps/node-agent/internal/node/link_producers.go @@ -0,0 +1,154 @@ +package node + +// Producer leases provide sizing advice from the existing class budget. They +// never reserve packet tokens, add queues, change control, or outlive a process. +import ( + "encoding/hex" + "encoding/json" + "errors" + "math" + "net/http" + "time" +) + +const producerTTL = 3 * time.Second +const maxLinkProducers = 32 + +type linkProducer struct { + class string + seen time.Time + demand int + since time.Time + primary bool + selected time.Time +} + +func (b *LinkBudget) allocate(id, class string, active bool) (map[string]any, error) { + return b.allocateDemand(id, class, active, 0) +} +func (b *LinkBudget) allocateDemand(id, class string, active bool, demand int) (map[string]any, error) { + return b.allocateRole(id, class, active, demand, false) +} +func (b *LinkBudget) primaryVideo(now time.Time) string { + selected := "" + for id, p := range b.producers { + if p.class != "video" || !p.primary || now.Sub(p.seen) >= producerTTL { + continue + } + if selected == "" || p.selected.After(b.producers[selected].selected) || (p.selected.Equal(b.producers[selected].selected) && id < selected) { + selected = id + } + } + return selected +} +func (b *LinkBudget) allocateRole(id, class string, active bool, demand int, operatorPrimary bool) (map[string]any, error) { + if operatorPrimary && class != "video" { + return nil, errors.New("primary must be video") + } + if demand < 0 || demand > 100000000 { + return nil, errors.New("invalid media demand") + } + if demand == 0 { + demand = 5000000 + if class == "cloud" { + demand = 2000000 + } + } + + if raw, err := hex.DecodeString(id); err != nil || len(raw) != 16 || (class != "video" && class != "cloud") { + return nil, errors.New("invalid media producer") + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + for key, p := range b.producers { + if now.Sub(p.seen) >= producerTTL { + delete(b.producers, key) + } + } + if old, exists := b.producers[id]; exists && old.class != class { + return nil, errors.New("producer class changed") + } + if !active { + delete(b.producers, id) + return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": 0, "ttl_ms": 0}, nil + } + if _, exists := b.producers[id]; !exists && len(b.producers) >= maxLinkProducers { + return nil, errors.New("media producer capacity") + } + b.refill(now) + since := now + if old, exists := b.producers[id]; exists { + since = old.since + } + selected := now + if old, exists := b.producers[id]; exists && old.primary == operatorPrimary { + selected = old.selected + } + b.producers[id] = linkProducer{class: class, seen: now, demand: demand, since: since, primary: operatorPrimary, selected: selected} + weights, demands := map[string]float64{}, map[string]float64{} + primary := "" + for key, p := range b.producers { + if p.class != class { + continue + } + weights[key] = 1 + demands[key] = float64(p.demand) + if primary == "" || p.since.Before(b.producers[primary].since) || (p.since.Equal(b.producers[primary].since) && key < primary) { + primary = key + } + } + explicit := b.primaryVideo(now) + if class == "video" && explicit != "" { + primary = explicit + } + rate := b.classRates(now)[class] + // When there is insufficient useful video for every viewer, retain the oldest + // active view. Additional viewers wait without resetting acquisition/recording. + count := len(weights) + minimum := 512000.0 + shares := map[string]float64{} + if class == "video" && explicit != "" { + shares[primary] = math.Min(rate, demands[primary]) + delete(weights, primary) + delete(demands, primary) + for key, value := range waterfill(rate-shares[primary], weights, demands) { + shares[key] = value + } + } else if class == "video" && rate < minimum*float64(len(weights)) { + shares[primary] = math.Min(rate, demands[primary]) + } else { + shares = waterfill(rate, weights, demands) + } + mode := "observing" + if b.protected(now) { + mode = "control_reserved" + } + return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": int(shares[id]), + "ttl_ms": producerTTL.Milliseconds(), "class_producers": count, "mode": mode, + "primary": id == primary, "reason": b.runtime.reason}, nil +} + +func (b *LinkBudget) producerRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /producer", func(w http.ResponseWriter, r *http.Request) { + var v struct { + ID string `json:"id"` + Class string `json:"class"` + Active *bool `json:"active"` + Demand int `json:"demand_bps"` + Primary bool `json:"primary"` + } + d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256)) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || v.Active == nil { + reply(w, 400, map[string]string{"error": "invalid media producer"}) + return + } + result, err := b.allocateRole(v.ID, v.Class, *v.Active, v.Demand, v.Primary) + if err != nil { + reply(w, 409, map[string]string{"error": err.Error()}) + return + } + reply(w, 200, result) + }) +} diff --git a/apps/node-agent/internal/node/link_producers_test.go b/apps/node-agent/internal/node/link_producers_test.go new file mode 100644 index 00000000..5e9190e8 --- /dev/null +++ b/apps/node-agent/internal/node/link_producers_test.go @@ -0,0 +1,68 @@ +package node + +import ( + "fmt" + "testing" + "time" +) + +func TestMediaProducersShareOneBudgetAndExpire(t *testing.T) { + b, _ := OpenLinkBudget("") + now := time.Now() + b.now = func() time.Time { return now } + b.at = now + id := func(i int) string { return fmt.Sprintf("%032x", i) } + for i := 1; i <= 2; i++ { + if _, err := b.allocate(id(i), "video", true); err != nil { + t.Fatal(err) + } + } + if _, err := b.allocate(id(3), "cloud", true); err != nil { + t.Fatal(err) + } + b.Try("bulk", 100) + a, _ := b.allocate(id(1), "video", true) + c, _ := b.allocate(id(3), "cloud", true) + if a["allocation_bps"] != 1220800 || c["allocation_bps"] != 697600 || b.tokens != 0 { + t.Fatal("advice must divide existing class budget without minting permits", a, c, b.tokens) + } + b.allocate(id(2), "video", false) + a, _ = b.allocate(id(1), "video", true) + if a["allocation_bps"] != 2441600 { + t.Fatal(a) + } + now = now.Add(4 * time.Second) + a, _ = b.allocate(id(1), "video", true) + if len(b.producers) != 1 || a["allocation_bps"] != 3488000 { + t.Fatal("expired producer retained capacity", a) + } + for i := 0; i < 3; i++ { + now = now.Add(time.Second) + b.Observe(time.Second, false) + } + a, _ = b.allocate(id(1), "video", true) + if a["allocation_bps"].(int) >= 3488000 { + t.Fatal("allocation ignored congestion", a) + } +} + +func TestMediaProducerAdmissionIsBoundedAndHasNoControlClass(t *testing.T) { + b, _ := OpenLinkBudget("") + for i := 0; i < maxLinkProducers; i++ { + if _, err := b.allocate(fmt.Sprintf("%032x", i), "video", true); err != nil { + t.Fatal(err) + } + } + if _, err := b.allocate(fmt.Sprintf("%032x", 99), "video", true); err == nil { + t.Fatal("unbounded producer registry") + } + if _, err := b.allocate(fmt.Sprintf("%032x", 0), "cloud", true); err == nil { + t.Fatal("producer changed class") + } + if _, err := b.allocate(fmt.Sprintf("%032x", 0), "control", true); err == nil { + t.Fatal("control allocation admitted") + } + if _, err := b.allocate("bad", "video", true); err == nil { + t.Fatal("bad identifier admitted") + } +} diff --git a/apps/node-agent/internal/node/link_runtime.go b/apps/node-agent/internal/node/link_runtime.go new file mode 100644 index 00000000..99456172 --- /dev/null +++ b/apps/node-agent/internal/node/link_runtime.go @@ -0,0 +1,338 @@ +package node + +// Runtime policy for the existing egress gate. Rates are send budgets, not a +// claim to have measured physical link capacity. No command authority lives here. +import ( + "math" + "time" +) + +type linkSample struct { + at time.Time + elapsed time.Duration + ok bool +} +type linkDecision struct { + AtMS int64 `json:"at_ms"` + Reason string `json:"reason"` + Kbps int `json:"kbps"` +} +type linkRuntime struct { + feedback linkDatagramFeedback + command linkCommandHealth + criticalAt time.Time + criticalBytes int + criticalKbps float64 + lastProtected bool + control bool + modeAt time.Time + samples []linkSample + errors int + reason string + events []linkDecision + started time.Time + coreMS float64 +} + +func (b *LinkBudget) ceiling() float64 { + if b.policy.CeilingKbps == 0 { + return 100000 + } // Contract bound, not inferred capacity. + return float64(b.policy.CeilingKbps) +} +func (b *LinkBudget) protected(now time.Time) bool { + return b.runtime.modeAt.IsZero() || now.Sub(b.runtime.modeAt) > 2*time.Second || b.runtime.control +} +func (b *LinkBudget) reserve(now time.Time) float64 { + if b.protected(now) { + return math.Max(float64(b.policy.ReserveKbps), b.runtime.criticalKbps*1.5) + } + if b.runtime.criticalAt.IsZero() { + return float64(b.policy.ReserveKbps) + } + return math.Max(64, b.runtime.criticalKbps*1.5) // Actual critical traffic plus margin, never an idle constant alone. +} + +// Critical bytes are observed, never paced or rejected by this regulator. +func (b *LinkBudget) ObserveCriticalBytes(size int) { + if b == nil || size <= 0 { + return + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + if b.runtime.criticalAt.IsZero() { + b.runtime.criticalAt = now + b.runtime.criticalKbps = float64(b.policy.ReserveKbps) / 1.5 + } + b.runtime.criticalBytes += size + ((size+1199)/1200)*linkOverhead + elapsed := now.Sub(b.runtime.criticalAt).Seconds() + if elapsed >= 1 { + rate := float64(b.runtime.criticalBytes) * 8 / 1000 / elapsed + // Follow growth immediately; decay slowly so a quiet sample cannot under-size admission. + b.runtime.criticalKbps = math.Max(rate, b.runtime.criticalKbps*.8) + b.runtime.criticalAt = now + b.runtime.criticalBytes = 0 + } +} +func (b *LinkBudget) optional(now time.Time) float64 { + if b.feedbackLimited(now) { + return 0 + } + ceiling := math.Max(0, b.effective-b.reserve(now)) + if b.runtime.feedback.enabled { + // A bounded acknowledgement window constrains useful optional traffic. + // This is admission credit, never a claim of measured wire capacity. + period := max(100*time.Millisecond, b.baseline) + ceiling = math.Min(ceiling, float64(b.runtime.feedback.window)*8/period.Seconds()/1000) + } + + if b.commandLimited(now) { + // A selected operator view gets only a bounded low profile during + // moderate jitter. At 250 ms silence/age all optional payload yields. + // The 400 ms command lease and 350/200 ms watchdogs are unchanged. + h := b.runtime.command + emergency := h.gap >= 250*time.Millisecond || h.age >= 250*time.Millisecond || + (!h.seen.IsZero() && now.Sub(h.seen) >= 250*time.Millisecond) + if emergency || b.primaryVideo(now) == "" { + return 0 + } + return math.Min(384, ceiling) + } + return ceiling +} +func (b *LinkBudget) SetControl(active bool) { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + was := b.protected(now) + b.runtime.control, b.runtime.modeAt = active, now + if !active { + // An intentionally closed observer stream is not packet loss. Do not + // retain pressure/old receipt timestamps across completed sessions. + b.runtime.command = linkCommandHealth{} + } + if !was && active { + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + } +} +func (b *LinkBudget) decision(now time.Time, reason string, next float64) { + if b.runtime.started.IsZero() { + b.runtime.started = now + } + if next < b.effective { + b.tokens = 0 + for _, c := range b.classes { + c.tokens = 0 + } + } + b.effective = next + b.changed = now + b.runtime.reason = reason + b.runtime.events = append(b.runtime.events, linkDecision{now.Sub(b.runtime.started).Milliseconds(), reason, int(next)}) + if len(b.runtime.events) > 32 { + b.runtime.events = b.runtime.events[len(b.runtime.events)-32:] + } +} + +// Observe remains for transport failures / older Core peers. Application errors +// are deliberately excluded by the caller; they are not bandwidth evidence. +func (b *LinkBudget) Observe(elapsed time.Duration, ok bool) { b.ObserveExchange(elapsed, 0, ok) } +func (b *LinkBudget) ObserveExchange(elapsed time.Duration, coreMS float64, ok bool) { + if b == nil { + return + } + b.mu.Lock() + defer b.mu.Unlock() + now := b.now() + if math.IsNaN(coreMS) || math.IsInf(coreMS, 0) || coreMS < 0 || coreMS > float64(elapsed.Microseconds())/1000 { + coreMS = 0 + } + b.runtime.coreMS = coreMS + elapsed -= time.Duration(coreMS * float64(time.Millisecond)) + samples := b.runtime.samples[:0] + for _, v := range b.runtime.samples { + if now.Sub(v.at) < 30*time.Second { + samples = append(samples, v) + } + } + samples = append(samples, linkSample{now, elapsed, ok}) + if len(samples) > 320 { + samples = samples[len(samples)-320:] + } + b.runtime.samples = samples + b.baseline = 0 + for _, v := range samples { + if v.ok && (b.baseline == 0 || v.elapsed < b.baseline) { + b.baseline = v.elapsed + } + } + if ok { + b.runtime.errors = 0 + } else { + b.runtime.errors++ + } + total, bad := 0, 0 + var first time.Time + for _, v := range samples { + if now.Sub(v.at) > 2*time.Second { + continue + } + if first.IsZero() { + first = v.at + } + total++ + if !v.ok || v.elapsed > b.baseline+150*time.Millisecond { + bad++ + } + } + ready := total >= 4 && now.Sub(first) >= time.Second + congested := b.runtime.errors >= 3 || (ready && bad*2 >= total) + if congested && now.Sub(b.changed) >= time.Second { + next := math.Max(float64(b.policy.ReserveKbps+128), b.effective*.75) + if next < b.effective { + b.refill(now) + b.decision(now, "sustained_delay_or_transport_loss", next) + } + b.healthy = time.Time{} + } else if ready && bad*5 <= total && !b.commandLimited(now) && !b.feedbackLimited(now) { + if b.healthy.IsZero() { + b.healthy = now + } + if now.Sub(b.healthy) >= 2*time.Second && now.Sub(b.changed) >= 2*time.Second { + // Bounded useful-traffic probing. Do not manufacture dummy network load or + // ramp indefinitely on a quiet scene / when nobody requests optional data. + demand := b.demand(now)/1000 + b.reserve(now) + next := math.Min(b.ceiling(), math.Min(demand, b.effective+math.Max(128, b.effective*.20))) + if next > b.effective { + b.refill(now) + b.decision(now, "healthy_demand_probe", next) + } + } + } + // An isolated outlier neither reduces the budget nor erases recovery progress. +} +func (b *LinkBudget) runtimeView(now time.Time) map[string]any { + mode := "observing" + if b.protected(now) { + mode = "control_reserved" + } + return map[string]any{"schema": "missioncore.link-runtime/v1", "direction": "node_egress", + "feedback_limited": b.feedbackLimited(now), "feedback_window_bytes": b.runtime.feedback.window, "feedback_outstanding_bytes": b.runtime.feedback.sent - b.runtime.feedback.acknowledged, "feedback_rtt_ms": b.runtime.feedback.rtt.Milliseconds(), + "feedback_pressure": b.runtime.feedback.pressureView(now), + "command_limited": b.commandLimited(now), "command_gap_ms": b.runtime.command.gap.Milliseconds(), + "command_age_upper_ms": b.runtime.command.age.Milliseconds(), + "mode": mode, "reserve_kbps": int(b.reserve(now)), "reason": b.runtime.reason, + "core_processing_ms": b.runtime.coreMS, "samples": len(b.runtime.samples), "automatic": b.policy.CeilingKbps == 0, + "critical_offered_kbps": int(b.runtime.criticalKbps), "capacity_measured": false} +} + +// Weighted water filling with demand caps redistributes unused allocations. +// Class packet admission and producer sizing use the same result. +func waterfill(total float64, weights, demands map[string]float64) map[string]float64 { + out := map[string]float64{} + active := map[string]float64{} + for k, w := range weights { + if demands[k] > 0 && w > 0 { + active[k] = w + } + } + remaining := total + for len(active) > 0 && remaining > 0 { + sum := 0.0 + for _, w := range active { + sum += w + } + capped := []string{} + for k, w := range active { + if demands[k] <= remaining*w/sum { + capped = append(capped, k) + } + } + if len(capped) == 0 { + for k, w := range active { + out[k] = remaining * w / sum + } + break + } + for _, k := range capped { + out[k] = demands[k] + remaining -= demands[k] + delete(active, k) + } + } + return out +} +func (b *LinkBudget) demands(now time.Time) map[string]float64 { + d := map[string]float64{} + for _, p := range b.producers { + if now.Sub(p.seen) < producerTTL { + d[p.class] += float64(p.demand) + } + } + for k, c := range b.classes { + if now.Sub(c.seen) <= 2*time.Second && (k == "inventory" || k == "bulk" || d[k] == 0) { + d[k] = c.wanted + if d[k] == 0 { + d[k] = b.ceiling() * 1000 + } + } + } + return d +} +func (b *LinkBudget) demand(now time.Time) float64 { + total := 0.0 + for _, v := range b.demands(now) { + total += v + } + return total +} +func (b *LinkBudget) classRates(now time.Time) map[string]float64 { + total := b.optional(now) * 1000 + demands := b.demands(now) + if b.commandLimited(now) { + return map[string]float64{"video": math.Min(total, demands["video"])} + } + 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. + rates := map[string]float64{} + if !b.protected(now) { + rates["bulk"] = math.Min(demands["bulk"], math.Min(32000, total/11)) + total -= rates["bulk"] + demands["bulk"] -= rates["bulk"] + } + rates["inventory"] = math.Min(total, math.Min(32000, demands["inventory"])) + total -= rates["inventory"] + rates["video"] = math.Min(total, demands["video"]) + total -= rates["video"] + for key, value := range waterfill(total, map[string]float64{"cloud": 1, "bulk": 1}, demands) { + rates[key] += value + } + return rates +} + +// Existing serialized HTTP lanes declare finite body demand rather than +// permanently competing as unlimited streams. This never mints packet credit. +func (b *LinkBudget) RequestDemand(class string, size int) { + if b == nil || size <= 0 { + return + } + b.mu.Lock() + defer b.mu.Unlock() + if c := b.classes[class]; c != nil { + wire := size + ((size+linkPacket-1)/linkPacket)*linkOverhead + c.wanted = math.Min(b.ceiling()*1000, math.Max(64000, float64(wire)*8)) + } +} diff --git a/apps/node-agent/internal/node/link_runtime_test.go b/apps/node-agent/internal/node/link_runtime_test.go new file mode 100644 index 00000000..3dc241a8 --- /dev/null +++ b/apps/node-agent/internal/node/link_runtime_test.go @@ -0,0 +1,103 @@ +package node + +import ( + "fmt" + "testing" + "time" +) + +func TestRuntimeRecoversWithPeriodicOutliersAndRespectsExplicitCeiling(t *testing.T) { + for _, limit := range []int{0, 4000} { + b, now := testBudget(t) + b.Configure(LinkPolicy{"missioncore.link-budget/v1", limit, 512}) + b.effective = 640 + for i := 0; i < 600; i++ { + *now = now.Add(100 * time.Millisecond) + b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 8000000) + delay := 50 * time.Millisecond + if i%80 == 0 { + delay = 500 * time.Millisecond + } + b.Observe(delay, true) + } + if b.effective < 4000 || (limit == 0 && b.effective <= 4000) || (limit > 0 && b.effective > float64(limit)) { + t.Fatal("recovery/cap", limit, b.effective) + } + if len(b.runtime.events) > 32 || len(b.runtime.samples) > 320 { + t.Fatal("unbounded diagnostics") + } + } +} +func TestRuntimeSubtractsCoreProcessingAndNeverTreatsItAsLinkLoss(t *testing.T) { + b, now := testBudget(t) + for i := 0; i < 60; i++ { + *now = now.Add(100 * time.Millisecond) + core := float64(i%6) * 100 + b.ObserveExchange(time.Duration(50+core)*time.Millisecond, core, true) + } + if b.effective != 4000 || b.baseline != 50*time.Millisecond { + t.Fatal("server processing misclassified", b.effective, b.baseline) + } +} +func TestControlReserveActivatesBeforeIntentAndReturnsOnStaleState(t *testing.T) { + b, now := testBudget(t) + b.runtime.criticalAt = *now + b.runtime.criticalKbps = 50 + b.SetControl(false) + if b.reserve(*now) != 75 { + t.Fatal("idle critical rate ignored") + } + b.Try("bulk", 1000) + *now = now.Add(time.Second) + b.Try("bulk", 1000) + b.SetControl(true) + if b.tokens != 0 || b.reserve(*now) != 512 { + t.Fatal("first intent can inherit idle burst") + } + b.SetControl(false) + *now = now.Add(3 * time.Second) + if b.reserve(*now) != 512 { + t.Fatal("stale state released control reserve") + } + b.runtime.criticalKbps = 600 + if b.reserve(*now) != 900 { + t.Fatal("actual critical demand clipped") + } +} +func TestDemandRedistributionAndUsefulVideoAdmission(t *testing.T) { + b, now := testBudget(t) + first, second := fmt.Sprintf("%032x", 1), fmt.Sprintf("%032x", 2) + b.allocateDemand(first, "video", true, 1000000) + a, _ := b.allocateDemand(second, "video", true, 5000000) + if a["allocation_bps"] != 2488000 { + t.Fatal("unused producer demand not lent", a) + } + b.effective = 1000 + a, _ = b.allocateDemand(first, "video", true, 1000000) + c, _ := b.allocateDemand(second, "video", true, 5000000) + if a["allocation_bps"] != 488000 || c["allocation_bps"] != 0 { + t.Fatal("all video degraded instead of admitting one", a, c) + } + *now = now.Add(4 * time.Second) + c, _ = b.allocateDemand(second, "video", true, 5000000) + if c["allocation_bps"] != 488000 { + t.Fatal("expired viewer retained priority", c) + } +} +func TestWaterfillIsBoundedAndDemandCapped(t *testing.T) { + rates := waterfill(100, map[string]float64{"a": 1, "b": 1, "c": 1}, map[string]float64{"a": 5, "b": 10, "c": 200}) + if rates["a"] != 5 || rates["b"] != 10 || rates["c"] != 85 { + t.Fatal(rates) + } +} + +func TestSmallInventoryDoesNotReserveAnUnlimitedStream(t *testing.T) { + b, now := testBudget(t) + b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 5000000) + b.RequestDemand("inventory", 6000) + b.Try("inventory", 1000) + rates := b.classRates(*now) + if rates["inventory"] != 64000 || rates["video"] != 3424000 { + t.Fatal("small metadata held camera bandwidth", rates) + } +} diff --git a/apps/node-agent/internal/node/link_stop_recovery_test.go b/apps/node-agent/internal/node/link_stop_recovery_test.go new file mode 100644 index 00000000..e28c00ab --- /dev/null +++ b/apps/node-agent/internal/node/link_stop_recovery_test.go @@ -0,0 +1,40 @@ +package node + +import ( + "testing" + "time" +) + +func TestTenStopRecoveryCyclesPreserveVideoAdmissionBounds(t *testing.T) { + b, now := testBudget(t) + const primary = "11111111111111111111111111111111" + for run := 0; run < 10; run++ { + b.SetControl(true) + b.allocateRole(primary, "video", true, 5000000, true) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + *now = now.Add(250 * time.Millisecond) + b.ObserveCommandSilence() + if b.optional(*now) != 0 { + t.Fatal("expired commands admitted video", run) + } + for _, class := range []string{"video", "bulk", "cloud", "inventory"} { + if ok, _ := b.Try(class, 100); ok { + t.Fatal("cached credit bypassed pause", run, class) + } + } + // Confirmed absence of authority ends command-specific pressure; it + // does not increase capacity or remove other feedback/bandwidth caps. + capacity := b.effective + b.SetControl(false) + if b.optional(*now) <= 0 || b.effective != capacity { + t.Fatal("observation failed to resume within cap", run) + } + b.SetControl(true) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + *now = now.Add(50 * time.Millisecond) + b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond) + if b.optional(*now) <= 0 || b.reserve(*now) < float64(b.policy.ReserveKbps) { + t.Fatal("fresh neutral recovery lost reserve", run) + } + } +} diff --git a/apps/node-agent/internal/node/network_profile.go b/apps/node-agent/internal/node/network_profile.go new file mode 100644 index 00000000..ae1a98a8 --- /dev/null +++ b/apps/node-agent/internal/node/network_profile.go @@ -0,0 +1,478 @@ +package node + +// Network preferences belong to this board. Core observes acknowledged generations. +import ( + "bufio" + "context" + "encoding/json" + "errors" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "time" +) + +type NetworkPending struct { + Deadline int64 `json:"deadline"` + PreviousEndpoint string `json:"previous_endpoint"` + Provider string `json:"provider"` + ServerID string `json:"server_id"` + Config json.RawMessage `json:"config,omitempty"` + Local bool `json:"local,omitempty"` +} +type NetworkProfile struct { + BindingID string `json:"binding_id"` + Revision int64 `json:"revision"` + Provider string `json:"provider"` + ServerID string `json:"server_id,omitempty"` + Config json.RawMessage `json:"config,omitempty"` + TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"` + OperationID string `json:"operation_id,omitempty"` + Phase string `json:"phase"` + PublicKey string `json:"public_key,omitempty"` + Error string `json:"error,omitempty"` + Pending *NetworkPending `json:"pending,omitempty"` +} +type NetworkCommand struct { + ID string `json:"id"` + Action string `json:"action"` + Provider string `json:"provider"` + ServerID string `json:"server_id"` + ExpectedRevision int64 `json:"expected_revision"` + ExpiresAt int64 `json:"expires_at"` + CoreEndpoint string `json:"core_endpoint,omitempty"` + Config json.RawMessage `json:"config,omitempty"` +} + +var networkID = regexp.MustCompile(`^wg_[a-f0-9]{32}$`) +var networkOperationID = regexp.MustCompile(`^[a-f0-9]{32}$`) + +func networkHelper(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) { + connection, err := net.DialTimeout("unix", "/run/mission-core-wireguard/control.sock", 3*time.Second) + if err != nil { + return nil, errors.New("Системная служба WireGuard недоступна. Обновите Node.") + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(25 * time.Second)) + body := map[string]any{"action": action, "server_id": identity} + for key, value := range fields { + body[key] = value + } + if err = json.NewEncoder(connection).Encode(body); err != nil { + return nil, err + } + var result struct { + OK bool `json:"ok"` + Result map[string]json.RawMessage `json:"result"` + Error string `json:"error"` + } + data, err := bufio.NewReaderSize(connection, 16385).ReadSlice('\n') + if err != nil || len(data) > 16384 || json.Unmarshal(data, &result) != nil { + return nil, errors.New("Нет подтверждения сетевой службы.") + } + if !result.OK { + return nil, errors.New("Не удалось подготовить WireGuard на борту.") + } + return result.Result, nil +} +func (p *Pairing) callNetwork(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) { + if p.networkCall != nil { + return p.networkCall(action, identity, fields) + } + return networkHelper(action, identity, fields) +} +func (p *Pairing) networkPath() string { + return filepath.Join(filepath.Dir(p.path), "network-profile.json") +} +func (p *Pairing) loadNetworkLocked() error { + if p.network != nil { + if p.state.Binding == nil || p.network.BindingID == p.state.Binding.BindingID { + return nil + } + p.network = nil + } + value := NetworkProfile{Provider: "tailscale", Phase: "applied"} + raw, err := os.ReadFile(p.networkPath()) + if err == nil { + info, e := os.Lstat(p.networkPath()) + if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 { + return errors.New("Invalid network configuration permissions") + } + } + if err == nil { + if len(raw) > 16384 || json.Unmarshal(raw, &value) != nil { + return errors.New("Invalid network configuration") + } + } else if !os.IsNotExist(err) { + return err + } + if p.state.Binding != nil { + if value.BindingID != p.state.Binding.BindingID { + value = NetworkProfile{BindingID: p.state.Binding.BindingID, Provider: "tailscale", Phase: "applied"} + } + endpoint, _ := url.Parse(p.state.Binding.Endpoint) + if tailnetAddress(endpoint.Hostname()) { + value.TailscaleEndpoint = p.state.Binding.Endpoint + } + } + p.network = &value + return nil +} +func (p *Pairing) saveNetworkLocked() error { return savePrivateJSON(p.networkPath(), p.network) } +func (p *Pairing) networkViewLocked() map[string]any { + if p.loadNetworkLocked() != nil { + return map[string]any{"phase": "unavailable"} + } + n := p.network + result := map[string]any{"provider": n.Provider, "server_id": n.ServerID, "revision": n.Revision, "phase": n.Phase, + "operation_id": n.OperationID, "public_key": n.PublicKey, "tailscale_endpoint": n.TailscaleEndpoint, "error": n.Error} + if n.Pending != nil { + result["pending_provider"] = n.Pending.Provider + result["rollback_at"] = n.Pending.Deadline + } + return result +} +func (p *Pairing) networkSnapshot() map[string]any { + p.mu.Lock() + defer p.mu.Unlock() + return p.networkViewLocked() +} +func (p *Pairing) networkEndpointLocked(endpoint string) error { + b := p.state.Binding + if b == nil || p.state.Phase != "paired" || !privateEndpoint(endpoint, CorePort) { + return errors.New("Binding unavailable") + } + if b.Endpoint == endpoint { + return nil + } + if b.EndpointRevision >= 1000000000 { + return errors.New("Endpoint revision exhausted") + } + next := p.state + copy := *b + copy.Endpoint = endpoint + copy.EndpointRevision++ + next.Binding = © + if err := p.save(next); err != nil { + return err + } + p.connection = "offline" + p.lastSeen = 0 + return nil +} +func (p *Pairing) rollbackNetwork() { + p.mu.Lock() + if p.loadNetworkLocked() != nil || p.network.Pending == nil { + p.mu.Unlock() + return + } + n := p.network + pending := *n.Pending + identity := pending.ServerID + op := n.OperationID + p.mu.Unlock() + if networkID.MatchString(identity) { + if _, err := p.callNetwork("rollback", identity, map[string]any{"operation_id": op}); err != nil { + return + } + } + p.mu.Lock() + defer p.mu.Unlock() + if p.network.Pending == nil || p.network.OperationID != op { + return + } + if p.networkEndpointLocked(pending.PreviousEndpoint) != nil { + return + } + n.Pending = nil + n.Phase = "rolled_back" + n.Error = "Новое подключение не подтверждено. Восстановлен прежний профиль." + _ = p.saveNetworkLocked() +} +func (p *Pairing) networkWatch(ctx context.Context) { + // A restart during a transaction restores the last confirmed endpoint. + p.rollbackNetwork() + timer := time.NewTicker(time.Second) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + p.mu.Lock() + expired := p.network != nil && p.network.Pending != nil && p.network.Pending.Deadline <= time.Now().Unix() + p.mu.Unlock() + if expired { + p.rollbackNetwork() + } + } + } +} +func (p *Pairing) networkFailure(op string, err error) { + p.mu.Lock() + pending := p.network != nil && p.network.Pending != nil + p.mu.Unlock() + if pending { + p.rollbackNetwork() + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.network != nil && p.network.OperationID == op { + p.network.Phase = "failed" + p.network.Error = err.Error() + _ = p.saveNetworkLocked() + } +} +func (p *Pairing) applyNetworkCommand(raw json.RawMessage) { + if len(raw) == 0 || string(raw) == "null" { + return + } + var c NetworkCommand + if decodeRoverJSON(raw, &c) != nil || !networkOperationID.MatchString(c.ID) || c.ExpiresAt <= time.Now().Unix() || c.ExpiresAt > time.Now().Unix()+180 { + return + } + p.mu.Lock() + if p.loadNetworkLocked() != nil || p.state.Binding == nil || p.state.Phase != "paired" { + p.mu.Unlock() + return + } + n := p.network + if c.Action == "abort" && n.OperationID == c.ID { + p.mu.Unlock() + p.rollbackNetwork() + return + } + if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "applied" { + p.mu.Unlock() + return + } + if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) { + p.mu.Unlock() + return + } + if n.Pending != nil && n.OperationID != c.ID { + p.mu.Unlock() + return + } + if c.Action == "prepare" { + if n.OperationID == c.ID && n.Phase == "prepared" { + p.mu.Unlock() + return + } + n.OperationID = c.ID + n.Phase = "preparing" + n.Error = "" + _ = p.saveNetworkLocked() + p.mu.Unlock() + reply, err := p.callNetwork("prepare", c.ServerID, nil) + if err != nil { + p.networkFailure(c.ID, err) + return + } + var public string + _ = json.Unmarshal(reply["public_key"], &public) + p.mu.Lock() + defer p.mu.Unlock() + if p.network.OperationID != c.ID || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID { + return + } + p.network.PublicKey = public + p.network.Phase = "prepared" + _ = p.saveNetworkLocked() + return + } + if c.Action == "apply" { + if n.OperationID == c.ID && (n.Phase == "verifying" || n.Phase == "applied") { + p.mu.Unlock() + return + } + if c.Provider == "tailscale" { + if c.CoreEndpoint != n.TailscaleEndpoint || c.CoreEndpoint == "" { + p.mu.Unlock() + return + } + } else { + var config struct { + ServerID string `json:"server_id"` + Address string `json:"address"` + Subnet string `json:"subnet"` + Role string `json:"role"` + Allowed []string `json:"allowed_ips"` + } + if json.Unmarshal(c.Config, &config) != nil || config.ServerID != c.ServerID || config.Role != "node" { + p.mu.Unlock() + return + } + _, network, err := net.ParseCIDR(config.Subnet) + u, e := url.Parse(c.CoreEndpoint) + if err != nil || e != nil || !privateEndpoint(c.CoreEndpoint, CorePort) || !network.Contains(net.ParseIP(u.Hostname())) { + p.mu.Unlock() + return + } + found := false + for _, address := range config.Allowed { + if address == u.Hostname()+"/32" { + found = true + } + } + if !found { + p.mu.Unlock() + return + } + } + n.OperationID = c.ID + n.Phase = "preparing" + n.Error = "" + n.Pending = &NetworkPending{Deadline: time.Now().Unix() + 100, PreviousEndpoint: p.state.Binding.Endpoint, Provider: c.Provider, ServerID: c.ServerID, Config: c.Config} + if p.saveNetworkLocked() != nil { + p.mu.Unlock() + return + } + p.mu.Unlock() + if c.Provider == "wireguard" { + var config map[string]any + _ = json.Unmarshal(c.Config, &config) + if _, err := p.callNetwork("stage", c.ServerID, map[string]any{"config": config, "operation_id": c.ID}); err != nil { + p.networkFailure(c.ID, err) + return + } + } + p.mu.Lock() + defer p.mu.Unlock() + if p.network.OperationID != c.ID || p.network.Pending == nil || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID { + return + } + if err := p.networkEndpointLocked(c.CoreEndpoint); err != nil { + p.network.Phase = "failed" + p.network.Error = "Не удалось сохранить адрес Core." + } else { + p.network.Phase = "verifying" + } + _ = p.saveNetworkLocked() + return + } + if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "verifying" && n.Pending != nil { + pending := *n.Pending + oldServer := n.ServerID + p.mu.Unlock() + if pending.Provider == "wireguard" { + if _, err := p.callNetwork("confirm", pending.ServerID, map[string]any{"operation_id": c.ID}); err != nil { + p.networkFailure(c.ID, err) + return + } + } + + p.mu.Lock() + defer p.mu.Unlock() + if p.network.Pending == nil || p.network.OperationID != c.ID { + return + } + n = p.network + previous := *n + n.Provider = pending.Provider + n.ServerID = pending.ServerID + n.Config = pending.Config + n.Pending = nil + n.Phase = "applied" + n.Revision++ + n.Error = "" + if err := p.saveNetworkLocked(); err != nil { + *n = previous + return + } + if oldServer != "" && oldServer != pending.ServerID { + // The confirmed endpoint is durable before retiring the previous tunnel. + _, _ = p.callNetwork("disable", oldServer, nil) + } + return + } + p.mu.Unlock() +} +func (p *Pairing) networkAddressLocked(address string) bool { + if p.network == nil || p.network.Provider != "wireguard" { + return tailnetAddress(address) + } + var config struct { + Address string `json:"address"` + } + return json.Unmarshal(p.network.Config, &config) == nil && config.Address == address +} +func (p *Pairing) networkPeerLocked(address string) bool { + if tailnetAddress(address) { + return true + } + for _, raw := range []json.RawMessage{func() json.RawMessage { + if p.network != nil { + return p.network.Config + } + return nil + }(), func() json.RawMessage { + if p.network != nil && p.network.Pending != nil { + return p.network.Pending.Config + } + return nil + }()} { + var config struct { + Allowed []string `json:"allowed_ips"` + } + if json.Unmarshal(raw, &config) == nil { + for _, peer := range config.Allowed { + if peer == address+"/32" { + return true + } + } + } + } + return false +} +func (p *Pairing) networkLocalRoutes(mux *http.ServeMux, s *Server) { + mux.HandleFunc("GET /api/network/profile", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + reply(w, 200, p.networkSnapshot()) + }) + mux.HandleFunc("POST /api/network/profile/tailscale", func(w http.ResponseWriter, r *http.Request) { + if !s.authorized(w, r) { + return + } + p.mu.Lock() + _ = p.loadNetworkLocked() + if p.network == nil || p.network.TailscaleEndpoint == "" { + p.mu.Unlock() + reply(w, 409, map[string]string{"error": "Нет сохранённого подключения Tailscale."}) + return + } + op := digest(token())[:32] + command := NetworkCommand{ID: op, Action: "apply", Provider: "tailscale", ExpectedRevision: p.network.Revision, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: p.network.TailscaleEndpoint} + p.mu.Unlock() + raw, _ := json.Marshal(command) + p.applyNetworkCommand(raw) + p.mu.Lock() + if p.network.Pending != nil && p.network.OperationID == op { + p.network.Pending.Local = true + _ = p.saveNetworkLocked() + } + p.mu.Unlock() + reply(w, 200, p.networkSnapshot()) + }) +} + +// Only a successful authenticated heartbeat through the selected endpoint can +// confirm the local recovery action. It cannot authorize a remote arbitrary path. +func (p *Pairing) networkLocalAcknowledged(binding CoreBinding) { + p.mu.Lock() + n := p.network + if n == nil || n.Pending == nil || !n.Pending.Local || n.Phase != "verifying" || p.state.Binding == nil || p.state.Binding.Endpoint != binding.Endpoint { + p.mu.Unlock() + return + } + c := NetworkCommand{ID: n.OperationID, Action: "commit", Provider: n.Pending.Provider, ServerID: n.Pending.ServerID, ExpectedRevision: n.Revision, ExpiresAt: time.Now().Unix() + 30} + p.mu.Unlock() + raw, _ := json.Marshal(c) + p.applyNetworkCommand(raw) +} diff --git a/apps/node-agent/internal/node/network_profile_test.go b/apps/node-agent/internal/node/network_profile_test.go new file mode 100644 index 00000000..4f360a34 --- /dev/null +++ b/apps/node-agent/internal/node/network_profile_test.go @@ -0,0 +1,105 @@ +package node + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func networkFixture(t *testing.T) (*Pairing, NetworkCommand, *[]string) { + p, _ := testPairing(t) + b := testCoreBinding(t, p) + b.Endpoint = "https://100.64.1.2:8782" + b.EndpointRevision = 7 + if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil { + t.Fatal(err) + } + actions := []string{} + p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) { + actions = append(actions, action) + return map[string]json.RawMessage{"public_key": json.RawMessage(`"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE="`)}, nil + } + config := json.RawMessage(`{"server_id":"wg_11111111111111111111111111111111","address":"10.203.1.3","subnet":"10.203.1.0/24","role":"node","allowed_ips":["10.203.1.1/32","10.203.1.2/32"]}`) + c := NetworkCommand{ID: "22222222222222222222222222222222", Action: "apply", Provider: "wireguard", ServerID: "wg_11111111111111111111111111111111", ExpectedRevision: 0, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: "https://10.203.1.2:8782", Config: config} + return p, c, &actions +} +func networkSend(p *Pairing, c NetworkCommand) { raw, _ := json.Marshal(c); p.applyNetworkCommand(raw) } +func TestNetworkCommitIsIdempotentAndUsesNewEndpoint(t *testing.T) { + p, c, actions := networkFixture(t) + networkSend(p, c) + if p.network.Phase != "verifying" || p.network.Provider != "tailscale" || p.state.Binding.Endpoint != c.CoreEndpoint { + t.Fatal("unconfirmed profile became active") + } + revision := p.state.Binding.EndpointRevision + networkSend(p, c) + if p.state.Binding.EndpointRevision != revision { + t.Fatal("repeat changed endpoint revision") + } + c.Action = "commit" + networkSend(p, c) + networkSend(p, c) + if p.network.Revision != 1 || p.network.Provider != "wireguard" || p.network.Pending != nil { + t.Fatal("commit failed") + } + if len(*actions) != 2 || (*actions)[0] != "stage" || (*actions)[1] != "confirm" { + t.Fatal(*actions) + } +} +func TestNetworkRestartAndFailedStageRestoreConfirmedBinding(t *testing.T) { + p, c, _ := networkFixture(t) + networkSend(p, c) + p.network = nil // Reload durable state, exactly as a new Node process. + p.rollbackNetwork() + if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Phase != "rolled_back" || p.state.Binding.EndpointRevision != 9 { + t.Fatal("restart did not restore prior endpoint") + } + p, c, _ = networkFixture(t) + p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) { + if action == "stage" { + return nil, errors.New("test fault") + } + return nil, nil + } + networkSend(p, c) + if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Pending != nil { + t.Fatal("failed stage changed confirmed endpoint") + } +} +func TestNetworkRejectsStaleAndUnrelatedEndpoint(t *testing.T) { + for _, change := range []func(*NetworkCommand){func(c *NetworkCommand) { c.ExpectedRevision = 8 }, func(c *NetworkCommand) { c.CoreEndpoint = "https://192.168.1.10:8782" }, func(c *NetworkCommand) { c.ExpiresAt = time.Now().Unix() - 1 }} { + p, c, actions := networkFixture(t) + change(&c) + networkSend(p, c) + if len(*actions) != 0 || p.state.Binding.Endpoint != "https://100.64.1.2:8782" { + t.Fatal("invalid change reached root helper") + } + } +} + +func TestNetworkCommitStorageFailureKeepsRollbackState(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("permission fault requires unprivileged qualification") + } + p, c, _ := networkFixture(t) + networkSend(p, c) + dir := filepath.Dir(p.networkPath()) + if err := os.Chmod(dir, 0500); err != nil { + t.Fatal(err) + } + defer os.Chmod(dir, 0700) + c.Action = "commit" + networkSend(p, c) + if p.network.Provider != "tailscale" || p.network.Revision != 0 || p.network.Pending == nil || p.network.Phase != "verifying" { + t.Fatal("failed persistence changed confirmed state") + } + if err := os.Chmod(dir, 0700); err != nil { + t.Fatal(err) + } + p.rollbackNetwork() + if p.network.Provider != "tailscale" || p.network.Pending != nil || p.state.Binding.Endpoint != "https://100.64.1.2:8782" { + t.Fatal("rollback after storage failure failed") + } +} diff --git a/apps/node-agent/internal/node/pairing.go b/apps/node-agent/internal/node/pairing.go index 436c9650..49d2ca54 100644 --- a/apps/node-agent/internal/node/pairing.go +++ b/apps/node-agent/internal/node/pairing.go @@ -13,6 +13,8 @@ import ( "sort" "sync" "time" + + "nodedc.local/mission-core/node-agent/internal/routers" ) type Invitation struct { @@ -41,10 +43,14 @@ type PairState struct { Revocations []CoreBinding `json:"revocations,omitempty"` } type Pairing struct { + Budget *LinkBudget + Routers *routers.Collector RoverConfiguration *RoverConfigurationStore Monitor *Monitor Sensors *Sensors DeviceEnrollment *DeviceEnrollment + networkCall func(string, string, map[string]any) (map[string]json.RawMessage, error) + network *NetworkProfile mu sync.Mutex path string store *Store @@ -148,7 +154,7 @@ func (p *Pairing) status() map[string]any { defer p.mu.Unlock() _ = p.expire() id, _ := p.store.Public() - out := map[string]any{"phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)} + out := map[string]any{"network_profile": p.networkViewLocked(), "phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)} if i := p.state.Invitation; i != nil { out["invitation"] = map[string]any{"id": i.ID, "endpoint": i.Endpoint, "expires_at": i.ExpiresAt} } diff --git a/apps/node-agent/internal/node/pairing_budget_test.go b/apps/node-agent/internal/node/pairing_budget_test.go new file mode 100644 index 00000000..72ade069 --- /dev/null +++ b/apps/node-agent/internal/node/pairing_budget_test.go @@ -0,0 +1,147 @@ +package node + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestLinkHeartbeatWithDevAtFloor(t *testing.T) { + for _, devSize := range []int{0, 400, linkPacket} { + b, now := testBudget(t) + b.effective = float64(b.policy.ReserveKbps + 128) + delivered, devBytes := 0, 0 + deadline := pacedTimeout(40 * 1024) + for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond { + *now = now.Add(10 * time.Millisecond) + // Persistent congestion must not erase earned tokens at the floor. + if elapsed%time.Second == 0 { + b.Observe(time.Second, false) + } + b.Try("video", 1200) + b.Try("cloud", 1200) + if devSize > 0 { + if ok, _ := b.Try("bulk", devSize); ok { + devBytes += devSize + } + } + if delivered < 40*1024 { + size := min(linkPacket, 40*1024-delivered) + if ok, _ := b.Try("inventory", size); ok { + delivered += size + } + } + } + t.Logf("DEV packet=%d: heartbeat=%d/40960, DEV=%d, deadline=%v", devSize, delivered, devBytes, deadline) + if delivered != 40*1024 || (devSize > 0 && devBytes == 0) { + t.Fatal("optional traffic starved") + } + var charged uint64 + for _, class := range b.classes { + charged += class.bytes + } + if float64(charged) > 128*125*deadline.Seconds()+linkBurst { + t.Fatal("aggregate allowance exceeded") + } + } +} + +func TestLinkPacedTimeoutCoversLargestDiagnosticBlock(t *testing.T) { + b, now := testBudget(t) + b.effective = float64(b.policy.ReserveKbps + 128) + left := 108 * 1024 + deadline := pacedTimeout(left) + for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond { + *now = now.Add(10 * time.Millisecond) + for _, class := range []string{"video", "cloud", "inventory"} { + b.Try(class, 1200) + } + size := min(linkPacket, left) + if ok, _ := b.Try("bulk", size); ok { + left -= size + } + if left == 0 { + return + } + } + t.Fatal("export deadline below worst-case budget", left) +} + +func TestHeartbeatLivenessDuringBlockedSnapshot(t *testing.T) { + p, _ := testPairing(t) + binding := testCoreBinding(t, p) + p.state = PairState{Phase: "paired", Binding: &binding} + var lives atomic.Int64 + started := make(chan struct{}) + release := make(chan struct{}) + p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{ + Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/v1/node/liveness" { + raw, _ := io.ReadAll(r.Body) + var envelope map[string]any + json.Unmarshal(raw, &envelope) + if len(raw) > 2048 || envelope["host"] != nil || envelope["sensor_results"] != nil || envelope["monitor"] != nil { + t.Error("large snapshot or acknowledgements leaked into liveness") + } + if lives.Add(1) == 2 { + close(release) + } + } else { + close(started) + select { + case <-release: + case <-r.Context().Done(): + return nil, r.Context().Err() + } + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: make(http.Header)}, nil + }), + } + ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second) + defer cancel() + payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, + "node_id": "test", "execution_binding": map[string]string{"agent_instance_id": "test"}, + "core_endpoint": binding.Endpoint, "endpoint_revision": 0, + "host": strings.Repeat("x", 40*1024), "monitor": strings.Repeat("x", 100*1024)} + _, status, err := p.sendHeartbeat(ctx, binding, payload) + if err != nil || status != 200 || lives.Load() != 2 { + t.Fatal("snapshot blocked liveness", status, err, lives.Load()) + } + select { + case <-started: + default: + t.Fatal("snapshot was not sent") + } + if p.lastSeen == 0 || p.connection != "online" { + t.Fatal("live binding remained offline") + } +} + +func TestHeartbeatCancelledUploadJoinsBeforeReturn(t *testing.T) { + p, _ := testPairing(t) + binding := testCoreBinding(t, p) + p.state = PairState{Phase: "paired", Binding: &binding} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var finished atomic.Bool + p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{ + Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/v1/node/heartbeat" { + cancel() + <-r.Context().Done() + finished.Store(true) + return nil, r.Context().Err() + } + return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil + }), + } + _, _, err := p.sendHeartbeat(ctx, binding, map[string]any{}) + if err == nil || !finished.Load() { + t.Fatal("upload leaked after cancellation") + } +} diff --git a/apps/node-agent/internal/node/pairing_encoding_test.go b/apps/node-agent/internal/node/pairing_encoding_test.go new file mode 100644 index 00000000..2775484d --- /dev/null +++ b/apps/node-agent/internal/node/pairing_encoding_test.go @@ -0,0 +1,72 @@ +package node + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" +) + +func TestHeartbeatCompressionNegotiatedOnExistingAuthenticatedChannel(t *testing.T) { + for _, supported := range []bool{false, true} { + p, _ := testPairing(t) + b := testCoreBinding(t, p) + p.state = PairState{Phase: "paired", Binding: &b} + if supported { + budget, now := testBudget(t) + budget.tokens = linkBurst + budget.classes["inventory"].tokens = linkClassBurst + budget.classes["inventory"].seen = *now + p.Budget = budget + } + payload := map[string]any{"node_id": "fixture", "host": strings.Repeat("metadata", 8000)} + raw, _ := json.Marshal(payload) + seen := 0 + p.clients[b.BindingID+b.Endpoint+digest(b.ClientPEM)] = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + response := `{"ok":true}` + if r.URL.Path == "/v1/node/liveness" { + if supported { + response = `{"ok":true,"heartbeat_encoding":"gzip"}` + } + } else { + seen++ + wire, err := io.ReadAll(r.Body) + if err != nil { + t.Fatal(err) + } + decoded := wire + if supported { + if r.Header.Get("Content-Encoding") != "gzip" || len(wire) >= len(raw)/10 { + t.Error("heartbeat not compressed") + } + reader, err := gzip.NewReader(bytes.NewReader(wire)) + if err != nil { + t.Fatal(err) + } + decoded, err = io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + } else if r.Header.Get("Content-Encoding") != "" { + t.Error("old Core received unsupported encoding") + } + if !bytes.Equal(decoded, raw) || r.ContentLength != int64(len(wire)) { + t.Error("snapshot or framing changed") + } + } + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil + })} + _, status, err := p.sendHeartbeat(context.Background(), b, payload) + if err != nil || status != 200 || seen != 1 { + t.Fatal(status, err, seen) + } + if supported && p.Budget.classes["inventory"].bytes == 0 { + t.Fatal("compressed body bypassed shared budget") + } + } +} diff --git a/apps/node-agent/internal/node/pairing_liveness.go b/apps/node-agent/internal/node/pairing_liveness.go new file mode 100644 index 00000000..665b9f29 --- /dev/null +++ b/apps/node-agent/internal/node/pairing_liveness.go @@ -0,0 +1,77 @@ +package node + +import ( + "context" + "encoding/json" + "time" +) + +// A bounded keepalive on the existing authenticated Node HTTP transport. +// It cannot carry inventory, operation receipts or a motor lease. Old Core +// returns 404; full heartbeat remains backward-compatible. No retry queue. +func (p *Pairing) sendHeartbeat(ctx context.Context, b CoreBinding, payload map[string]any) (map[string]json.RawMessage, int, error) { + live := map[string]any{} + for _, key := range []string{"schema", "node_id", "binding_id", "execution_binding", "core_endpoint", "endpoint_revision"} { + live[key] = payload[key] + } + compressed := false + keepalive := func() { + result, status, err := p.send(ctx, b, "/v1/node/liveness", live) + var encoding string + if err == nil && status == 200 { + _ = json.Unmarshal(result["heartbeat_encoding"], &encoding) + } + compressed = encoding == "gzip" + p.mu.Lock() + defer p.mu.Unlock() + if p.sameBinding(b) && err == nil && status == 200 { + p.connection, p.lastSeen = "online", p.now().Unix() + } + } + // Initializes the shared two-connection client before the concurrent upload; + // the client map is owned by channel, and only read until this upload joins. + keepalive() + call, cancel := context.WithCancel(ctx) + defer cancel() + type outcome struct { + body map[string]json.RawMessage + status int + err error + } + done := make(chan outcome, 1) + go func(compress bool) { + body, status, err := p.sendEncoded(call, b, "/v1/node/heartbeat", payload, compress) + done <- outcome{body, status, err} + }(compressed) + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for { + select { + case result := <-done: + return result.body, result.status, result.err + case <-ctx.Done(): + cancel() + result := <-done + return result.body, result.status, result.err + case <-ticker.C: + p.mu.Lock() + current := p.sameBinding(b) + p.mu.Unlock() + if !current { + cancel() + result := <-done + return result.body, result.status, result.err + } + keepalive() + } + } +} + +// Caller holds p.mu. Endpoint revisions and certificate rotation invalidate an +// in-flight snapshot; an old upload cannot refresh a replacement binding. +func (p *Pairing) sameBinding(b CoreBinding) bool { + current := p.state.Binding + return p.state.Phase == "paired" && current != nil && + current.BindingID == b.BindingID && current.Endpoint == b.Endpoint && + current.EndpointRevision == b.EndpointRevision && current.ClientPEM == b.ClientPEM +} diff --git a/apps/node-agent/internal/node/pairing_recovery.go b/apps/node-agent/internal/node/pairing_recovery.go index b49e6697..1c395681 100644 --- a/apps/node-agent/internal/node/pairing_recovery.go +++ b/apps/node-agent/internal/node/pairing_recovery.go @@ -50,7 +50,10 @@ func (p *Pairing) recoveryHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") host, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil || !tailnetAddress(host) || r.TLS == nil { + p.mu.Lock() + allowedNetwork := p.networkPeerLocked(host) + p.mu.Unlock() + if err != nil || !allowedNetwork || r.TLS == nil { http.Error(w, "Private authenticated channel required", 403) return } @@ -80,7 +83,7 @@ func (p *Pairing) recoveryHandler() http.Handler { case "/v1/channel/inspect": case "/v1/channel/migrate": u, err := url.Parse(body.Endpoint) - if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !tailnetAddress(u.Hostname()) || u.Hostname() != host { + if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !p.networkPeerLocked(u.Hostname()) || u.Hostname() != host { http.Error(w, "Endpoint must address the authenticated Core transport", 400) return } diff --git a/apps/node-agent/internal/node/pairing_recovery_test.go b/apps/node-agent/internal/node/pairing_recovery_test.go index 79deb998..1a558972 100644 --- a/apps/node-agent/internal/node/pairing_recovery_test.go +++ b/apps/node-agent/internal/node/pairing_recovery_test.go @@ -169,6 +169,9 @@ func TestOldHeartbeatCannotRevokeMigratedBinding(t *testing.T) { entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) p.clients[old.BindingID+old.Endpoint+digest(old.ClientPEM)] = &http.Client{ Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/v1/node/liveness" { + return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil + } close(entered) <-release return &http.Response{StatusCode: 410, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil diff --git a/apps/node-agent/internal/node/pairing_transport.go b/apps/node-agent/internal/node/pairing_transport.go index 31843e67..7986c472 100644 --- a/apps/node-agent/internal/node/pairing_transport.go +++ b/apps/node-agent/internal/node/pairing_transport.go @@ -2,6 +2,7 @@ package node import ( "bytes" + "compress/gzip" "context" "crypto/tls" "encoding/json" @@ -151,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler { } func (p *Pairing) Run(ctx context.Context) { + go p.networkWatch(ctx) go p.channel(ctx) go p.roverChannel(ctx) var server *http.Server @@ -181,7 +183,7 @@ func (p *Pairing) Run(ctx context.Context) { } if p.state.Phase == "paired" && p.state.Binding != nil { for _, address := range p.addresses() { - if tailnetAddress(address) { + if p.networkAddressLocked(address) { desired = "https://" + address + ":" + PairPort copy := *p.state.Binding recovery = © @@ -230,6 +232,10 @@ func (p *Pairing) Run(ctx context.Context) { } } func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload any) (map[string]json.RawMessage, int, error) { + return p.sendEncoded(ctx, b, path, payload, false) +} + +func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, payload any, compress bool) (map[string]json.RawMessage, int, error) { config, e := bindingTLS(b, p.store.pairingKey()) if e != nil { return nil, 0, e @@ -237,19 +243,55 @@ func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload cacheKey := b.BindingID + b.Endpoint + digest(b.ClientPEM) client := p.clients[cacheKey] if client == nil { - transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 15 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext} - client = &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }} + transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 2, MaxIdleConnsPerHost: 2, IdleConnTimeout: 15 * time.Second, ResponseHeaderTimeout: 8 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext} + client = &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }} p.clients[cacheKey] = client } data, e := json.Marshal(payload) if e != nil { return nil, 0, e } - request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, bytes.NewReader(data)) + if len(data) > 8*1024*1024 { + return nil, 0, errors.New("Core envelope exceeds limit") + } + // Compress metadata only after the authenticated Core advertises support. + // Budget the actual wire body, retaining admission even if it shrinks below + // 4 KiB. The control reserve, transport and full-snapshot ACK stay unchanged. + paced := len(data) > 4096 && p.Budget != nil + encoding := "" + if compress && path == "/v1/node/heartbeat" && len(data) > 4096 { + var encoded bytes.Buffer + writer, _ := gzip.NewWriterLevel(&encoded, gzip.BestSpeed) + _, _ = writer.Write(data) + _ = writer.Close() + if encoded.Len() < len(data) { + data, encoding = encoded.Bytes(), "gzip" + } + } + timeout := 8 * time.Second + class := "bulk" + if path == "/v1/node/heartbeat" { + class = "inventory" + } + if paced { + timeout = pacedTimeout(len(data)) + } + call, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + ctx = call + var body io.Reader = bytes.NewReader(data) + if paced { + body = &budgetReader{ctx: ctx, source: body, budget: p.Budget, class: class} + } + request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, body) if e != nil { return nil, 0, e } + request.ContentLength = int64(len(data)) request.Header.Set("Content-Type", "application/json") + if encoding != "" { + request.Header.Set("Content-Encoding", encoding) + } response, e := client.Do(request) if e != nil { return nil, 0, e @@ -304,6 +346,7 @@ func (p *Pairing) channel(ctx context.Context) { if p.RoverConfiguration != nil { payload["rover_configuration"] = p.RoverConfiguration.Snapshot() } + payload["network_profile"] = p.networkSnapshot() payload["core_endpoint"] = binding.Endpoint payload["endpoint_revision"] = binding.EndpointRevision if p.Sensors != nil { @@ -322,11 +365,18 @@ func (p *Pairing) channel(ctx context.Context) { if p.Monitor != nil { payload["monitor"] = p.Monitor.Snapshot() } - result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload) + if p.Routers != nil { + payload["routers"] = p.Routers.Snapshot() + } + result, status, e := p.sendHeartbeat(ctx, *binding, payload) + var networkChange json.RawMessage var configurationChange json.RawMessage + var routerCommands json.RawMessage p.mu.Lock() if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision { if e == nil && status == 200 { + networkChange = result["network_profile_change"] + routerCommands = result["router_commands"] if p.RoverConfiguration != nil { configurationChange = result["rover_configuration_change"] } @@ -375,11 +425,16 @@ func (p *Pairing) channel(ctx context.Context) { next.Phase = "revoked" _ = p.save(next) p.connection = "revoked" - } else { + } else if p.now().Unix()-p.lastSeen >= 20 { p.connection = "offline" } } p.mu.Unlock() + if e == nil && status == http.StatusOK { + p.networkLocalAcknowledged(*binding) + } + p.applyNetworkCommand(networkChange) + p.applyRouterCommands(routerCommands) // Durable preference IO must not hold the pairing/control mutex. if p.RoverConfiguration != nil { p.RoverConfiguration.Apply(configurationChange) diff --git a/apps/node-agent/internal/node/rover_channel.go b/apps/node-agent/internal/node/rover_channel.go index 329b6e22..930d3e4a 100644 --- a/apps/node-agent/internal/node/rover_channel.go +++ b/apps/node-agent/internal/node/rover_channel.go @@ -12,7 +12,6 @@ import ( "errors" "io" "log" - "net" "net/http" "sync" "time" @@ -57,12 +56,7 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) { if err != nil { return } - transport := func() *http.Transport { - return &http.Transport{TLSClientConfig: config, Proxy: nil, - MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second, - TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second, - DialContext: (&net.Dialer{Timeout: time.Second}).DialContext} - } + transport := func() *http.Transport { return newRoverHTTPTransport(config) } telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }} stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect} defer telemetry.CloseIdleConnections() @@ -76,10 +70,14 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) { base := map[string]any{"schema": PairSchema, "node_id": id, "binding_id": b.BindingID, "core_endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision, "relay_id": relay} state := newRoverStreamState(time.Now()) + state.budget = p.Budget ctx, cancel := context.WithCancel(parent) var workers sync.WaitGroup defer func() { cancel(); workers.Wait() }() - workers.Add(2) + workers.Add(3) + optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect} + defer optional.CloseIdleConnections() + go func() { defer workers.Done(); roverDiagnosticsLane(ctx, optional, b.Endpoint, base, state) }() go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }() go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }() var model *sensorModel @@ -92,32 +90,17 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) { if model == nil { return } - var diagnostic roverDiagnostics + workers.Add(1) + go func() { defer workers.Done(); p.roverDev(ctx, model, state) }() + diagnostic := roverDiagnostics{lane: "local", epoch: relay, started: state.origin} + var delivery roverLocalDelivery for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) { select { case <-state.wake: default: } started := time.Now() - watch, command, stop := state.delivery(started) - frame := roverFrame{} - if command != nil { - frame.Session, _ = command["id"].(string) - frame.Sequence, _ = command["sequence"].(float64) - frame.TTLMS, _ = command["ttl_ms"].(float64) - } - call, done := context.WithTimeout(ctx, 25*time.Millisecond) - result, driverErr := p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay}) - done() - frame.DriverMS = time.Since(started).Milliseconds() - if driverErr != nil { - state.stopStream() - frame.Stage = "driver_transport" - state.delivered(map[string]any{}, 0) - } else { - state.delivered(result, stop) - frame.State, _ = result["state"].(string) - } + frame := delivery.run(ctx, p.Sensors, model, state, relay, started) diagnostic.record(started, frame) // New intent and stop signals bypass the periodic watchdog tick. The // buffered wake channel coalesces arrivals; it never queues commands. @@ -135,30 +118,86 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) { done() } func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) { - var diagnostic roverDiagnostics + epoch, _ := base["relay_id"].(string) + diagnostic := roverDiagnostics{lane: "telemetry", epoch: epoch, started: state.origin} + var budgetAt time.Time + var metadata roverMetadataEncoder + connected := false for ctx.Err() == nil { + if !connected { + connected = roverConnectTelemetry(ctx, client, endpoint, base, state) + budgetAt = time.Time{} + metadata.reset() + if !connected { + if !roverWait(ctx, 250*time.Millisecond) { + return + } + continue + } + } + // Keep transport liveness separate from sample freshness. A stamped + // observation ages in transit; waiting for its reply cannot renew motion. started := time.Now() - snapshot, _ := state.view() + snapshot, sampleClock := state.telemetryView() payload := make(map[string]any, len(base)+1) for k, v := range base { payload[k] = v } payload["rover"] = snapshot + state.mu.Lock() + budgetInterval := state.budgetInterval + compact := state.roverDetails + state.mu.Unlock() + if compact { + live, details := metadata.encode(snapshot, started) + if details != nil { + payload["rover"], payload["rover_details_v1"] = live, details + } + } + if state.budget != nil && (!budgetInterval || budgetAt.IsZero() || started.Sub(budgetAt) >= time.Second) { + payload["link_budget"] = state.budget.Snapshot() + budgetAt = started + } + requestClient := *client + if sampleClock != nil { + payload["sample_clock"] = sampleClock + requestClient.Timeout = 2 * time.Second + } + state.mu.Lock() + dedicated := state.diagnosticLane + state.mu.Unlock() + payload["diagnostic_lane_v1"] = dedicated + payload["diagnostic_options_v1"] = true + if !dedicated { + if dev := state.devPayload(); dev != nil { + payload["diagnostics"] = dev + payload["diagnostic_relay_ack_v1"] = true + } + } + marshalAt := time.Now() raw, _ := json.Marshal(payload) + marshalMS := float64(time.Since(marshalAt).Microseconds()) / 1000 + state.budget.ObserveCriticalBytes(len(raw)) req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw)) req.Header.Set("Content-Type", "application/json") - frame := roverFrame{} + var trace *roverHTTPTrace + if state.devTraceEnabled() { + trace = newRoverHTTPTrace(started, len(raw)) + req = req.WithContext(trace.context(req.Context())) + } + frame := roverFrame{MarshalMS: marshalMS, RequestBytes: len(raw), ReleaseConfirmed: roverReleaseEvidence(snapshot)} frame.State, _ = snapshot["state"].(string) if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" { frame.Session, _ = snapshot["session_id"].(string) } - response, err := client.Do(req) + processingMS := 0.0 + response, err := requestClient.Do(req) if err != nil { frame.Stage = "telemetry_transport" } else { frame.Status = response.StatusCode var out roverStreamReply - readErr := json.NewDecoder(io.LimitReader(response.Body, 32768)).Decode(&out) + readErr := json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&out) response.Body.Close() if readErr != nil || response.StatusCode != 200 { frame.Stage = "telemetry_response" @@ -166,10 +205,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b frame.Stage = "clock_invalid" state.stopStream() } else { + processingMS = out.CoreProcessingMS + state.mu.Lock() + state.diagnosticPending = out.DiagnosticsPending + hasIntent := state.command != nil + state.mu.Unlock() + state.budget.SetControl(roverControlActive(snapshot, hasIntent, out.ControlActive)) state.setWatch(out.Watch) + state.setDev(out.Diagnostics) } } + if frame.Stage != "" { + connected = false + } + frame.CoreProcessingMS = processingMS frame.CoreMS = time.Since(started).Milliseconds() + if frame.Stage == "" || frame.Stage == "telemetry_transport" { + state.budget.ObserveExchange(time.Since(started), processingMS, frame.Stage == "") + } + details := map[string]any{"elapsed_ms": frame.CoreMS, "http_status": frame.Status, "error_stage": frame.Stage, "reason": roverErrorKind(err), "marshal_ms": marshalMS, "request_bytes": len(raw), "core_processing_ms": processingMS, "epoch": epoch, "sample_mono_ms": float64(started.Sub(state.origin).Microseconds()) / 1000} + if trace != nil { + details["transport"] = trace.snapshot() + } + state.recordDev("telemetry", details) diagnostic.record(started, frame) _, watch := state.view() delay := 500 * time.Millisecond @@ -182,18 +240,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b } } func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) { + defer state.budget.DisableDatagramFeedback() for ctx.Err() == nil { _, watch := state.view() if !watch { + state.budget.DisableDatagramFeedback() if !roverWait(ctx, 50*time.Millisecond) { return } continue } - err := roverReadStream(ctx, client, endpoint, base, state) + state.mu.Lock() + datagram := state.latestDatagram + state.mu.Unlock() + var err error + if datagram { + err = roverReadDatagram(ctx, client, endpoint, base, state) + } else { + err = roverReadStream(ctx, client, endpoint, base, state) + } state.stopStream() if err != nil && ctx.Err() == nil { - log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\"}") + log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\",\"reason\":%q}", roverErrorKind(err)) + state.recordDev("stream_disconnected", map[string]any{"reason": roverErrorKind(err)}) } if !roverWait(ctx, 250*time.Millisecond) { return @@ -223,6 +292,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin first := true for { line, err := reader.ReadSlice('\n') + received := time.Now() if err != nil { return err } @@ -239,6 +309,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin if !state.accept(out) { return errors.New("invalid stream intent") } + state.receivedFrame(out, received) if !out.Watch { return nil } diff --git a/apps/node-agent/internal/node/rover_control_activity.go b/apps/node-agent/internal/node/rover_control_activity.go new file mode 100644 index 00000000..b630d634 --- /dev/null +++ b/apps/node-agent/internal/node/rover_control_activity.go @@ -0,0 +1,20 @@ +package node + +// A terminal status is history, not continuing command authority. The driver +// reports its actual worker/lease, including cleanup before the worker exits. +// Older drivers use explicit known states; an unknown projection reserves +// control until a fresh authoritative snapshot arrives. +func roverControlActive(snapshot map[string]any, hasIntent bool, coreActive *bool) bool { + if hasIntent || (coreActive != nil && *coreActive) { + return true + } + if active, ok := snapshot["control_active"].(bool); ok { + return active + } + switch snapshot["state"] { + case "observing", "stopped", "receiver", "fault": + return false + default: + return true + } +} diff --git a/apps/node-agent/internal/node/rover_control_activity_test.go b/apps/node-agent/internal/node/rover_control_activity_test.go new file mode 100644 index 00000000..c5ce8f43 --- /dev/null +++ b/apps/node-agent/internal/node/rover_control_activity_test.go @@ -0,0 +1,75 @@ +package node + +import ( + "testing" + "time" +) + +func TestRoverActivitySeparatesTerminalHistoryFromLiveAuthority(t *testing.T) { + yes, no := true, false + for _, state := range []string{"fault", "stopped", "receiver", "observing"} { + for _, explicit := range []bool{false, true} { + snapshot := map[string]any{"state": state, "release_confirmed": false} + if explicit { + snapshot["control_active"] = false + } + if roverControlActive(snapshot, false, &no) { + t.Fatal("terminal history took control reserve", state) + } + if !roverControlActive(snapshot, true, &no) || !roverControlActive(snapshot, false, &yes) { + t.Fatal("live intent lost priority", state) + } + snapshot["control_active"] = true + if !roverControlActive(snapshot, false, &no) { + t.Fatal("live cleanup worker lost priority", state) + } + } + } + for _, state := range []string{"preparing", "ready", "driving", "stopping", "", "future-state"} { + if !roverControlActive(map[string]any{"state": state}, false, nil) { + t.Fatal("legacy active/unknown state lost reserve", state) + } + } +} + +func TestTerminalFaultAllowsInventoryWithoutAnObservatoryOrCommandFrames(t *testing.T) { + b, now := testBudget(t) + b.SetControl(true) + b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond) + if !b.commandLimited(*now) { + t.Fatal("missing initial command pressure") + } + b.effective = float64(b.policy.ReserveKbps + 128) + delivered := 0 + stopped := map[string]any{"state": "fault", "control_active": false, "release_confirmed": false} + for elapsed := time.Duration(0); elapsed < 20*time.Second; elapsed += 10 * time.Millisecond { + *now = now.Add(10 * time.Millisecond) + // A closed observatory intentionally sends no stream frames. Driver and + // board telemetry still refresh their actual inactive state. + if elapsed%(500*time.Millisecond) == 0 { + b.SetControl(roverControlActive(stopped, false, nil)) + } + b.ObserveCommandSilence() + if b.commandLimited(*now) { + t.Fatal("closed observer starved inventory again") + } + if delivered < 40*1024 { + size := min(linkPacket, 40*1024-delivered) + if ok, _ := b.Try("inventory", size); ok { + delivered += size + } + } + } + if delivered != 40*1024 { + t.Fatal("inventory never recovered", delivered) + } + // Resuming real control must still respond to a new delayed frame. + b.SetControl(true) + b.ObserveCommandFrame(151*time.Millisecond, 20*time.Millisecond) + if ok, _ := b.Try("inventory", 100); ok { + t.Fatal("inventory bypassed active command pressure") + } + if b.reserve(*now) < 512 { + t.Fatal("control reserve changed") + } +} diff --git a/apps/node-agent/internal/node/rover_datagram.go b/apps/node-agent/internal/node/rover_datagram.go new file mode 100644 index 00000000..d7de7e8c --- /dev/null +++ b/apps/node-agent/internal/node/rover_datagram.go @@ -0,0 +1,218 @@ +package node + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/url" + "strconv" + "time" +) + +type roverDatagramGrant struct { + Channel string `json:"channel"` + SendKey string `json:"send_key"` + ReceiveKey string `json:"receive_key"` + Port int `json:"port"` + MaxPacket int `json:"max_packet"` + Lifetime int `json:"lifetime_s"` +} +type roverDatagramFrame struct { + Probe uint64 `json:"probe"` + ProbeClock roverClock `json:"probe_clock"` + Reply roverStreamReply `json:"reply"` +} +type roverDatagramReceived struct { + raw []byte + counter uint64 + at time.Time +} + +func roverReadDatagram(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) error { + // Only the paired mTLS connection can disclose the ephemeral keys. No UDP + // packet establishes identity, grants motion or chooses a different endpoint. + raw, _ := json.Marshal(base) + setup, cancel := context.WithTimeout(ctx, 2500*time.Millisecond) + defer cancel() + req, err := http.NewRequestWithContext(setup, "POST", endpoint+"/v1/node/rover-datagram", bytes.NewReader(raw)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + response, err := client.Do(req) + if err != nil { + return err + } + var grant roverDatagramGrant + err = json.NewDecoder(io.LimitReader(response.Body, 2048)).Decode(&grant) + response.Body.Close() + if err != nil || response.StatusCode != 200 || grant.Port < 1 || grant.Port > 65535 || grant.MaxPacket != roverDatagramLimit || grant.Lifetime != 86400 { + return errors.New("datagram negotiation rejected") + } + tx, err := newRoverDatagramCipher(grant.Channel, grant.SendKey) + if err != nil { + return err + } + rx, err := newRoverDatagramCipher(grant.Channel, grant.ReceiveKey) + if err != nil { + return err + } + parsed, err := url.Parse(endpoint) + if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" { + return errors.New("invalid datagram endpoint") + } + address, err := net.ResolveUDPAddr("udp4", net.JoinHostPort(parsed.Hostname(), strconv.Itoa(grant.Port))) + if err != nil { + return err + } + conn, err := net.DialUDP("udp4", nil, address) + if err != nil { + return err + } + return roverReceiveDatagrams(ctx, conn, tx, rx, grant.Channel, state) +} + +func roverReceiveDatagrams(ctx context.Context, conn *net.UDPConn, tx, rx *roverDatagramCipher, channel string, state *roverStreamState) error { + // A one-element mailbox replaces unread datagrams; no old command backlog + // is replayed after a scheduling pause. Only authenticated packets enter it. + incoming := make(chan roverDatagramReceived, 1) + done := make(chan struct{}) + go func() { + defer close(done) + for { + packet := make([]byte, roverDatagramLimit+1) + n, err := conn.Read(packet) + if err != nil { + return + } + at := time.Now() + raw, counter, ok := rx.open(packet[:n]) + if !ok { + continue + } + item := roverDatagramReceived{raw, counter, at} + select { + case incoming <- item: + default: + select { + case <-incoming: + default: + } + select { + case incoming <- item: + default: + } + } + } + }() + defer func() { conn.Close(); <-done }() + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + // Startup has no command authority. Once a valid first frame arrives, the + // exact same 350 ms authority guard applies. Silence does not close a + // usable UDP socket; a separate 2 s bound renegotiates expired transport keys. + lastFrame := time.Now() + seenFrame, suspended := false, false + guard := time.NewTimer(2 * time.Second) + defer guard.Stop() + state.budget.EnableDatagramFeedback() + suspend := func() { + if suspended { + return + } + state.stopStream() // Retire authority now; never replay it on recovery. + suspended = true + state.recordDev("stream_suspended", map[string]any{"reason": "datagram_stream_deadline", "channel": channel}) + } + type probeSample struct { + at time.Time + optionalBytes uint64 + } + probes := map[uint64]probeSample{} + send := func() error { + packet, err := tx.seal([]byte("{}")) + if err != nil { + return err + } + now := time.Now() + probes[tx.sent] = probeSample{now, state.budget.DatagramFeedbackMark()} + state.budget.ObserveCriticalBytes(len(packet)) + for seq, sample := range probes { + if now.Sub(sample.at) > 2*time.Second { + delete(probes, seq) + } + } + conn.SetWriteDeadline(now.Add(25 * time.Millisecond)) + _, err = conn.Write(packet) + return err + } + if err := send(); err != nil { + return err + } + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-done: + return errors.New("datagram socket closed") + case <-guard.C: + // A stale mailbox item may have suspended authority before this + // timer branch runs. Only elapsed silence expires the transport; + // suspension itself is never evidence of a 2 s link outage. + if time.Since(lastFrame) >= 2*time.Second { + return errors.New("datagram link timeout") + } + suspend() + guard.Reset(max(0, 2*time.Second-time.Since(lastFrame))) + case <-ticker.C: + if err := send(); err != nil { + return err + } + case item := <-incoming: + // Check elapsed time even when both a packet and the timer are ready. + // Receipt can restore transport health, never an interrupted lease. + if time.Since(lastFrame) >= 2*time.Second { + return errors.New("datagram link timeout") + } + if seenFrame && time.Since(lastFrame) >= 350*time.Millisecond { + suspend() + } + if time.Since(item.at) >= 350*time.Millisecond { + suspend() + continue // Discard delayed local work without closing the receiver. + } + var frame roverDatagramFrame + if json.Unmarshal(item.raw, &frame) != nil { + return errors.New("invalid datagram frame") + } + if sent, ok := probes[frame.Probe]; ok { + if !state.sampleClock(frame.ProbeClock, sent.at, item.at) { + return errors.New("invalid datagram clock") + } + state.budget.ObserveDatagramFeedback(item.at.Sub(sent.at), frame.Reply.Clock.MonotonicMS-frame.ProbeClock.MonotonicMS, sent.optionalBytes) + for seq := range probes { + if seq <= frame.Probe { + delete(probes, seq) + } + } + } + if !state.accept(frame.Reply) { + return errors.New("invalid datagram intent") + } + state.receivedFrame(frame.Reply, item.at) + state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44}) + if !frame.Reply.Watch { + return nil + } + if suspended { + state.recordDev("stream_resumed", map[string]any{"channel": channel, "gap_ms": float64(item.at.Sub(lastFrame).Microseconds()) / 1000}) + } + lastFrame, seenFrame, suspended = item.at, true, false + guard.Reset(max(0, 350*time.Millisecond-time.Since(item.at))) + } + } +} diff --git a/apps/node-agent/internal/node/rover_datagram_codec.go b/apps/node-agent/internal/node/rover_datagram_codec.go new file mode 100644 index 00000000..5e255bf9 --- /dev/null +++ b/apps/node-agent/internal/node/rover_datagram_codec.go @@ -0,0 +1,68 @@ +package node + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "encoding/binary" + "encoding/hex" + "errors" +) + +const roverDatagramLimit = 1200 +const roverDatagramCounterLimit = 1<<32 - 1 + +// Keys are independent in each direction and exist only for this negotiated +// generation. The authenticated counter is both nonce and anti-replay order. +type roverDatagramCipher struct { + channel []byte + aead cipher.AEAD + sent, received uint64 +} + +func newRoverDatagramCipher(channel, key string) (*roverDatagramCipher, error) { + id, e1 := hex.DecodeString(channel) + raw, e2 := hex.DecodeString(key) + if e1 != nil || e2 != nil || len(id) != 16 || len(raw) != 32 { + return nil, errors.New("invalid datagram key") + } + block, err := aes.NewCipher(raw) + if err != nil { + return nil, err + } + aead, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + return &roverDatagramCipher{channel: id, aead: aead}, nil +} +func (c *roverDatagramCipher) seal(raw []byte) ([]byte, error) { + if len(raw)+44 > roverDatagramLimit || c.sent >= roverDatagramCounterLimit { + return nil, errors.New("datagram bound exceeded") + } + c.sent++ + header := make([]byte, 28) + copy(header, "MCR1") + copy(header[4:], c.channel) + binary.BigEndian.PutUint64(header[20:], c.sent) + nonce := make([]byte, 12) + copy(nonce[4:], header[20:]) + return c.aead.Seal(header, nonce, raw, header), nil +} +func (c *roverDatagramCipher) open(packet []byte) ([]byte, uint64, bool) { + if len(packet) <= 44 || len(packet) > roverDatagramLimit || string(packet[:4]) != "MCR1" || !bytes.Equal(packet[4:20], c.channel) { + return nil, 0, false + } + counter := binary.BigEndian.Uint64(packet[20:28]) + if counter <= c.received || counter > roverDatagramCounterLimit { + return nil, 0, false + } + nonce := make([]byte, 12) + copy(nonce[4:], packet[20:28]) + raw, err := c.aead.Open(nil, nonce, packet[28:], packet[:28]) + if err != nil { + return nil, 0, false + } + c.received = counter + return raw, counter, true +} diff --git a/apps/node-agent/internal/node/rover_datagram_codec_test.go b/apps/node-agent/internal/node/rover_datagram_codec_test.go new file mode 100644 index 00000000..5dec7b81 --- /dev/null +++ b/apps/node-agent/internal/node/rover_datagram_codec_test.go @@ -0,0 +1,43 @@ +package node + +import ( + "bytes" + "encoding/hex" + "testing" +) + +func TestRoverDatagramAuthenticationAndOrdering(t *testing.T) { + channel := "11111111111111111111111111111111" + key := "2222222222222222222222222222222222222222222222222222222222222222" + tx, _ := newRoverDatagramCipher(channel, key) + rx, _ := newRoverDatagramCipher(channel, key) + a, _ := tx.seal([]byte("{}")) + b, _ := tx.seal([]byte("{\"fresh\":true}")) + corrupt := append([]byte(nil), b...) + corrupt[len(corrupt)-1] ^= 1 + if _, _, ok := rx.open(corrupt); ok { + t.Fatal("forgery accepted") + } + if raw, seq, ok := rx.open(b); !ok || seq != 2 || !bytes.Equal(raw, []byte("{\"fresh\":true}")) { + t.Fatal("fresh frame rejected") + } + for _, packet := range [][]byte{a, b, append(b, 0), b[:20]} { + if _, _, ok := rx.open(packet); ok { + t.Fatal("stale/malformed accepted") + } + } + other, _ := newRoverDatagramCipher(channel, "3333333333333333333333333333333333333333333333333333333333333333") + if _, _, ok := other.open(b); ok { + t.Fatal("opposite direction accepted") + } + tx.sent = roverDatagramCounterLimit + if _, err := tx.seal([]byte("{}")); err == nil { + t.Fatal("counter wrapped") + } + if _, err := rx.seal(make([]byte, 1200)); err == nil { + t.Fatal("oversized datagram") + } + if hex.EncodeToString(a) != "4d43523111111111111111111111111111111111000000000000000108b7c9b2eb8c526f9dc03ac92264617fd09b" { + t.Fatal("Python/Go vector mismatch") + } +} diff --git a/apps/node-agent/internal/node/rover_datagram_continuity_test.go b/apps/node-agent/internal/node/rover_datagram_continuity_test.go new file mode 100644 index 00000000..b635ddf9 --- /dev/null +++ b/apps/node-agent/internal/node/rover_datagram_continuity_test.go @@ -0,0 +1,218 @@ +package node + +// Bounded loopback receiver tests. No driver, serial port or physical actuator. +import ( + "context" + "encoding/json" + "fmt" + "net" + "testing" + "time" +) + +type continuityRig struct { + t *testing.T + state *roverStreamState + peer *net.UDPConn + address *net.UDPAddr + tx, rx *roverDatagramCipher + result chan error + ended bool + origin time.Time +} + +func newContinuityRig(t *testing.T) *continuityRig { + t.Helper() + peer, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")}) + if err != nil { + t.Fatal(err) + } + conn, err := net.DialUDP("udp4", nil, peer.LocalAddr().(*net.UDPAddr)) + if err != nil { + peer.Close() + t.Fatal(err) + } + const channel = "11111111111111111111111111111111" + const a = "2222222222222222222222222222222222222222222222222222222222222222" + const b = "3333333333333333333333333333333333333333333333333333333333333333" + tx, _ := newRoverDatagramCipher(channel, a) + rx, _ := newRoverDatagramCipher(channel, b) + ptx, _ := newRoverDatagramCipher(channel, b) + prx, _ := newRoverDatagramCipher(channel, a) + now := time.Now() + s := newRoverStreamState(now) + s.budget, err = OpenLinkBudget("") + if err != nil { + t.Fatal(err) + } + s.setDev(map[string]any{"id": testClockID, "enabled": true}) + f := &continuityRig{t: t, state: s, peer: peer, tx: ptx, rx: prx, result: make(chan error, 1), origin: now} + ctx, cancel := context.WithCancel(context.Background()) + go func() { f.result <- roverReceiveDatagrams(ctx, conn, tx, rx, channel, s) }() + t.Cleanup(func() { + cancel() + peer.Close() + if !f.ended { + select { + case <-f.result: + case <-time.After(time.Second): + t.Error("receiver leaked") + } + } + }) + f.send("", 0) + f.ackStop() + return f +} +func (f *continuityRig) clock() roverClock { + return roverClock{testClockID, 10000 + float64(time.Since(f.origin).Microseconds())/1000} +} +func (f *continuityRig) send(id string, seq float64) []byte { + f.t.Helper() + f.peer.SetReadDeadline(time.Now().Add(time.Second)) + packet := make([]byte, 1201) + n, addr, err := f.peer.ReadFromUDP(packet) + if err != nil { + f.t.Fatal(err) + } + _, probe, ok := f.rx.open(packet[:n]) + if !ok { + f.t.Fatal("invalid probe") + } + f.address = addr + clock := f.clock() + reply := roverStreamReply{Watch: true, Clock: clock} + if id != "" { + reply.Command = map[string]any{"id": id, "sequence": seq, "left": float64(0), "right": float64(0), "settings": map[string]any{}, "expires_mono_ms": clock.MonotonicMS + 400} + } + raw, _ := json.Marshal(roverDatagramFrame{Probe: probe, ProbeClock: clock, Reply: reply}) + sealed, err := f.tx.seal(raw) + if err != nil { + f.t.Fatal(err) + } + f.state.mu.Lock() + before := f.state.streamReceived + f.state.mu.Unlock() + if _, err = f.peer.WriteToUDP(sealed, addr); err != nil { + f.t.Fatal(err) + } + f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.streamReceived.After(before) }, time.Second) + return sealed +} +func (f *continuityRig) wait(check func() bool, limit time.Duration) { + f.t.Helper() + until := time.Now().Add(limit) + for time.Now().Before(until) { + if check() { + return + } + select { + case err := <-f.result: + f.ended = true + f.t.Fatalf("transport ended instead of staying connected: %v", err) + default: + } + time.Sleep(time.Millisecond) + } + f.t.Fatal("bounded condition not reached") +} +func (f *continuityRig) ackStop() { + _, _, revision := f.state.delivery(time.Now()) + f.state.delivered(map[string]any{"state": "stopped", "release_confirmed": true}, revision) +} +func (f *continuityRig) command() map[string]any { _, c, _ := f.state.delivery(time.Now()); return c } +func (f *continuityRig) awaitSafetyStop() { + f.t.Helper() + f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.stopPending }, 450*time.Millisecond) + if c := f.command(); c != nil { + f.t.Fatal("motion authority retained after silence") + } +} +func TestRoverDatagramSilenceStopsAuthorityWithoutClosingTransport(t *testing.T) { + f := newContinuityRig(t) + old := "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + f.send(old, 1) + if f.command() == nil { + t.Fatal("neutral fixture not admitted") + } + f.awaitSafetyStop() + f.ackStop() + f.send(old, 2) + if f.command() != nil { + t.Fatal("retired authority revived") + } + f.send("cccccccccccccccccccccccccccccccc", 1) + if c := f.command(); c == nil || c["left"] != float64(0) || c["right"] != float64(0) { + t.Fatal("fresh neutral identity not admitted on existing transport") + } +} +func TestRoverDatagramReplayCannotKeepAuthorityAlive(t *testing.T) { + f := newContinuityRig(t) + raw := f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1) + for n := 0; n < 8; n++ { + time.Sleep(50 * time.Millisecond) + f.peer.WriteToUDP(raw, f.address) + } + f.awaitSafetyStop() + f.ackStop() + f.send("cccccccccccccccccccccccccccccccc", 1) + if f.command() == nil { + t.Fatal("authenticated channel failed to recover") + } +} +func TestRoverDatagramProlongedSilenceRenegotiatesAfterSafetyStop(t *testing.T) { + f := newContinuityRig(t) + f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1) + f.awaitSafetyStop() + f.ackStop() + select { + case err := <-f.result: + f.ended = true + if err == nil || err.Error() != "datagram link timeout" { + t.Fatalf("wrong reconnect cause: %v", err) + } + case <-time.After(2100 * time.Millisecond): + t.Fatal("silent transport did not renegotiate") + } + if f.command() != nil { + t.Fatal("authority retained during reconnect") + } +} + +// Both the expired guard and a stale mailbox item can be ready after local +// scheduling pauses. Exercise both select orders without a physical driver. +func TestRoverDatagramDelayedLocalWorkRetainsRecoveryWindow(t *testing.T) { + for attempt := 0; attempt < 12; attempt++ { + t.Run(fmt.Sprint(attempt), func(t *testing.T) { + f := newContinuityRig(t) + f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1) + f.state.mu.Lock() + previousCommand := f.state.command + f.state.mu.Unlock() + queue := func() { + raw, _ := json.Marshal(roverDatagramFrame{Reply: roverStreamReply{Watch: true, Clock: f.clock(), Command: previousCommand}}) + packet, err := f.tx.seal(raw) + if err != nil { + t.Fatal(err) + } + if _, err = f.peer.WriteToUDP(packet, f.address); err != nil { + t.Fatal(err) + } + } + func() { + f.state.mu.Lock() + defer f.state.mu.Unlock() + queue() + time.Sleep(30 * time.Millisecond) + queue() + time.Sleep(400 * time.Millisecond) + }() + f.awaitSafetyStop() + f.ackStop() + f.send("cccccccccccccccccccccccccccccccc", 1) + if f.command() == nil { + t.Fatal("fresh neutral authority not admitted after local pause") + } + }) + } +} diff --git a/apps/node-agent/internal/node/rover_dev.go b/apps/node-agent/internal/node/rover_dev.go new file mode 100644 index 00000000..ca9d1ca1 --- /dev/null +++ b/apps/node-agent/internal/node/rover_dev.go @@ -0,0 +1,206 @@ +package node + +// Optional recorder transport is independent of the 25 ms motor-delivery path. +// No files, controller queries, command retries or lease changes originate here. +import ( + "context" + "encoding/json" + "errors" + "io" + "net" + "time" +) + +func roverErrorKind(err error) string { + if err == nil { + return "" + } + if errors.Is(err, context.DeadlineExceeded) { + return "deadline" + } + if errors.Is(err, context.Canceled) { + return "cancelled" + } + if errors.Is(err, io.EOF) { + return "eof" + } + var n net.Error + if errors.As(err, &n) && n.Timeout() { + return "network_timeout" + } + switch err.Error() { + case "stream rejected", "invalid command frame", "invalid stream clock", "invalid stream intent", "stream deadline": + return err.Error() + // These fixed, locally generated failures must remain distinguishable. + // Never emit arbitrary transport errors: they can contain paired URLs. + case "datagram negotiation rejected": + return "datagram_negotiation_rejected" + case "invalid datagram endpoint": + return "datagram_endpoint_invalid" + case "datagram socket closed": + return "datagram_socket_closed" + case "datagram link timeout": + return "datagram_link_timeout" + case "datagram stream deadline": + return "datagram_stream_deadline" + case "invalid datagram frame": + return "datagram_frame_invalid" + case "invalid datagram clock": + return "datagram_clock_invalid" + case "datagram receipt stale": + return "datagram_receipt_stale" + case "invalid datagram intent": + return "datagram_intent_invalid" + } + return "transport_error" // Raw errors can contain private URLs; never emit them. +} + +func (s *roverStreamState) setDev(value map[string]any) { + s.mu.Lock() + defer s.mu.Unlock() + if value == nil { + return + } + id, ok := value["id"].(string) + enabled, valid := value["enabled"].(bool) + if !ok || len(id) != 32 || !valid { + return + } + if s.devID != id { + s.devID = id + s.devSequence = 0 + s.devRelayAfter = 0 + s.devEvents = nil + s.devPacket = nil + s.devBudgetAt = time.Time{} + } + s.devEnabled = enabled + s.devDesired = make(map[string]any, len(value)) + for k, v := range value { + if k != "relay_after" { + s.devDesired[k] = v + } + } + if ack, ok := finiteNumber(value["relay_after"]); ok && ack >= 0 && ack <= float64(s.devSequence) { + s.devRelayAfter = max(s.devRelayAfter, int64(ack)) + } + s.devAfter = value["after"] +} +func devOption(options any, key string) bool { + if value, ok := options.(map[string]any); ok { + if flag, ok := value[key].(bool); ok { + return flag + } + } + return true // Legacy capture keeps its original explicit behavior. +} + +func (s *roverStreamState) recordDev(event string, data map[string]any) { + s.mu.Lock() + defer s.mu.Unlock() + if s.devID == "" || !s.devEnabled || !devOption(s.devDesired["options"], "network") { + return + } + // UTC microseconds fit exactly in JSON and keep sequence unique across relay restarts. + s.devSequence = max(s.devSequence+1, time.Now().UnixMicro()) + row := map[string]any{"source": "node", "event": event, "record_sequence": s.devSequence, + "at_utc": time.Now().UTC().Format(time.RFC3339Nano), "monotonic_ms": float64(time.Since(s.origin).Microseconds()) / 1000} + for k, v := range data { + row[k] = v + } + s.devEvents = append(s.devEvents, row) + if len(s.devEvents) > 64 { + s.devEvents = s.devEvents[len(s.devEvents)-64:] + } +} +func (s *roverStreamState) devRequest() map[string]any { + s.mu.Lock() + defer s.mu.Unlock() + if s.devID == "" { + return nil + } + if !s.devEnabled && s.devDesired["export"] == nil { + if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) { + return nil + } + } + result := map[string]any{} + for k, v := range s.devDesired { + result[k] = v + } + result["relay_events"] = append([]map[string]any{}, s.devEvents...) + return result +} +func (s *roverStreamState) devPayload() map[string]any { + s.mu.Lock() + defer s.mu.Unlock() + if s.devID == "" { + return nil + } + result := map[string]any{"id": s.devID, "frames": []any{}, "vehicle": s.devDesired["vehicle"]} + for k, v := range s.devPacket { + result[k] = v + } + if !s.devEnabled && s.devDesired["export"] == nil { + if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) { + return map[string]any{"id": s.devID, "active": false, "storage": storage, "frames": []any{}} + } + } + pending := []map[string]any{} + for _, event := range s.devEvents { + if seq, ok := event["record_sequence"].(int64); ok && seq > s.devRelayAfter { + pending = append(pending, event) + } + } + if devOption(s.devDesired["options"], "live") { + result["relay_events"] = pending + } else { + result["relay_events"] = []any{} + result["frames"] = []any{} + } + return result +} +func (p *Pairing) roverDev(ctx context.Context, model *sensorModel, state *roverStreamState) { + for ctx.Err() == nil { + state.recordBudgetDev(time.Now()) + if request := state.devRequest(); request != nil { + call, done := context.WithTimeout(ctx, 3*time.Second) + result, err := p.Sensors.modelDriver(call, model, "/drive-trace", request) + done() + if err == nil { + raw, _ := json.Marshal(result) + if len(raw) <= 256*1024 { + state.mu.Lock() + state.devPacket = result + state.mu.Unlock() + } + } else { + state.recordDev("diagnostics_transport", map[string]any{"reason": roverErrorKind(err)}) + state.mu.Lock() + if state.devPacket == nil { + state.devPacket = map[string]any{} + } + state.devPacket["transport_error"] = roverErrorKind(err) + state.mu.Unlock() + } + } + if !roverWait(ctx, 100*time.Millisecond) { + return + } + } +} + +// Budget evidence belongs to the optional local recorder lane, never to the +// motor delivery loop. One snapshot per second, and none outside DEV. +func (s *roverStreamState) recordBudgetDev(now time.Time) { + s.mu.Lock() + active := s.devEnabled && s.devID != "" && s.budget != nil && + (s.devBudgetAt.IsZero() || now.Sub(s.devBudgetAt) >= time.Second) + if active { + s.devBudgetAt = now + } + s.mu.Unlock() + if active { + s.recordDev("link_budget", map[string]any{"budget": s.budget.Snapshot()}) + } +} diff --git a/apps/node-agent/internal/node/rover_dev_test.go b/apps/node-agent/internal/node/rover_dev_test.go new file mode 100644 index 00000000..5939e5b2 --- /dev/null +++ b/apps/node-agent/internal/node/rover_dev_test.go @@ -0,0 +1,73 @@ +package node + +import ( + "testing" + "time" +) + +func TestDevCaptureOptInAndOff(t *testing.T) { + s := newRoverStreamState(time.Now()) + s.recordDev("delivery", nil) + if s.devRequest() != nil || len(s.devEvents) != 0 { + t.Fatal("disabled recorder must be inert") + } + s.setDev(map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "enabled": true, "after": float64(0)}) + s.recordDev("delivery", map[string]any{"sequence": 42}) + if len(s.devEvents) != 1 || s.devRequest()["enabled"] != true { + t.Fatal("capture not enabled") + } + if s.devEvents[0]["sequence"] != 42 || s.devEvents[0]["record_sequence"].(int64) <= 42 { + t.Fatal("command and trace cursors collide") + } + s.setDev(map[string]any{"id": s.devID, "enabled": false, "after": float64(0)}) + s.recordDev("late", nil) + if len(s.devEvents) != 1 { + t.Fatal("capture continues after off") + } + s.devPacket = map[string]any{"sequence": float64(0), "storage": map[string]any{"closed": true}} + if s.devRequest() != nil { + t.Fatal("finished capture keeps polling driver") + } + if _, ok := s.devPayload()["relay_events"]; ok { + t.Fatal("finished capture keeps sending verbose events") + } +} +func TestDevDoesNotExtendMotionLease(t *testing.T) { + s := newRoverStreamState(time.Now()) + before := s.stopRevision + s.setDev(map[string]any{"id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "enabled": true, "after": float64(0)}) + if s.command != nil || s.stopRevision != before || !s.stopPending { + t.Fatal("DEV changed motion authority") + } + for i := 0; i < 100; i++ { + s.recordDev("sample", nil) + } + if len(s.devEvents) != 64 { + t.Fatal("unbounded relay RAM") + } +} + +func TestDevNetworkAcknowledgementDoesNotDropOnboardRecords(t *testing.T) { + s := newRoverStreamState(time.Now()) + id := "cccccccccccccccccccccccccccccccc" + s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0)}) + s.recordDev("first", nil) + first := s.devSequence + s.recordDev("second", nil) + s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0), "relay_after": float64(first)}) + network := s.devPayload()["relay_events"].([]map[string]any) + if len(network) != 1 || network[0]["event"] != "second" { + t.Fatal("acknowledged network events retransmitted") + } + request := s.devRequest() + if _, exists := request["relay_after"]; exists { + t.Fatal("Core ack leaked into native protocol") + } + if len(request["relay_events"].([]map[string]any)) != 2 { + t.Fatal("network ack discarded records before onboard writer") + } + s.setDev(map[string]any{"id": "dddddddddddddddddddddddddddddddd", "enabled": true, "after": float64(0)}) + if s.devRelayAfter != 0 { + t.Fatal("ack leaked across sessions") + } +} diff --git a/apps/node-agent/internal/node/rover_diagnostics.go b/apps/node-agent/internal/node/rover_diagnostics.go index aa600df8..b1e0d1e9 100644 --- a/apps/node-agent/internal/node/rover_diagnostics.go +++ b/apps/node-agent/internal/node/rover_diagnostics.go @@ -1,7 +1,7 @@ package node -// A bounded memory flight recorder. It never stores endpoints, certificates, -// payloads or raw HTTP errors, and never changes admission or lease deadlines. +// A bounded memory flight recorder. No endpoints, credentials or raw payloads. +// Both lanes use the relay epoch and one origin. Reporting never renews a lease. import ( "encoding/json" "log" @@ -9,32 +9,51 @@ import ( ) type roverFrame struct { - AtMS int64 `json:"at_ms"` - GapMS int64 `json:"gap_ms"` - BindingMS int64 `json:"binding_ms"` - CoreMS int64 `json:"core_ms"` - DriverMS int64 `json:"driver_ms"` - Status int `json:"http_status"` - Stage string `json:"error_stage,omitempty"` - Session string `json:"session,omitempty"` - Sequence float64 `json:"sequence"` - TTLMS float64 `json:"ttl_ms"` - State string `json:"state"` + Delivery string `json:"delivery_mode,omitempty"` + Index uint64 `json:"index"` + AtMS int64 `json:"at_ms"` + GapMS int64 `json:"gap_ms"` + BindingMS int64 `json:"binding_ms"` + CoreMS int64 `json:"core_ms"` + DriverMS int64 `json:"driver_ms"` + Status int `json:"http_status"` + Stage string `json:"error_stage,omitempty"` + Reason string `json:"reason,omitempty"` + Session string `json:"session,omitempty"` + Sequence float64 `json:"sequence"` + TTLMS float64 `json:"ttl_ms"` + State string `json:"state"` + ReleaseConfirmed *bool `json:"release_confirmed"` + MarshalMS float64 `json:"marshal_ms,omitempty"` + RequestBytes int `json:"request_bytes,omitempty"` + CoreProcessingMS float64 `json:"core_processing_ms,omitempty"` } type roverDiagnostics struct { - frames []roverFrame - last time.Time - started time.Time - state string - session string - emit func([]byte) + frames []roverFrame + last time.Time + started time.Time + state string + session string + lane string + epoch string + stage string + pendingReason string + release *bool + lastEmit time.Time + activeUntil time.Time + controlSession string + index uint64 + emitted uint64 + emit func([]byte) } func (d *roverDiagnostics) record(at time.Time, frame roverFrame) { if d.started.IsZero() { d.started = at } + d.index++ + frame.Index = d.index frame.AtMS = at.Sub(d.started).Milliseconds() if !d.last.IsZero() { frame.GapMS = at.Sub(d.last).Milliseconds() @@ -44,18 +63,78 @@ func (d *roverDiagnostics) record(at time.Time, frame roverFrame) { if len(d.frames) > 128 { d.frames = d.frames[len(d.frames)-128:] } - active := frame.Session != "" || d.session != "" + if frame.Session != "" { + d.activeUntil = at.Add(5 * time.Second) + d.controlSession = frame.Session + } + // Retirement used to suppress the ensuing stopping/fault/release result. + // Keep a bounded post-control window; idle observation remains silent. + active := frame.Session != "" || d.session != "" || at.Before(d.activeUntil) changed := frame.State != d.state || frame.Session != d.session - if active && (changed || frame.Stage != "" || frame.GapMS >= 200) { + reason := d.pendingReason + releaseChanged := (frame.ReleaseConfirmed == nil) != (d.release == nil) + if frame.ReleaseConfirmed != nil && d.release != nil { + releaseChanged = *frame.ReleaseConfirmed != *d.release + } + if releaseChanged { + reason = "release_changed" + } + if d.stage != "" && frame.Stage == "" { + reason = "stage_recovered" + } + if changed { + reason = "state_changed" + } + if frame.GapMS >= 200 { + reason = "cycle_gap" + } + if frame.Stage != "" { + reason = frame.Stage + } + if frame.Reason != "" { + reason = frame.Reason + } + terminal := frame.State == "stopped" || frame.State == "stopping" || frame.State == "fault" || frame.State == "receiver" + urgent := releaseChanged || frame.Session != d.session || (changed && terminal) || frame.Stage != d.stage || frame.Delivery == "stop" + if active { + d.pendingReason = reason + } else { + d.pendingReason = "" + } + if active && reason != "" && (urgent || d.lastEmit.IsZero() || at.Sub(d.lastEmit) >= time.Second) { + // Emit newly captured frames plus at most two preceding context frames. + // Indexes expose both deduplication and any overwritten bounded history. + first := 0 + if d.emitted > 2 { + for first < len(d.frames)-1 && d.frames[first].Index <= d.emitted-2 { + first++ + } + } raw, _ := json.Marshal(struct { - Event string `json:"event"` - Frames []roverFrame `json:"frames"` - }{"rover-channel", d.frames}) + Event string `json:"event"` + Schema string `json:"schema"` + Epoch string `json:"epoch"` + Lane string `json:"lane"` + Origin string `json:"origin_utc"` + Reason string `json:"reason"` + ControlSession string `json:"control_session,omitempty"` + Frames []roverFrame `json:"frames"` + }{"rover-channel", "missioncore.rover-timeline/v1", d.epoch, d.lane, + d.started.UTC().Format(time.RFC3339Nano), reason, d.controlSession, d.frames[first:]}) if d.emit != nil { d.emit(raw) } else { log.Printf("%s", raw) } + d.lastEmit, d.emitted = at, d.index + d.pendingReason = "" } - d.state, d.session = frame.State, frame.Session + d.state, d.session, d.stage, d.release = frame.State, frame.Session, frame.Stage, frame.ReleaseConfirmed +} + +func roverReleaseEvidence(snapshot map[string]any) *bool { + if value, ok := snapshot["release_confirmed"].(bool); ok { + return &value + } + return nil } diff --git a/apps/node-agent/internal/node/rover_diagnostics_lane.go b/apps/node-agent/internal/node/rover_diagnostics_lane.go new file mode 100644 index 00000000..7f8cb7fe --- /dev/null +++ b/apps/node-agent/internal/node/rover_diagnostics_lane.go @@ -0,0 +1,194 @@ +package node + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "time" +) + +// Paces actual reads by net/http in bounded chunks. It holds no control/state +// locks and cancellation interrupts the wait. Content-Length stays explicit. +type budgetReader struct { + started bool + ctx context.Context + source io.Reader + budget *LinkBudget + class string +} + +func (r *budgetReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + if !r.started { + r.started = true + if source, ok := r.source.(interface{ Len() int }); ok { + r.budget.RequestDemand(r.class, source.Len()) + } + } + n, err := r.source.Read(p[:min(len(p), linkPacket)]) + if n == 0 { + return n, err + } + for { + if e := r.ctx.Err(); e != nil { + return 0, e + } + granted, wait := r.budget.Try(r.class, n) + if granted { + return n, err + } + if !roverWait(r.ctx, wait) { + return 0, r.ctx.Err() + } + } +} + +// Fit a network view without discarding the complete onboard session file. +// Export and lifecycle metadata come first. Live-view gaps remain explicit at +// Core; only delivered record sequences are acknowledged. Live rows use 12 KB; +// one negotiated 64 KiB export block has a separate bounded allowance. +func boundedDevPacket(packet map[string]any) map[string]any { + if packet == nil { + return nil + } + out := make(map[string]any, len(packet)) + for k, v := range packet { + if k != "frames" && k != "relay_events" { + out[k] = v + } + } + export, _ := json.Marshal(out["export"]) + if len(export) > 90*1024 { + delete(out, "export") + export = nil + } + liveBytes := 12 * 1024 + if options, ok := packet["options"].(map[string]any); ok { + if rate, ok := finiteNumber(options["live_kbps"]); ok && rate >= 8 && rate <= 64 { + liveBytes = min(liveBytes, int(rate*125)) + } + } + // The operator limit applies to event rows only. Lifecycle metadata and + // export have separate accounting; subtracting them here can reduce every + // 8-kbit/s live view to zero. Share unused capacity across both row sources. + allowance := liveBytes - 4 // Two JSON array delimiters; row commas counted below. + for _, key := range []string{"frames", "relay_events"} { + rows := []any{} + switch v := packet[key].(type) { + case []any: + rows = v + case []map[string]any: + for _, row := range v { + rows = append(rows, row) + } + } + kept := []any{} + used := 0 + // Network view is latest-first admission, chronological delivery. A large + // old row must not permanently block newer evidence; full rows stay on disk. + for i := len(rows) - 1; i >= 0; i-- { + raw, _ := json.Marshal(rows[i]) + if used+len(raw)+1 > allowance { + continue + } + kept = append(kept, rows[i]) + used += len(raw) + 1 + } + for i, j := 0, len(kept)-1; i < j; i, j = i+1, j-1 { + kept[i], kept[j] = kept[j], kept[i] + } + out[key] = kept + allowance -= used + } + return out +} + +// A successful exchange has delivered this immutable block. Until Core asks +// for the next offset, send only the small status poll, never the same 64 KiB +// again. Failed exchanges retain the block for retry with the same identity. +func devExportKey(packet map[string]any) string { + export, ok := packet["export"].(map[string]any) + if !ok { + return "" + } + key, _ := json.Marshal([]any{export["capture_id"], export["token"], export["offset"], export["next"], export["sha256"]}) + return string(key) +} + +// Recorder lifecycle/status is a bounded metadata request. Live records and +// export bytes still use residual bulk capacity; they cannot hide in this lane. +func diagnosticTrafficClass(packet map[string]any) string { + if packet["export"] != nil { + return "bulk" + } + for _, key := range []string{"frames", "relay_events"} { + switch rows := packet[key].(type) { + case []any: + if len(rows) > 0 { + return "bulk" + } + case []map[string]any: + if len(rows) > 0 { + return "bulk" + } + } + } + return "inventory" +} + +func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) { + lastExport := "" + for ctx.Err() == nil { + state.mu.Lock() + enabled := state.diagnosticLane && (state.diagnosticPending == nil || *state.diagnosticPending || state.devEnabled) + state.mu.Unlock() + if !enabled { + if !roverWait(ctx, 250*time.Millisecond) { + return + } + continue + } + payload := make(map[string]any, len(base)+1) + for k, v := range base { + payload[k] = v + } + packet := state.devPayload() + exportKey := devExportKey(packet) + if exportKey != "" && exportKey == lastExport { + delete(packet, "export") + } + payload["diagnostic_export_v2"] = true + payload["diagnostics"] = boundedDevPacket(packet) + raw, _ := json.Marshal(payload) + // On capable peers idle DEV sleeps until the existing telemetry reply + // announces work. Legacy peers keep polling. No recorder rows or exports + // travel on the critical lane; only a boolean wake hint does. + call, cancel := context.WithTimeout(ctx, pacedTimeout(len(raw))) + reader := &budgetReader{ctx: call, source: bytes.NewReader(raw), budget: state.budget, class: diagnosticTrafficClass(packet)} + req, _ := http.NewRequestWithContext(call, "POST", endpoint+"/v1/node/rover-diagnostics", reader) + req.ContentLength = int64(len(raw)) + req.Header.Set("Content-Type", "application/json") + response, err := client.Do(req) + if err == nil { + var reply struct { + Diagnostics map[string]any `json:"diagnostics"` + } + err = json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&reply) + response.Body.Close() + if err == nil && response.StatusCode == 200 { + state.setDev(reply.Diagnostics) + if exportKey != "" { + lastExport = exportKey + } + } + } + cancel() + if !roverWait(ctx, time.Second) { + return + } + } +} diff --git a/apps/node-agent/internal/node/rover_diagnostics_low_rate_test.go b/apps/node-agent/internal/node/rover_diagnostics_low_rate_test.go new file mode 100644 index 00000000..c8c02d02 --- /dev/null +++ b/apps/node-agent/internal/node/rover_diagnostics_low_rate_test.go @@ -0,0 +1,63 @@ +package node + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestDevMinimumRateDoesNotChargeLifecycleOrExportAgainstEvents(t *testing.T) { + for _, exported := range []bool{false, true} { + packet := map[string]any{ + "id": "capture", + "options": map[string]any{"live_kbps": float64(8)}, + "storage": map[string]any{"file": strings.Repeat("metadata", 180), "closed": false}, + "frames": []any{map[string]any{"record_sequence": 1, "event": "capture_started"}}, + "relay_events": []any{ + map[string]any{"record_sequence": 2, "event": "oversized", "data": strings.Repeat("x", 2000)}, + map[string]any{"record_sequence": 3, "event": "network", "data": strings.Repeat("x", 580)}, + }, + } + if exported { + packet["export"] = map[string]any{"data": strings.Repeat("A", 87384)} + } + bounded := boundedDevPacket(packet) + frames, relay := bounded["frames"].([]any), bounded["relay_events"].([]any) + if len(frames) != 1 || len(relay) != 1 || relay[0].(map[string]any)["record_sequence"] != 3 { + t.Fatal("minimum event rate starved by metadata or an oversized row", bounded["frames"], bounded["relay_events"]) + } + eventBytes := 0 + for _, rows := range [][]any{frames, relay} { + for _, row := range rows { + raw, _ := json.Marshal(row) + eventBytes += len(raw) + 1 + } + } + if eventBytes > 1000 { + t.Fatal("event rate exceeded", eventBytes) + } + if bounded["storage"] == nil || (exported && bounded["export"] == nil) { + t.Fatal("lifecycle/export lost") + } + } +} + +func TestDevMinimumRateAdmitsNearKilobyteMotorSample(t *testing.T) { + sample := map[string]any{"record_sequence": 1, "event": "sample", "data": ""} + raw, _ := json.Marshal(sample) + sample["data"] = strings.Repeat("x", 985-len(raw)) + packet := map[string]any{ + "options": map[string]any{"live_kbps": float64(8)}, + "storage": map[string]any{"file": strings.Repeat("metadata", 180)}, + "frames": []any{sample}, + } + bounded := boundedDevPacket(packet) + frames := bounded["frames"].([]any) + if len(frames) != 1 { + t.Fatal("real-sized motor sample cannot pass minimum rate") + } + raw, _ = json.Marshal(frames) + if len(raw) > 1000 { + t.Fatal("sample exceeds event rate", len(raw)) + } +} diff --git a/apps/node-agent/internal/node/rover_diagnostics_test.go b/apps/node-agent/internal/node/rover_diagnostics_test.go index 20e23a4c..361c3f98 100644 --- a/apps/node-agent/internal/node/rover_diagnostics_test.go +++ b/apps/node-agent/internal/node/rover_diagnostics_test.go @@ -61,3 +61,86 @@ func TestRoverDiagnosticsRecordsBindingWaitAndDriverTerminalState(t *testing.T) t.Fatal(last) } } + +func TestRoverTimelineSharesOriginAndKeepsReleaseAfterRetirement(t *testing.T) { + origin := time.Unix(100, 0) + var events []map[string]any + d := roverDiagnostics{started: origin, epoch: "relay", lane: "local", emit: func(raw []byte) { + var event map[string]any + if err := json.Unmarshal(raw, &event); err != nil { + t.Fatal(err) + } + events = append(events, event) + }} + d.record(origin.Add(time.Second), roverFrame{Session: "intent", State: "driving"}) + d.record(origin.Add(1100*time.Millisecond), roverFrame{Delivery: "stop", Reason: "intent_expired", State: "stopping"}) + no, yes := false, true + d.record(origin.Add(1500*time.Millisecond), roverFrame{State: "fault", ReleaseConfirmed: &no}) + d.record(origin.Add(2500*time.Millisecond), roverFrame{State: "stopped", ReleaseConfirmed: &yes}) + if len(events) != 4 { + t.Fatalf("lost release after retirement: %d", len(events)) + } + for _, event := range events { + if event["epoch"] != "relay" || event["lane"] != "local" || event["origin_utc"] != origin.UTC().Format(time.RFC3339Nano) { + t.Fatal(event) + } + if event["control_session"] != "intent" { + t.Fatal("retired session correlation lost") + } + } + first := events[0]["frames"].([]any)[0].(map[string]any) + if first["at_ms"] != float64(1000) || first["release_confirmed"] != nil { + t.Fatal(first) + } + for i := 0; i < 200; i++ { + d.record(origin.Add(time.Duration(7+i)*time.Second), roverFrame{State: "stopped", Stage: "idle_error"}) + } + if len(events) != 4 || len(d.frames) != 128 { + t.Fatal("post-control window must be bounded") + } +} + +func TestRoverTimelineAvoidsRepeatedFullRingOnStateFlapping(t *testing.T) { + count, rows := 0, 0 + var previous uint64 + d := roverDiagnostics{emit: func(raw []byte) { + var event struct { + Frames []roverFrame `json:"frames"` + } + if err := json.Unmarshal(raw, &event); err != nil { + t.Fatal(err) + } + count++ + rows += len(event.Frames) + if previous > 2 && event.Frames[0].Index < previous-1 { + t.Fatal("repeated older context") + } + previous = event.Frames[len(event.Frames)-1].Index + }} + at := time.Unix(100, 0) + for i := 0; i < 200; i++ { + state := "ready" + if i%2 == 0 { + state = "driving" + } + d.record(at.Add(time.Duration(i)*50*time.Millisecond), roverFrame{Session: "live", State: state}) + } + d.record(at.Add(10*time.Second), roverFrame{Session: "live", State: "driving"}) + if count > 11 || rows > 225 || previous != 201 { + t.Fatalf("events=%d rows=%d last=%d", count, rows, previous) + } +} + +func TestRoverReleaseEvidencePreservesUnknownFalseTrue(t *testing.T) { + for _, value := range []any{nil, "false", 0} { + if roverReleaseEvidence(map[string]any{"release_confirmed": value}) != nil { + t.Fatal("invalid release became proof") + } + } + for _, value := range []bool{false, true} { + got := roverReleaseEvidence(map[string]any{"release_confirmed": value}) + if got == nil || *got != value { + t.Fatal("release truth changed") + } + } +} diff --git a/apps/node-agent/internal/node/rover_error_kind_test.go b/apps/node-agent/internal/node/rover_error_kind_test.go new file mode 100644 index 00000000..5b1e53bf --- /dev/null +++ b/apps/node-agent/internal/node/rover_error_kind_test.go @@ -0,0 +1,44 @@ +package node + +import ( + "context" + "errors" + "fmt" + "net/url" + "testing" +) + +func TestDatagramFailureReasonsAreDistinctAndRedacted(t *testing.T) { + cases := map[string]string{ + "datagram negotiation rejected": "datagram_negotiation_rejected", + "invalid datagram endpoint": "datagram_endpoint_invalid", + "datagram socket closed": "datagram_socket_closed", + "datagram link timeout": "datagram_link_timeout", + "datagram stream deadline": "datagram_stream_deadline", + "invalid datagram frame": "datagram_frame_invalid", + "invalid datagram clock": "datagram_clock_invalid", + "datagram receipt stale": "datagram_receipt_stale", + "invalid datagram intent": "datagram_intent_invalid", + } + seen := map[string]bool{} + for message, want := range cases { + got := roverErrorKind(errors.New(message)) + if got != want || seen[got] { + t.Fatalf("reason %q: got %q, want unique %q", message, got, want) + } + seen[got] = true + } + // Transport errors may embed private endpoints. Only the timeout category + // may survive wrapping; never copy the raw URL, query or nested error. + private := &url.Error{Op: "Post", URL: "https://private.invalid/pair?secret=synthetic", Err: errors.New("connection failed")} + if got := roverErrorKind(private); got != "transport_error" { + t.Fatalf("private error leaked: %q", got) + } + private.Err = fmt.Errorf("request: %w", context.DeadlineExceeded) + if got := roverErrorKind(private); got != "deadline" { + t.Fatalf("wrapped deadline: %q", got) + } + if got := roverErrorKind(errors.New("datagram stream deadline: secret=synthetic")); got != "transport_error" { + t.Fatalf("prefix is not an allowlist: %q", got) + } +} diff --git a/apps/node-agent/internal/node/rover_export_lane_test.go b/apps/node-agent/internal/node/rover_export_lane_test.go new file mode 100644 index 00000000..5cc368d6 --- /dev/null +++ b/apps/node-agent/internal/node/rover_export_lane_test.go @@ -0,0 +1,84 @@ +package node + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestDevExportSendsAcknowledgedBlockOnceAndRetriesFailedExchange(t *testing.T) { + for _, failFirst := range []bool{false, true} { + t.Run(map[bool]string{false: "acknowledged", true: "failed-then-acknowledged"}[failFirst], func(t *testing.T) { + var calls, blocks atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if json.NewDecoder(r.Body).Decode(&body) != nil { + t.Error("invalid lane request") + } + packet := body["diagnostics"].(map[string]any) + if packet["export"] != nil { + blocks.Add(1) + } + n := calls.Add(1) + if failFirst && n == 1 { + w.WriteHeader(503) + } + json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil}) + })) + defer server.Close() + state := newRoverStreamState(time.Now()) + state.diagnosticLane = true + state.devID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + state.devDesired = map[string]any{"export": map[string]any{"offset": 0}} + state.devPacket = map[string]any{"id": state.devID, "frames": []any{}, "export": map[string]any{ + "capture_id": state.devID, "token": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "offset": 0, "next": 3, "data": "YWJj"}} + ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond) + defer cancel() + roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state) + expected := int64(1) + if failFirst { + expected = 2 + } + if calls.Load() < 3 || blocks.Load() != expected { + t.Fatal("unbounded duplicate or lost retry", calls.Load(), blocks.Load()) + } + if state.devPacket["export"] == nil { + t.Fatal("network suppression modified retained source") + } + }) + } +} + +func TestIdleDiagnosticLaneSleepsUntilTelemetryAnnouncesWork(t *testing.T) { + var calls atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil}) + })) + defer server.Close() + state := newRoverStreamState(time.Now()) + state.diagnosticLane = true + idle := false + state.diagnosticPending = &idle + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state) + cancel() + if calls.Load() != 0 { + t.Fatal("disabled DEV generated bulk polls") + } + busy := true + state.diagnosticPending = &busy + ctx, cancel = context.WithTimeout(context.Background(), 150*time.Millisecond) + roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state) + cancel() + if calls.Load() == 0 { + t.Fatal("capture/export wake hint ignored") + } + if state.command != nil || !state.stopPending { + t.Fatal("diagnostics affected control") + } +} diff --git a/apps/node-agent/internal/node/rover_http_trace.go b/apps/node-agent/internal/node/rover_http_trace.go new file mode 100644 index 00000000..ce9ecd9e --- /dev/null +++ b/apps/node-agent/internal/node/rover_http_trace.go @@ -0,0 +1,64 @@ +package node + +// DEV-only transport timing. Never record endpoints, headers, keys or raw errors. +import ( + "context" + "crypto/tls" + "net/http/httptrace" + "sync" + "time" +) + +type roverHTTPTrace struct { + mu sync.Mutex + started time.Time + fields map[string]any +} + +func newRoverHTTPTrace(started time.Time, requestBytes int) *roverHTTPTrace { + return &roverHTTPTrace{started: started, fields: map[string]any{"phase": "waiting_connection", "request_bytes": requestBytes}} +} +func (t *roverHTTPTrace) mark(phase string, values map[string]any) { + t.mu.Lock() + defer t.mu.Unlock() + t.fields["phase"] = phase + t.fields[phase+"_ms"] = float64(time.Since(t.started).Microseconds()) / 1000 + for key, value := range values { + t.fields[key] = value + } +} +func (t *roverHTTPTrace) context(ctx context.Context) context.Context { + return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ + DNSStart: func(httptrace.DNSStartInfo) { t.mark("dns_start", nil) }, + DNSDone: func(v httptrace.DNSDoneInfo) { t.mark("dns_done", map[string]any{"dns_error": roverErrorKind(v.Err)}) }, + ConnectStart: func(_, _ string) { t.mark("connect_start", nil) }, + ConnectDone: func(_, _ string, err error) { + t.mark("connect_done", map[string]any{"connect_error": roverErrorKind(err)}) + }, + TLSHandshakeStart: func() { t.mark("tls_start", nil) }, + TLSHandshakeDone: func(_ tls.ConnectionState, err error) { + t.mark("tls_done", map[string]any{"tls_error": roverErrorKind(err)}) + }, + GotConn: func(v httptrace.GotConnInfo) { + t.mark("connection_ready", map[string]any{"reused": v.Reused, "was_idle": v.WasIdle}) + }, + WroteRequest: func(v httptrace.WroteRequestInfo) { + t.mark("request_written", map[string]any{"write_error": roverErrorKind(v.Err)}) + }, + GotFirstResponseByte: func() { t.mark("first_response_byte", nil) }, + }) +} +func (t *roverHTTPTrace) snapshot() map[string]any { + t.mu.Lock() + defer t.mu.Unlock() + result := make(map[string]any, len(t.fields)) + for key, value := range t.fields { + result[key] = value + } + return result +} +func (s *roverStreamState) devTraceEnabled() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.devID != "" && s.devEnabled && devOption(s.devDesired["options"], "network") +} diff --git a/apps/node-agent/internal/node/rover_http_trace_test.go b/apps/node-agent/internal/node/rover_http_trace_test.go new file mode 100644 index 00000000..77341485 --- /dev/null +++ b/apps/node-agent/internal/node/rover_http_trace_test.go @@ -0,0 +1,83 @@ +package node + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestRoverHTTPTraceConnectionReuseAndPrivacy(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) })) + defer server.Close() + client := &http.Client{Transport: &http.Transport{}, Timeout: time.Second} + defer client.CloseIdleConnections() + for i := 0; i < 2; i++ { + trace := newRoverHTTPTrace(time.Now(), 7) + req, _ := http.NewRequestWithContext(trace.context(context.Background()), "POST", server.URL+"/private-path", strings.NewReader("private")) + req.Header.Set("Authorization", "private-key") + response, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + _, err = io.Copy(io.Discard, response.Body) + response.Body.Close() + if err != nil { + t.Fatal(err) + } + fields := trace.snapshot() + if fields["reused"] != (i == 1) || fields["phase"] != "first_response_byte" || fields["request_bytes"] != 7 { + t.Fatalf("unexpected timing: %v", fields) + } + for _, key := range []string{"connection_ready_ms", "request_written_ms", "first_response_byte_ms"} { + if _, ok := fields[key].(float64); !ok { + t.Fatalf("missing timing %s: %v", key, fields) + } + } + for _, value := range fields { + if str, ok := value.(string); ok && (strings.Contains(str, "private") || strings.Contains(str, server.URL)) { + t.Fatal("private request data escaped into diagnostic") + } + } + } +} +func TestRoverHTTPTraceDistinguishesWaitingForResponse(t *testing.T) { + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-release })) + defer server.Close() + defer close(release) + client := &http.Client{Timeout: 200 * time.Millisecond} + trace := newRoverHTTPTrace(time.Now(), 0) + req, _ := http.NewRequestWithContext(trace.context(context.Background()), "GET", server.URL, nil) + response, err := client.Do(req) + if response != nil { + response.Body.Close() + } + if roverErrorKind(err) != "deadline" { + t.Fatalf("expected deadline, got %v", err) + } + fields := trace.snapshot() + if fields["phase"] != "request_written" { + t.Fatalf("lost failing phase: %v", fields) + } + if _, ok := fields["first_response_byte_ms"]; ok { + t.Fatal("response was never sent") + } +} +func TestRoverHTTPTraceOnlyEnabledDuringDev(t *testing.T) { + state := newRoverStreamState(time.Now()) + if state.devTraceEnabled() { + t.Fatal("trace enabled outside DEV") + } + state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": true}) + if !state.devTraceEnabled() { + t.Fatal("DEV trace absent") + } + state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": false}) + if state.devTraceEnabled() { + t.Fatal("trace survived session stop") + } +} diff --git a/apps/node-agent/internal/node/rover_link.go b/apps/node-agent/internal/node/rover_link.go new file mode 100644 index 00000000..510cb5db --- /dev/null +++ b/apps/node-agent/internal/node/rover_link.go @@ -0,0 +1,66 @@ +package node + +// Establish the authenticated HTTP connection separately from fresh snapshots. +// A probe returns a clock sample but cannot publish telemetry or renew a lease. +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "time" +) + +func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) bool { + started := time.Now() + raw, _ := json.Marshal(base) + req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-link", bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + var trace *roverHTTPTrace + if state.devTraceEnabled() { + trace = newRoverHTTPTrace(started, len(raw)) + req = req.WithContext(trace.context(req.Context())) + } + // Share the exact authenticated transport/pool. The normal client's timeout + // stays unchanged; no connection or command queue is added. + connectClient := &http.Client{Transport: client.Transport, Timeout: 2500 * time.Millisecond, CheckRedirect: client.CheckRedirect} + response, err := connectClient.Do(req) + ok := false + status := 0 + if err == nil { + status = response.StatusCode + var reply struct { + LatestDatagram bool `json:"latest_datagram_v1"` + RoverDetails bool `json:"rover_details_v1"` + BudgetInterval bool `json:"budget_interval_v1"` + DiagnosticLane bool `json:"diagnostic_lane_v1"` + Connected bool `json:"connected"` + SampleClock bool `json:"sample_clock_v1"` + Clock roverClock `json:"control_clock"` + } + err = json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&reply) + response.Body.Close() + ok = err == nil && status == 200 && reply.Connected + stamped := ok && reply.SampleClock + if stamped { + ok = state.sampleClock(reply.Clock, started, time.Now()) + } + state.mu.Lock() + state.telemetryStamped = stamped && ok + state.diagnosticLane = ok && reply.DiagnosticLane + state.budgetInterval = ok && reply.BudgetInterval + state.roverDetails = ok && reply.RoverDetails + state.latestDatagram = state.latestDatagram || (ok && reply.LatestDatagram) + state.diagnosticPending = nil // One discovery exchange on every authenticated reconnect. + state.mu.Unlock() + } + if !ok && status == 0 { + state.budget.Observe(time.Since(started), false) + } + details := map[string]any{"elapsed_ms": time.Since(started).Milliseconds(), "http_status": status, "connected": ok, "reason": roverErrorKind(err)} + if trace != nil { + details["transport"] = trace.snapshot() + } + state.recordDev("link_connect", details) + return ok +} diff --git a/apps/node-agent/internal/node/rover_link_test.go b/apps/node-agent/internal/node/rover_link_test.go new file mode 100644 index 00000000..a00cbba2 --- /dev/null +++ b/apps/node-agent/internal/node/rover_link_test.go @@ -0,0 +1,148 @@ +package node + +import ( + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestRoverTelemetryCapturesFreshSnapshotAfterSlowConnection(t *testing.T) { + state := newRoverStreamState(time.Now()) + state.delivered(map[string]any{"generation": float64(1)}, 0) + received := make(chan map[string]any, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + if r.URL.Path == "/v1/node/rover-link" { + if _, ok := body["rover"]; ok { + t.Error("probe must not carry a stale snapshot") + } + if _, ok := body["command"]; ok { + t.Error("probe cannot command a motor") + } + _ = json.NewEncoder(w).Encode(map[string]bool{"connected": true}) + return + } + if r.URL.Path != "/v1/node/rover" { + t.Error("unexpected path") + } + select { + case received <- body: + default: + } + _ = json.NewEncoder(w).Encode(roverStreamReply{Clock: roverClock{testClockID, 10000}}) + })) + defer server.Close() + var dials atomic.Int32 + transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + dials.Add(1) + // Connection takes longer than the snapshot budget. Data changes meanwhile. + if !roverWait(ctx, 150*time.Millisecond) { + return nil, ctx.Err() + } + state.delivered(map[string]any{"generation": float64(2)}, 0) + return (&net.Dialer{}).DialContext(ctx, network, address) + }} + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan struct{}) + go func() { defer close(done); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }() + select { + case body := <-received: + if body["rover"].(map[string]any)["generation"] != float64(2) { + t.Fatal("stale pre-connect snapshot was transmitted") + } + case <-time.After(2 * time.Second): + t.Fatal("connection never recovered beyond snapshot deadline") + } + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("cancelled telemetry worker leaked") + } + if dials.Load() != 1 { + t.Fatalf("warm connection was not reused: %d", dials.Load()) + } + if client.Timeout != 75*time.Millisecond { + t.Fatal("snapshot deadline was relaxed") + } +} + +func TestRoverDelayedReplyKeepsConnectionWithoutExtendingCommandDeadline(t *testing.T) { + state := newRoverStreamState(time.Now()) + state.delivered(map[string]any{"generation": float64(1)}, 0) + origin := time.Now() + var probes atomic.Int32 + var snapshots atomic.Int32 + done := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clock := func() roverClock { + return roverClock{testClockID, 10000 + float64(time.Since(origin).Microseconds())/1000} + } + if r.URL.Path == "/v1/node/rover-link" { + probes.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"connected": true, "sample_clock_v1": true, "control_clock": clock()}) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + if body["sample_clock"] == nil { + t.Error("long transport deadline without capture age") + } + // A valid observation reply exceeds the former 300 ms cutoff. + time.Sleep(400 * time.Millisecond) + _ = json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: clock()}) + if snapshots.Add(1) == 2 { + done <- struct{}{} + } + })) + defer server.Close() + transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1} + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond} + ctx, cancel := context.WithCancel(context.Background()) + workerDone := make(chan struct{}) + go func() { defer close(workerDone); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("delayed response caused retry loop") + } + cancel() + <-workerDone + if probes.Load() != 1 { + t.Fatalf("unnecessary reconnects: %d", probes.Load()) + } + if client.Timeout != 75*time.Millisecond { + t.Fatal("shared command/client timeout changed") + } + if state.command != nil { + t.Fatal("observation created motion authority") + } +} + +func TestSampleTimeUsesConservativeLowerClockSeparateFromCommandUpper(t *testing.T) { + origin := time.Now() + s := newRoverStreamState(origin) + if !s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(400*time.Millisecond)) { + t.Fatal("clock") + } + s.telemetryStamped = true + captured := origin.Add(450 * time.Millisecond) + s.deliveredAt(map[string]any{}, 0, captured) + _, clock := s.telemetryView() + if clock == nil || clock.MonotonicMS > 10050 || clock.MonotonicMS < 10040 { + t.Fatalf("incorrect capture bound: %+v", clock) + } + if s.upperMS < 10000 { + t.Fatal("command upper bound was replaced by lower bound") + } +} diff --git a/apps/node-agent/internal/node/rover_local_delivery.go b/apps/node-agent/internal/node/rover_local_delivery.go new file mode 100644 index 00000000..e02444ba --- /dev/null +++ b/apps/node-agent/internal/node/rover_local_delivery.go @@ -0,0 +1,84 @@ +package node + +import ( + "context" + "time" +) + +// The local tick checks expiry even when no newer operator intent has arrived. +// It owns no independent lease and cannot extend the Core's original deadline. +type roverLocalDelivery struct { + session string + sequence float64 + sent bool +} + +func (d *roverLocalDelivery) run(ctx context.Context, sensors *Sensors, model *sensorModel, state *roverStreamState, relay string, started time.Time) roverFrame { + state.budget.ObserveCommandSilence() + watch, command, stop := state.delivery(started) + frame := roverFrame{} + mode := "observe" + if stop != 0 { + mode = "stop" + frame.Reason, _ = state.stopDetails()["reason"].(string) + if state.devTraceEnabled() { + state.recordDev("delivery_stop", state.stopDetails()) + } + } + if command != nil { + state.budget.SetControl(true) // Reserve before the first local intent, not after telemetry catches up. + mode = "intent" + frame.Session, _ = command["id"].(string) + frame.Sequence, _ = command["sequence"].(float64) + frame.TTLMS, _ = command["ttl_ms"].(float64) + } + // A successful RPC already carried this exact input to the owner. The + // VESC owner's input lease rejects duplicates anyway. Do not turn a redundant + // snapshot request into a second opportunity to retire valid authority. + // delivery() above still enforces expiry/stop/clock barriers every tick; + // skipping must NOT refresh the last snapshot's capture timestamp. + if command != nil && d.sent && d.session == frame.Session && d.sequence == frame.Sequence { + snapshot, _ := state.view() + frame.State, _ = snapshot["state"].(string) + frame.ReleaseConfirmed = roverReleaseEvidence(snapshot) + frame.Delivery = "unchanged" + state.recordDev("delivery", map[string]any{"session_id": frame.Session, "sequence": frame.Sequence, + "ttl_ms": frame.TTLMS, "driver_ms": 0, "state": frame.State, "error_stage": "", "delivery_mode": frame.Delivery}) + return frame + } + frame.Delivery = mode + call, done := context.WithTimeout(ctx, 25*time.Millisecond) + var trace *roverHTTPTrace + if state.devTraceEnabled() { + trace = newRoverHTTPTrace(started, 0) + call = trace.context(call) + } + result, err := sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay}) + reason := roverErrorKind(call.Err()) + if reason == "" && err != nil { + reason = roverErrorKind(err) + } + done() + frame.DriverMS = time.Since(started).Milliseconds() + if err != nil { + d.sent = false + state.stopStream() + frame.Stage = "driver_transport" + state.deliveredAt(map[string]any{}, 0, started) + } else { + d.sent = command != nil + d.session, d.sequence = frame.Session, frame.Sequence + state.deliveredAt(result, stop, started) + frame.State, _ = result["state"].(string) + frame.ReleaseConfirmed = roverReleaseEvidence(result) + } + details := map[string]any{"session_id": frame.Session, "sequence": frame.Sequence, "ttl_ms": frame.TTLMS, + "driver_ms": frame.DriverMS, "state": frame.State, "error_stage": frame.Stage, "delivery_mode": mode, "reason": reason} + if trace != nil { + timing := trace.snapshot() + delete(timing, "request_bytes") // Encoding belongs to modelDriver; its size is not measured here. + details["transport"] = timing + } + state.recordDev("delivery", details) + return frame +} diff --git a/apps/node-agent/internal/node/rover_local_delivery_test.go b/apps/node-agent/internal/node/rover_local_delivery_test.go new file mode 100644 index 00000000..7b4f1e02 --- /dev/null +++ b/apps/node-agent/internal/node/rover_local_delivery_test.go @@ -0,0 +1,184 @@ +package node + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptrace" + "testing" + "time" +) + +func localDeliveryFixture(t *testing.T) (*Sensors, *sensorModel, *roverStreamState, time.Time) { + t.Helper() + 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 VESC") + } + at := time.Now() + state := newRoverStreamState(at) + state.sampleClock(roverClock{testClockID, 10000}, at, at) + acknowledgeStop(state, at) + state.accept(streamIntent(1331, 10000, 10400)) + return sensors, model, state, at +} + +func TestRoverLocalDeliveryDoesNotResendAlreadyDeliveredIntent(t *testing.T) { + sensors, model, state, at := localDeliveryFixture(t) + calls := 0 + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + calls++ + if calls > 1 { + return nil, context.DeadlineExceeded + } + return testSensorReply(map[string]any{"state": "driving", "instance": "same", "session_id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}), nil + }) + var delivery roverLocalDelivery + delivery.run(context.Background(), sensors, model, state, "relay", at) + before, _ := state.view() + sampled := state.snapshotAt + delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond)) + _, command, stop := state.delivery(at.Add(75 * time.Millisecond)) + if calls != 1 || command == nil || stop != 0 { + t.Fatalf("duplicate RPC retired live intent: calls=%d command=%v stop=%d", calls, command, stop) + } + after, _ := state.view() + if after["instance"] != before["instance"] || !state.snapshotAt.Equal(sampled) { + t.Fatal("skipped RPC refreshed/replaced telemetry") + } + if command["ttl_ms"].(float64) >= 325 { + t.Fatal("duplicate extended the original deadline") + } +} + +func TestRoverLocalDeliveryStillSendsExpiryAndExplicitStop(t *testing.T) { + for _, explicit := range []bool{false, true} { + t.Run(map[bool]string{false: "expiry", true: "explicit"}[explicit], func(t *testing.T) { + sensors, model, state, at := localDeliveryFixture(t) + var requests []map[string]any + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatal(err) + } + requests = append(requests, body) + deadline, ok := r.Context().Deadline() + if !ok || time.Until(deadline) > 25*time.Millisecond { + t.Fatal("local RPC deadline relaxed") + } + return testSensorReply(map[string]any{"state": "driving"}), nil + }) + var delivery roverLocalDelivery + delivery.run(context.Background(), sensors, model, state, "relay", at) + next := at.Add(450 * time.Millisecond) + if explicit { + state.stopStream() + next = at.Add(50 * time.Millisecond) + } + delivery.run(context.Background(), sensors, model, state, "relay", next) + if len(requests) != 2 || requests[1]["command"] != nil { + t.Fatal("cached delivery suppressed stop") + } + state.accept(streamIntent(1332, 10450, 10850)) + _, command, _ := state.delivery(next) + if command != nil { + t.Fatal("retired session resumed") + } + }) + } +} + +func TestRoverLocalDeliveryNewIntentFailureRemainsTerminal(t *testing.T) { + sensors, model, state, at := localDeliveryFixture(t) + calls := 0 + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + calls++ + if calls == 2 { + return nil, errors.New("synthetic failure") + } + return testSensorReply(map[string]any{"state": "driving"}), nil + }) + var delivery roverLocalDelivery + delivery.run(context.Background(), sensors, model, state, "relay", at) + state.accept(streamIntent(1332, 10100, 10500)) + frame := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(100*time.Millisecond)) + _, command, stop := state.delivery(at.Add(150 * time.Millisecond)) + if calls != 2 || frame.Stage != "driver_transport" || command != nil || stop == 0 || delivery.sent { + t.Fatal("fresh intent failure no longer retires authority") + } + delivery.run(context.Background(), sensors, model, state, "relay", at.Add(150*time.Millisecond)) + if state.stopPending { + t.Fatal("explicit stop not acknowledged") + } +} + +func TestRoverLocalDeliveryNewInputAfterSkippedTickIsNotCoalescedAway(t *testing.T) { + sensors, model, state, at := localDeliveryFixture(t) + var sequences []float64 + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatal(err) + } + sequences = append(sequences, body["command"].(map[string]any)["sequence"].(float64)) + return testSensorReply(map[string]any{"state": "driving"}), nil + }) + var delivery roverLocalDelivery + delivery.run(context.Background(), sensors, model, state, "relay", at) + skipped := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond)) + state.accept(streamIntent(1332, 10060, 10460)) + delivery.run(context.Background(), sensors, model, state, "relay", at.Add(60*time.Millisecond)) + if len(sequences) != 2 || sequences[0] != 1331 || sequences[1] != 1332 || skipped.Delivery != "unchanged" { + t.Fatal("new input was suppressed", sequences) + } +} + +func TestRoverLocalDeliveryDeadlineTraceIsDevOnly(t *testing.T) { + for _, dev := range []bool{false, true} { + t.Run(map[bool]string{false: "off", true: "on"}[dev], func(t *testing.T) { + sensors, model, state, at := localDeliveryFixture(t) + if dev { + state.devID = testClockID + state.devEnabled = true + } + sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + tr := httptrace.ContextClientTrace(r.Context()) + if (tr != nil) != dev { + t.Fatal("trace state disagrees with DEV") + } + if tr != nil { + tr.WroteRequest(httptrace.WroteRequestInfo{}) + } + <-r.Context().Done() + return nil, r.Context().Err() + }) + var delivery roverLocalDelivery + delivery.run(context.Background(), sensors, model, state, "relay", at) + if !dev { + if len(state.devEvents) != 0 { + t.Fatal("DEV-off retained trace") + } + return + } + if len(state.devEvents) != 1 { + t.Fatal("trace missing") + } + row := state.devEvents[0] + timing := row["transport"].(map[string]any) + if row["reason"] != "deadline" || timing["phase"] != "request_written" || row["delivery_mode"] != "intent" { + t.Fatal(row) + } + if _, ok := timing["request_bytes"]; ok { + t.Fatal("invented request size") + } + }) + } +} diff --git a/apps/node-agent/internal/node/rover_metadata.go b/apps/node-agent/internal/node/rover_metadata.go new file mode 100644 index 00000000..5e50d2ea --- /dev/null +++ b/apps/node-agent/internal/node/rover_metadata.go @@ -0,0 +1,89 @@ +package node + +import ( + "bytes" + "encoding/json" + "time" +) + +// Only presentation/identity metadata is cached. Every measured value, age, +// attachment session, authority flag and release result stays in every frame. +var roverMetadataFields = []string{"supported", "control_modes", "profile"} +var roverDeviceMetadataFields = []string{"uuid", "slot", "label"} + +type roverMetadataEncoder struct { + instance string + previous []byte + revision uint64 + sentAt time.Time +} + +func (e *roverMetadataEncoder) reset() { e.sentAt = time.Time{} } + +func (e *roverMetadataEncoder) encode(snapshot map[string]any, now time.Time) (map[string]any, map[string]any) { + readings, ok := snapshot["devices"].([]any) + instance, _ := snapshot["instance"].(string) + if !ok || instance == "" { + e.reset() + return snapshot, nil + } + if e.instance != instance { + e.instance = instance + e.reset() + } + details := map[string]any{} + compact := make(map[string]any, len(snapshot)) + for k, v := range snapshot { + compact[k] = v + } + for _, k := range roverMetadataFields { + if v, exists := compact[k]; exists { + details[k] = v + delete(compact, k) + } + } + devices := map[string]any{} + live := make([]any, 0, len(readings)) + for _, value := range readings { + row, valid := value.(map[string]any) + id, _ := row["id"].(string) + session, _ := row["session_id"].(string) + if !valid || id == "" || session == "" { + e.reset() + return snapshot, nil + } + if _, duplicate := devices[id]; duplicate { + e.reset() + return snapshot, nil + } + metadata, current := map[string]any{}, map[string]any{} + for k, v := range row { + current[k] = v + } + for _, k := range roverDeviceMetadataFields { + if v, exists := current[k]; exists { + metadata[k] = v + delete(current, k) + } + } + devices[id] = metadata + live = append(live, current) + } + details["devices"], compact["devices"] = devices, live + raw, err := json.Marshal(details) + if err != nil { + e.reset() + return snapshot, nil + } + if !bytes.Equal(raw, e.previous) { + e.previous = raw + e.revision++ + e.reset() + } + envelope := map[string]any{"revision": e.revision} + if e.sentAt.IsZero() || now.Sub(e.sentAt) >= time.Second { + envelope["details"] = details + e.sentAt = now + } + return compact, envelope +} diff --git a/apps/node-agent/internal/node/rover_metadata_test.go b/apps/node-agent/internal/node/rover_metadata_test.go new file mode 100644 index 00000000..c4eac191 --- /dev/null +++ b/apps/node-agent/internal/node/rover_metadata_test.go @@ -0,0 +1,83 @@ +package node + +import ( + "encoding/json" + "reflect" + "testing" + "time" +) + +func metadataSnapshot() map[string]any { + return map[string]any{"instance": "driver", "supported": true, "control_modes": []any{"duty"}, + "profile": map[string]any{"revision": float64(2)}, "state": "stopped", "release_confirmed": false, + "devices": []any{map[string]any{"id": "motor", "session_id": "attached", "uuid": "physical", "label": "Left", "slot": "left.1", "age_ms": float64(25), + "values": map[string]any{"erpm": float64(123), "motor_current_a": 0.2}}}} +} + +func TestRoverMetadataKeepsLiveTruthAndRefreshesOnChange(t *testing.T) { + var encoder roverMetadataEncoder + at := time.Unix(100, 0) + snapshot := metadataSnapshot() + before, _ := json.Marshal(snapshot) + first, details := encoder.encode(snapshot, at) + if details["details"] == nil || details["revision"] != uint64(1) { + t.Fatal(details) + } + current := first["devices"].([]any)[0].(map[string]any) + if first["release_confirmed"] != false || current["age_ms"] != float64(25) || current["session_id"] != "attached" { + t.Fatal(first) + } + if !reflect.DeepEqual(current["values"], snapshot["devices"].([]any)[0].(map[string]any)["values"]) { + t.Fatal("live values changed") + } + if _, ok := current["uuid"]; ok { + t.Fatal("metadata repeated") + } + after, _ := json.Marshal(snapshot) + if string(before) != string(after) { + t.Fatal("snapshot mutated") + } + _, ref := encoder.encode(snapshot, at.Add(100*time.Millisecond)) + if len(ref) != 1 || ref["revision"] != uint64(1) { + t.Fatal(ref) + } + _, refresh := encoder.encode(snapshot, at.Add(time.Second)) + if refresh["details"] == nil { + t.Fatal("metadata not refreshed") + } + snapshot["profile"] = map[string]any{"revision": float64(3)} + _, changed := encoder.encode(snapshot, at.Add(1100*time.Millisecond)) + if changed["details"] == nil || changed["revision"] != uint64(2) { + t.Fatal("configuration change delayed") + } + encoder.reset() + _, reconnect := encoder.encode(snapshot, at.Add(1200*time.Millisecond)) + if reconnect["details"] == nil { + t.Fatal("reconnect needs full metadata") + } + snapshot["instance"] = "restarted-driver" + _, restarted := encoder.encode(snapshot, at.Add(1300*time.Millisecond)) + if restarted["details"] == nil { + t.Fatal("driver restart must refresh metadata even with an identical profile") + } +} + +func TestRoverMetadataCannotHideMalformedRoster(t *testing.T) { + for _, change := range []string{"missing_session", "duplicate", "missing_instance"} { + snapshot := metadataSnapshot() + row := snapshot["devices"].([]any)[0].(map[string]any) + switch change { + case "missing_session": + delete(row, "session_id") + case "duplicate": + snapshot["devices"] = []any{row, row} + case "missing_instance": + delete(snapshot, "instance") + } + var encoder roverMetadataEncoder + live, details := encoder.encode(snapshot, time.Now()) + if details != nil || !reflect.DeepEqual(live, snapshot) { + t.Fatal("malformed snapshot hidden") + } + } +} diff --git a/apps/node-agent/internal/node/rover_stream_health.go b/apps/node-agent/internal/node/rover_stream_health.go new file mode 100644 index 00000000..28ea8e80 --- /dev/null +++ b/apps/node-agent/internal/node/rover_stream_health.go @@ -0,0 +1,34 @@ +package node + +import "time" + +// Record receipt before local delivery, including retired frames. This closes +// the evidence gap between Core's socket write and the driver's input receipt. +func (s *roverStreamState) receivedFrame(reply roverStreamReply, at time.Time) { + s.mu.Lock() + s.observeLowerClock(reply.Clock, at) + gap := time.Duration(0) + if !s.streamReceived.IsZero() { + gap = at.Sub(s.streamReceived) + } + s.streamReceived = at + upper := float64(at.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(at.Sub(s.anchored).Microseconds())/1e6 + age := max(0, upper-reply.Clock.MonotonicMS) + id, _ := reply.Command["id"].(string) + retired, pending := s.retired[id], s.stopPending + s.mu.Unlock() + s.budget.ObserveCommandFrame(gap, time.Duration(age*float64(time.Millisecond))) + if s.devTraceEnabled() { + s.recordDev("stream_frame_received", map[string]any{"session_id": id, "sequence": reply.Command["sequence"], + "received_mono_ms": float64(at.Sub(s.origin).Microseconds()) / 1000, + "core_clock_ms": reply.Clock.MonotonicMS, "gap_ms": float64(gap.Microseconds()) / 1000, + "age_upper_ms": age, "retired": retired, "stop_pending": pending}) + } +} + +func (s *roverStreamState) stopDetails() map[string]any { + s.mu.Lock() + defer s.mu.Unlock() + return map[string]any{"reason": s.stopCause, "stop_revision": s.stopRevision, + "last_frame_mono_ms": float64(s.streamReceived.Sub(s.origin).Microseconds()) / 1000} +} diff --git a/apps/node-agent/internal/node/rover_stream_state.go b/apps/node-agent/internal/node/rover_stream_state.go index 692aa860..5a9485c5 100644 --- a/apps/node-agent/internal/node/rover_stream_state.go +++ b/apps/node-agent/internal/node/rover_stream_state.go @@ -12,29 +12,54 @@ type roverClock struct { MonotonicMS float64 `json:"monotonic_ms"` } type roverStreamReply struct { - Watch bool `json:"watch"` - Command map[string]any `json:"command"` - Clock roverClock `json:"control_clock"` + CoreProcessingMS float64 `json:"core_processing_ms"` + ControlActive *bool `json:"control_active"` + DiagnosticsPending *bool `json:"diagnostics_pending"` + Diagnostics map[string]any `json:"diagnostics,omitempty"` + Watch bool `json:"watch"` + Command map[string]any `json:"command"` + Clock roverClock `json:"control_clock"` } // Clock bounds use the request-send time, never RTT/2 or synchronized wall // clocks. Server time was sampled after that send, so it gives an upper bound // on server-minus-local monotonic offset even on an asymmetric network. type roverStreamState struct { - mu sync.Mutex - origin time.Time - clockID string - upperMS float64 - anchored time.Time - clockSeen time.Time - command map[string]any - watch bool - stopPending bool - stopRevision uint64 - snapshot map[string]any - retired map[string]bool - inhibited bool - wake chan struct{} + budget *LinkBudget + latestDatagram bool + roverDetails bool + diagnosticLane bool + budgetInterval bool + diagnosticPending *bool + devID string + devEnabled bool + devDesired map[string]any + devAfter any + devRelayAfter int64 + devSequence int64 + devEvents []map[string]any + devPacket map[string]any + devBudgetAt time.Time + mu sync.Mutex + origin time.Time + clockID string + upperMS float64 + anchored time.Time + clockSeen time.Time + streamReceived time.Time + stopCause string + command map[string]any + watch bool + stopPending bool + stopRevision uint64 + snapshotAt time.Time + telemetryStamped bool + lowerClockMS float64 + lowerClockAt time.Time + snapshot map[string]any + retired map[string]bool + inhibited bool + wake chan struct{} } func newRoverStreamState(now time.Time) *roverStreamState { @@ -58,17 +83,41 @@ func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) b defer s.mu.Unlock() upper := c.MonotonicMS - float64(sent.Sub(s.origin).Microseconds())/1000 + 1 if c.Instance != s.clockID { - s.invalidate() + s.invalidateCause("core_clock_changed") s.clockID = c.Instance + s.lowerClockAt = time.Time{} s.upperMS = upper s.anchored = received } else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 { s.upperMS = upper s.anchored = received } + s.observeLowerClock(c, received) s.clockSeen = received return true } + +// Called with s.mu held. Every authenticated Core clock is a lower bound at +// local receipt. A slow response cannot erase a tighter bound already learned +// from another exchange or the command stream. Advance the old bound with the +// same conservative 1000 ppm drift allowance as telemetryView; never use RTT/2. +// This only timestamps observations. It does not touch the command-clock upper +// bound, clockSeen, original expiry, stop barrier or any motion authority. +func (s *roverStreamState) observeLowerClock(c roverClock, received time.Time) { + if c.Instance != s.clockID || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 { + return + } + lower := c.MonotonicMS + if !s.lowerClockAt.IsZero() { + delta := float64(received.Sub(s.lowerClockAt).Microseconds()) / 1000 + if delta < 0 { + return + } + lower = math.Max(lower, s.lowerClockMS+delta-delta*.001) + } + s.lowerClockMS, s.lowerClockAt = lower, received +} + func (s *roverStreamState) accept(reply roverStreamReply) bool { s.mu.Lock() defer s.mu.Unlock() @@ -77,7 +126,7 @@ func (s *roverStreamState) accept(reply roverStreamReply) bool { } if reply.Command == nil { if s.command != nil { - s.invalidate() + s.invalidateCause("core_withdrew_command") } return true } @@ -139,6 +188,10 @@ func (s *roverStreamState) retire(id string) { s.retired[id] = true } func (s *roverStreamState) invalidate() { + s.invalidateCause("stream_unavailable") +} +func (s *roverStreamState) invalidateCause(cause string) { + s.stopCause = cause wake := !s.stopPending || s.command != nil if s.command != nil { if id, ok := s.command["id"].(string); ok { @@ -162,7 +215,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64 return s.watch, nil, 0 } if now.Sub(s.clockSeen) > 2*time.Second { - s.invalidate() + s.invalidateCause("clock_sample_stale") return s.watch, nil, s.stopRevision } expires, _ := finiteNumber(s.command["expires_mono_ms"]) @@ -171,7 +224,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64 serverUpper := float64(now.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(now.Sub(s.anchored).Microseconds())/1e6 ttl := math.Min(400, expires-serverUpper-25) if ttl <= 0 { - s.invalidate() + s.invalidateCause("command_deadline_expired") return s.watch, nil, s.stopRevision } out := make(map[string]any, 6) @@ -184,8 +237,12 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64 return s.watch, out, 0 } func (s *roverStreamState) delivered(snapshot map[string]any, stop uint64) { + s.deliveredAt(snapshot, stop, time.Now()) +} +func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sampled time.Time) { s.mu.Lock() defer s.mu.Unlock() + s.snapshotAt = sampled s.snapshot = snapshot if stop != 0 && stop == s.stopRevision { s.stopPending = false @@ -197,3 +254,20 @@ func (s *roverStreamState) view() (map[string]any, bool) { return s.snapshot, s.watch } func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() } + +// Conservative capture time in the Core epoch: the reply clock was sampled +// before local receipt. Subtract drift/quantization margin, never RTT/2. +// This is observation age only; command authority still uses its upper bound. +func (s *roverStreamState) telemetryView() (map[string]any, *roverClock) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.telemetryStamped || s.lowerClockAt.IsZero() || s.snapshotAt.IsZero() { + return s.snapshot, nil + } + delta := float64(s.snapshotAt.Sub(s.lowerClockAt).Microseconds()) / 1000 + stamp := s.lowerClockMS + delta - 5 - math.Abs(delta)*.001 + if stamp < 0 { + stamp = 0 + } + return s.snapshot, &roverClock{s.clockID, stamp} +} diff --git a/apps/node-agent/internal/node/rover_stream_state_test.go b/apps/node-agent/internal/node/rover_stream_state_test.go index 5948426a..2146a0d5 100644 --- a/apps/node-agent/internal/node/rover_stream_state_test.go +++ b/apps/node-agent/internal/node/rover_stream_state_test.go @@ -233,3 +233,44 @@ func TestRoverStreamReadsMultipleFramesOnOneResponse(t *testing.T) { t.Fatal(err) } } + +func TestDelayedHTTPClockCannotMakeNewTelemetryArtificiallyStale(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.telemetryStamped = true + s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(50*time.Millisecond)) + // Fast command-stream receipt and a fresh local measurement, followed by + // a late HTTP response sampled much earlier on Core. + s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 10750}}, origin.Add(800*time.Millisecond)) + s.deliveredAt(map[string]any{"state": "observing"}, 0, origin.Add(850*time.Millisecond)) + s.sampleClock(roverClock{testClockID, 10050}, origin.Add(50*time.Millisecond), origin.Add(900*time.Millisecond)) + _, stamp := s.telemetryView() + if stamp == nil || stamp.MonotonicMS < 10790 || stamp.MonotonicMS > 10850 { + t.Fatal("late response rolled the observation clock backwards", stamp) + } + // No new measurement: advancing the bounds cannot rejuvenate the sample. + before := stamp.MonotonicMS + s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 11750}}, origin.Add(1800*time.Millisecond)) + _, stale := s.telemetryView() + if stale.MonotonicMS > before+2 || s.command != nil { + t.Fatal("old sample/authority renewed", stale, s.command) + } +} + +func TestObservationClockEpochAndInvalidSamplesCannotReuseOldBound(t *testing.T) { + origin := time.Unix(100, 0) + s := newRoverStreamState(origin) + s.telemetryStamped = true + s.sampleClock(roverClock{testClockID, 10000}, origin, origin) + s.receivedFrame(roverStreamReply{Clock: roverClock{"foreign", 99999}}, origin.Add(time.Millisecond)) + if s.lowerClockMS != 10000 { + t.Fatal("foreign clock changed lower bound") + } + next := "cccccccccccccccccccccccccccccccc" + s.sampleClock(roverClock{next, 10}, origin.Add(time.Second), origin.Add(time.Second)) + s.deliveredAt(map[string]any{}, 0, origin.Add(time.Second)) + _, stamp := s.telemetryView() + if stamp.Instance != next || stamp.MonotonicMS > 10 || s.command != nil { + t.Fatal("old epoch retained", stamp) + } +} diff --git a/apps/node-agent/internal/node/rover_transport.go b/apps/node-agent/internal/node/rover_transport.go new file mode 100644 index 00000000..0dc0f33d --- /dev/null +++ b/apps/node-agent/internal/node/rover_transport.go @@ -0,0 +1,22 @@ +package node + +import ( + "crypto/tls" + "net" + "net/http" + "time" +) + +const roverConnectTimeout = 2 * time.Second + +// Each rover lane owns its connection pool. Establishing a connection grants +// neither a command lease nor permission to revive an interrupted session. +func newRoverHTTPTransport(config *tls.Config) *http.Transport { + return &http.Transport{TLSClientConfig: config, Proxy: nil, + MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second, + TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second, + // A one-second connect deadline races the initial SYN retransmission. + // Allow that retry; the probe's 2.5 s context and lane cancellation still + // bound establishment. This never extends a command or the stream guard. + DialContext: (&net.Dialer{Timeout: roverConnectTimeout}).DialContext} +} diff --git a/apps/node-agent/internal/node/sensor_failure_result_test.go b/apps/node-agent/internal/node/sensor_failure_result_test.go new file mode 100644 index 00000000..025d4d49 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_failure_result_test.go @@ -0,0 +1,37 @@ +package node + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestSensorFailureKeepsNativeEvidenceForCore(t *testing.T) { + root := t.TempDir() + s, _ := OpenSensors(root, "node_test") + isolateSensorHost(t, s) + c := sensorTestCommand() + s.operations[c.ID] = &SensorOperation{Command: c, State: "running", Remote: true} + s.client = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + body := `{"items":[{"id":"` + c.Session.DeviceID + `"}]}` + if r.URL.Path == "/operation" { + body = `{"state":"error","error":"Read failed","result":{"failure":{"native_rpc":{"method":"diagnostic","command":"hw_status","error":"No response"}}}}` + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + })} + s.execute(c) + value := s.Get(c.ID) + if value.State != "error" || value.Error != "Read failed" || value.Result == nil { + t.Fatalf("Lost driver failure: %+v", value) + } + failure := value.Result.(map[string]any)["failure"].(map[string]any) + rpc := failure["native_rpc"].(map[string]any) + if rpc["command"] != "hw_status" { + t.Fatal("Wrong native request retained") + } + reopened, err := OpenSensors(root, "node_test") + if err != nil || reopened.Get(c.ID) == nil || reopened.Get(c.ID).Result == nil { + t.Fatal("Failure evidence lost after restart", err) + } +} diff --git a/apps/node-agent/internal/node/sensor_models.go b/apps/node-agent/internal/node/sensor_models.go index 251dce01..fdee1baa 100644 --- a/apps/node-agent/internal/node/sensor_models.go +++ b/apps/node-agent/internal/node/sensor_models.go @@ -33,7 +33,7 @@ func actions(names ...string) map[string]bool { } var sensorModels = []sensorModel{ - {ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.6", + {ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.7", Vendor: "8086", Product: "0b5c", Socket: "/run/mission-core-sensors/driver.sock", PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json", Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")}, @@ -46,11 +46,15 @@ var sensorModels = []sensorModel{ PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json", ActionTimeouts: map[string]time.Duration{"power.wake": 55 * time.Second}, Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer", "recovery.configure", "power.wake")}, - {ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.7.4", + {ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.20.11", Vendor: "0483", Product: "5740", USBName: "ChibiOS/RT Virtual COM Port", Socket: "/run/mission-core-vesc/driver.sock", PrepareUnit: "mission-core-node-vesc-prepare.service", Report: "/var/lib/mission-core-node-profiles/vesc/preparation.json", - ActionTimeouts: map[string]time.Duration{"vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second}, - ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")}, + ActionTimeouts: map[string]time.Duration{"vesc.packages.apply": 350 * time.Second, "vesc.packages.prepare": 70 * time.Second, "vesc.packages.status": 70 * time.Second, "vesc.packages.restore": 70 * time.Second, "vesc.packages.reconcile": 70 * time.Second, "vesc.packages.remove_prepare": 70 * time.Second, "vesc.code.apply": 180 * time.Second, "vesc.firmware.apply": 300 * time.Second, "vesc.configuration.apply": 60 * time.Second, "vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second}, + ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", "vesc.bms.configuration.apply", "vesc.bms.configuration.reconcile", "vesc.bms.configuration.restore", "vesc.packages.catalog", "vesc.packages.inspect", "vesc.packages.download", "vesc.packages.begin", "vesc.packages.chunk", "vesc.packages.load", "vesc.packages.forget", "vesc.packages.status", "vesc.packages.prepare", "vesc.packages.remove_prepare", "vesc.packages.restore", "vesc.packages.apply", "vesc.packages.reconcile", "vesc.packages.refresh", "vesc.samples.start", "vesc.samples.status", "vesc.samples.fetch", "vesc.samples.stop", "vesc.samples.read", "vesc.qml.begin", "vesc.qml.chunk", "vesc.qml.render", "vesc.qml.open", "vesc.qml.frame", "vesc.qml.close", "vesc.code.read", "vesc.code.begin", "vesc.code.chunk", "vesc.code.prepare", "vesc.code.erase_prepare", "vesc.code.apply", "vesc.code.reconcile", "vesc.code.control_prepare", "vesc.code.control_apply", "vesc.code.stats", "vesc.code.restore", "vesc.bms.read", "vesc.bms.prepare", "vesc.bms.apply", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.reconcile", "vesc.firmware.backup", "vesc.firmware.target", "vesc.firmware.catalog", "vesc.firmware.catalog_prepare", "vesc.firmware.begin", "vesc.firmware.chunk", "vesc.firmware.seal", "vesc.firmware.discard", "vesc.firmware.apply", "vesc.firmware.status", "vesc.firmware.cancel", "vesc.firmware.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")}, + {ID: "waveshare.usb-can-fd-b", Name: "Waveshare USB-CAN-FD-B", Prefix: "usbcan", Kind: "waveshare.usb-can-fd-b", Plugin: "missioncore.usb-can", Version: "0.2.7", + Vendor: "04d8", Product: "0053", USBName: "USB CANFD DEBUG", Socket: "/run/mission-core-usb-can/driver.sock", + PrepareUnit: "mission-core-node-usb-can-prepare.service", Report: "/var/lib/mission-core-node-profiles/usb-can/preparation.json", + ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop")}, } func modelForDevice(id string) *sensorModel { diff --git a/apps/node-agent/internal/node/sensor_snapshots.go b/apps/node-agent/internal/node/sensor_snapshots.go new file mode 100644 index 00000000..03331cf1 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_snapshots.go @@ -0,0 +1,67 @@ +package node + +import ( + "encoding/json" + "strings" + "time" +) + +// Configuration browsing is a bounded snapshot, not a durable backup or write receipt. +func sensorSnapshot(action string) bool { + return strings.HasPrefix(action, "can.") || action == "vesc.qml.open" || action == "vesc.qml.frame" || action == "vesc.qml.close" || action == "vesc.samples.start" || action == "vesc.samples.status" || action == "vesc.samples.fetch" || action == "vesc.samples.stop" || action == "vesc.samples.read" || action == "vesc.qml.begin" || action == "vesc.qml.chunk" || action == "vesc.qml.render" || action == "vesc.packages.catalog" || action == "vesc.packages.inspect" || action == "vesc.packages.download" || action == "vesc.packages.begin" || action == "vesc.packages.chunk" || action == "vesc.packages.load" || action == "vesc.packages.forget" || action == "vesc.packages.status" || action == "vesc.packages.prepare" || action == "vesc.packages.remove_prepare" || action == "vesc.packages.restore" || action == "vesc.packages.reconcile" || action == "vesc.packages.refresh" || action == "vesc.bms.configuration.read" || action == "vesc.bms.configuration.preview" || action == "vesc.bms.configuration.reconcile" || action == "vesc.bms.configuration.restore" || action == "vesc.code.read" || action == "vesc.code.begin" || action == "vesc.code.chunk" || action == "vesc.code.prepare" || action == "vesc.code.erase_prepare" || action == "vesc.code.reconcile" || action == "vesc.code.control_prepare" || action == "vesc.code.stats" || action == "vesc.code.restore" || action == "vesc.firmware.backup" || action == "vesc.firmware.target" || action == "vesc.bms.read" || action == "vesc.bms.prepare" || action == "vesc.firmware.catalog" || action == "vesc.tools.read" || action == "vesc.terminal.read" || action == "vesc.firmware.status" || action == "vesc.configuration.read" || action == "vesc.configuration.preview" || action == "vesc.diagnostics.read" +} + +func expiredSensorSnapshot(value SensorOperation) SensorOperation { + value.State = "error" + value.Error = "Снимок больше не хранится. Прочитайте данные заново." + value.Result = nil + return value +} + +// Caller owns s.mu. Retain at most eight payloads (8 MiB); never evict an +// unacknowledged remote result to admit a new request. Tombstones retain +// operation identity, so retrying an old ID cannot execute hardware work again. +func (s *Sensors) writeOperation(value *SensorOperation) error { + // CAN requests/results are bounded RAM. On restart every USB generation is + // replaced; queued old-session commands cannot execute or replay TX. + if strings.HasPrefix(value.Command.Action, "can.") && value.Result == nil { return nil } + + if !sensorSnapshot(value.Command.Action) || value.Result == nil { + return s.write(value.Command.ID+".json", value) + } + for { + count, bytes := 0, 0 + var oldest *SensorOperation + for _, entry := range s.operations { + if !sensorSnapshot(entry.Command.Action) || entry.Result == nil { + continue + } + raw, err := json.Marshal(entry.Result) + if err != nil { + return err + } + count++ + bytes += len(raw) + if entry != value && !entry.Remote && (oldest == nil || entry.Updated < oldest.Updated) { + oldest = entry + } + } + if count <= 8 && bytes <= 8*1024*1024 { + break + } + if oldest == nil { + *value = expiredSensorSnapshot(*value) + break + } + *oldest = expiredSensorSnapshot(*oldest) + } + // Payloads expire even if the operator leaves this panel open overnight. + for _, entry := range s.operations { + if sensorSnapshot(entry.Command.Action) && entry.Result != nil && !entry.Remote && time.Now().Unix()-entry.Updated >= 600 { + *entry = expiredSensorSnapshot(*entry) + } + } + if strings.HasPrefix(value.Command.Action, "can.") { return nil } + persisted := expiredSensorSnapshot(*value) + return s.write(value.Command.ID+".json", &persisted) +} diff --git a/apps/node-agent/internal/node/sensor_snapshots_test.go b/apps/node-agent/internal/node/sensor_snapshots_test.go new file mode 100644 index 00000000..c34f3364 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_snapshots_test.go @@ -0,0 +1,61 @@ +package node + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestSensorConfigurationSnapshotsBoundedAndNotPersisted(t *testing.T) { + s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}} + for i := 0; i < 12; i++ { + id := strings.Repeat("a", i+1) + op := &SensorOperation{Command: SensorCommand{ID: id, Action: "vesc.configuration.read"}, State: "complete", Result: map[string]any{"xml": strings.Repeat("x", 100)}, Updated: time.Now().Unix() + int64(i)} + s.operations[id] = op + if err := s.writeOperation(op); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(s.root, id+".json")) + if err != nil { + t.Fatal(err) + } + var disk SensorOperation + if err = json.Unmarshal(raw, &disk); err != nil { + t.Fatal(err) + } + if disk.Result != nil || disk.State != "error" { + t.Fatal("read payload was persisted") + } + } + count := 0 + for _, op := range s.operations { + if op.Result != nil { + count++ + } + } + if count != 8 { + t.Fatalf("snapshot count %d", count) + } + if s.operations["a"].State != "error" { + t.Fatal("old snapshot remained live") + } +} + +func TestConfigurationBackupsRemainDurable(t *testing.T) { + s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}} + op := &SensorOperation{Command: SensorCommand{ID: "backup", Action: "vesc.config.backup"}, State: "complete", Result: map[string]any{"backup": true}} + if err := s.writeOperation(op); err != nil { + t.Fatal(err) + } + raw, _ := os.ReadFile(filepath.Join(s.root, "backup.json")) + var disk SensorOperation + if err := json.Unmarshal(raw, &disk); err != nil { + t.Fatal(err) + } + if disk.Result == nil || disk.State != "complete" { + t.Fatal("backup receipt was discarded") + } +} diff --git a/apps/node-agent/internal/node/sensor_telemetry.go b/apps/node-agent/internal/node/sensor_telemetry.go new file mode 100644 index 00000000..90d53689 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_telemetry.go @@ -0,0 +1,38 @@ +package node + +import ( + "context" + "net/http" + "time" +) + +// Only the existing observer owns USB sampling. This endpoint renews bounded +// read interest; it cannot pass a relay, command, action or input lease. +func (s *Sensors) telemetryRoutes(mux *http.ServeMux, server *Server) { + mux.HandleFunc("GET /api/devices/telemetry", func(w http.ResponseWriter, r *http.Request) { + if !server.authorized(w, r) { + return + } + w.Header().Set("Cache-Control", "no-store") + var model *sensorModel + for i := range sensorModels { + if sensorModels[i].ID == "vesc.controller" { + model = &sensorModels[i] + break + } + } + if model == nil { + reply(w, 503, map[string]string{"error": "Интеграция VESC недоступна."}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond) + defer cancel() + result, err := s.modelDriver(ctx, model, "/observe", nil) + if err != nil { + reply(w, 503, map[string]string{"error": "Нет свежих показаний контроллеров."}) + return + } + result["fresh"] = true + reply(w, 200, result) + }) +} diff --git a/apps/node-agent/internal/node/sensor_telemetry_test.go b/apps/node-agent/internal/node/sensor_telemetry_test.go new file mode 100644 index 00000000..03fb27d2 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_telemetry_test.go @@ -0,0 +1,40 @@ +package node + +import ( + "errors" + "net/http" + "testing" + "time" +) + +func TestTelemetryReadCannotCarryControlOrRenewInputLease(t *testing.T) { + server := newTestServer(t) + server.Sensors = isolatedSensors(t) + calls := 0 + model := modelForDevice("vesc_00000000000000000000000000000000") + server.Sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + calls++ + if r.Method != "GET" || r.URL.Path != "/observe" || r.Body != nil { + t.Fatal("read became a command", r) + } + deadline, ok := r.Context().Deadline() + if !ok || time.Until(deadline) > 800*time.Millisecond { + t.Fatal("unbounded read") + } + return testSensorReply(map[string]any{"instance": "synthetic", "devices": []any{}}), nil + }) + if response := call(server, "GET", "/api/devices/telemetry", "", nil); response.Code != 401 || calls != 0 { + t.Fatal("unauthorized read", response.Code, calls) + } + cookie := login(t, server) + if response := call(server, "GET", "/api/devices/telemetry", "", cookie); response.Code != 200 || calls != 1 || response.Header().Get("Cache-Control") != "no-store" { + t.Fatal("snapshot", response.Code, calls) + } + if response := call(server, "POST", "/api/devices/telemetry", `{"command":{"left":1}}`, cookie); response.Code == 200 || calls != 1 { + t.Fatal("command accepted") + } + server.Sensors.clients[model.ID].Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) { return nil, errors.New("offline") }) + if response := call(server, "GET", "/api/devices/telemetry", "", cookie); response.Code != 503 { + t.Fatal("offline became fresh", response.Code) + } +} diff --git a/apps/node-agent/internal/node/sensor_vesc_packages.go b/apps/node-agent/internal/node/sensor_vesc_packages.go new file mode 100644 index 00000000..110c9f7b --- /dev/null +++ b/apps/node-agent/internal/node/sensor_vesc_packages.go @@ -0,0 +1,60 @@ +package node + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "time" +) + +// This is the upstream VESC Tool catalogue URL. The publisher currently serves +// it over HTTP. Treat every byte as untrusted code/data: fetching updates only +// the catalogue, never installs or executes a controller application. +const vescPackageCatalogueURL = "http://home.vedder.se/vesc_pkg/vesc_pkg_all.rcc" +const vescPackageCatalogueMax = 8 * 1024 * 1024 + +func fetchVescPackageCatalogue(ctx context.Context, client *http.Client) ([]byte,error) { + request,err:=http.NewRequestWithContext(ctx,http.MethodGet,vescPackageCatalogueURL,nil) + if err!=nil{return nil,err} + response,err:=client.Do(request) + if err!=nil{return nil,errors.New("Каталог автора недоступен. Сохранённый каталог остаётся доступным.")} + defer response.Body.Close() + if response.StatusCode!=http.StatusOK{return nil,errors.New("Автор каталога не вернул архив. Сохранённый каталог не изменён.")} + data,err:=io.ReadAll(io.LimitReader(response.Body,vescPackageCatalogueMax+1)) + if err!=nil||len(data)>vescPackageCatalogueMax||!bytes.HasPrefix(data,[]byte("qres")){return nil,errors.New("Получен некорректный или слишком большой каталог.")} + return data,nil +} + +func (s *Sensors) refreshVescPackages(c SensorCommand) (any,error) { + if len(c.Parameters)!=0{return nil,errors.New("Обновление использует только официальный каталог VESC.")} + deadline,_:=time.Parse(time.RFC3339Nano,c.Deadline) + ctx,cancel:=context.WithDeadline(context.Background(),deadline);defer cancel() + // No user URL, proxy environment, cookies, credentials or redirects. The USB + // driver keeps its PrivateNetwork sandbox and never performs Internet I/O. + transport:=&http.Transport{Proxy:nil,MaxIdleConns:1,DisableKeepAlives:true,ResponseHeaderTimeout:15*time.Second} + defer transport.CloseIdleConnections() + client:=&http.Client{Transport:transport,Timeout:35*time.Second,CheckRedirect:func(*http.Request,[]*http.Request)error{return http.ErrUseLastResponse}} + data,err:=fetchVescPackageCatalogue(ctx,client);if err!=nil{return nil,err} + sum:=sha256.Sum256(data) + step:=0 + call:=func(action string,parameters map[string]any)(map[string]any,error){ + child:=c;step++;id:=sha256.Sum256([]byte(fmt.Sprintf("%s/packages/%d",c.ID,step)));child.ID="op_"+hex.EncodeToString(id[:16]);child.Idempotency=child.ID;child.Action="vesc.packages."+action;child.Parameters=parameters + response,e:=s.modelDriver(ctx,modelForDevice(c.Session.DeviceID),"/operation",child) + if e!=nil{return nil,e};if response["state"]!="complete"{return nil,errors.New("Не удалось проверить новый каталог. Предыдущий каталог сохранён.")} + value,ok:=response["result"].(map[string]any);if !ok{return nil,errors.New("Некорректный ответ каталога.")};return value,nil + } + begin,err:=call("begin",map[string]any{"kind":"catalog","name":"vesc_pkg_all.rcc","size":len(data),"sha256":hex.EncodeToString(sum[:]),"library":false,"source":"upstream"});if err!=nil{return nil,err} + upload,ok:=begin["upload_id"].(string);if !ok{return nil,errors.New("Передача каталога не начата.")} + for offset:=0;offsetlen(data){end=len(data)} + result,e:=call("chunk",map[string]any{"upload_id":upload,"offset":offset,"data":base64.StdEncoding.EncodeToString(data[offset:end])});if e!=nil{return nil,e} + accepted,ok:=result["offset"].(float64);if !ok||int(accepted)!=end{return nil,errors.New("Передача каталога не подтверждена.")} + } + return call("load",map[string]any{"upload_id":upload}) +} diff --git a/apps/node-agent/internal/node/sensor_vesc_packages_test.go b/apps/node-agent/internal/node/sensor_vesc_packages_test.go new file mode 100644 index 00000000..5ffa34f3 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_vesc_packages_test.go @@ -0,0 +1,10 @@ +package node +import("context";"io";"net/http";"strings";"testing") +type packageRoundTripper func(*http.Request)(*http.Response,error) +func(f packageRoundTripper)RoundTrip(r *http.Request)(*http.Response,error){return f(r)} +func TestPackageCatalogueFixedSourceAndBound(t *testing.T){ + for _,test:=range []struct{body string;status int;valid bool}{{"qres-test",200,true},{"",200,false},{"qres",503,false},{"qres"+strings.Repeat("a",vescPackageCatalogueMax),200,false}}{ + client:=&http.Client{Transport:packageRoundTripper(func(r *http.Request)(*http.Response,error){if r.URL.String()!=vescPackageCatalogueURL||r.Method!="GET"||r.Header.Get("Authorization")!=""{t.Fatal("unexpected source/request")};return &http.Response{StatusCode:test.status,Body:io.NopCloser(strings.NewReader(test.body)),Header:make(http.Header)},nil})} + _,err:=fetchVescPackageCatalogue(context.Background(),client);if (err==nil)!=test.valid{t.Fatalf("expected valid %v, got %v",test.valid,err)} + } +} diff --git a/apps/node-agent/internal/node/sensor_vesc_test.go b/apps/node-agent/internal/node/sensor_vesc_test.go index 5c3016a7..09504e4e 100644 --- a/apps/node-agent/internal/node/sensor_vesc_test.go +++ b/apps/node-agent/internal/node/sensor_vesc_test.go @@ -12,20 +12,26 @@ import ( "testing" ) -func TestVESCDeclaredVersionMatchesBundledDriver(t *testing.T) { - model := modelForDevice("vesc_00000000000000000000000000000000") - root := filepath.Join("..", "..", "..", "..", "plugins", "vesc") - driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py")) - if err != nil { - t.Fatal(err) - } - match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver) - if model == nil || len(match) != 2 || model.Version != string(match[1]) { - t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver)) - } - preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py")) - if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) { - t.Fatal("VESC preparation must declare the bundled driver version", err) +func TestProtocolModelVersionsMatchBundledDrivers(t *testing.T) { + // A mismatched declaration silently replaces a healthy protocol device + // with USB discovery and a second, offline saved identity in Inventory. + for _, plugin := range []struct{ prefix, directory string }{ + {"vesc", "vesc"}, {"usbcan", "usb-can"}, + } { + t.Run(plugin.directory, func(t *testing.T) { + model := modelForDevice(plugin.prefix + "_00000000000000000000000000000000") + root := filepath.Join("..", "..", "..", "..", "plugins", plugin.directory) + driver, err := os.ReadFile(filepath.Join(root, "runtime", "__init__.py")) + if err != nil { t.Fatal(err) } + match := regexp.MustCompile(`(?m)^VERSION = "([^"]+)"`).FindSubmatch(driver) + if model == nil || len(match) != 2 || model.Version != string(match[1]) { + t.Fatal("Node must admit the exact driver shipped in the same release", model, string(driver)) + } + preparation, err := os.ReadFile(filepath.Join(root, "packaging", "prepare.py")) + if err != nil || !strings.Contains(string(preparation), `"version": "`+model.Version+`"`) { + t.Fatal("Preparation must declare the bundled driver version", err) + } + }) } } @@ -139,3 +145,86 @@ func TestVESCPreparePromotesAttachmentToProtocolUUID(t *testing.T) { t.Fatal("unplugged driver observation accepted") } } + +func TestVESCCANAndOfflineAssignmentsDoNotRequireDirectUSB(t *testing.T) { + s := isolatedSensors(t) + model := modelForDevice("vesc_00000000000000000000000000000000") + uuid := strings.Repeat("01", 12) + id := modelDeviceID(model, "uuid:"+uuid) + item := s.discovery(id, "—", false) + item["prepared"], item["verified"] = true, false + status := map[string]any{ + "identity": map[string]any{"uuid": uuid}, "connected": false, + "board_settings_supported": true, + "drive_profile": map[string]any{"bindings": map[string]any{"left.1": map[string]any{"device_id": id, "uuid": uuid}}}, + } + item["vesc_status"] = status + s.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) { + return testSensorReply(map[string]any{"items": []any{item}}), nil + }) + check := func(want bool) { + t.Helper() + all := s.Inventory()["items"].([]any) + items := []any{} + for _, raw := range all { if raw.(map[string]any)["kind"] == "vesc.controller" { items = append(items, raw) } } + if (len(items) == 1) != want { + t.Fatalf("unexpected transport projection: %v", items) + } + if want && items[0].(map[string]any)["prepared"] != true { + t.Fatal("driver metadata lost") + } + } + check(true) + item["online"], item["verified"], status["connected"] = true, true, true + route := map[string]any{"kind": "can", "uuid": uuid, "adapter_id": "usbcan_synthetic", "channel": 0, "can_id": 74, "bitrate": 500000} + status["control_transport"] = map[string]any{"routes": map[string]any{id: route}} + endpoint := map[string]any{"device_id": id, "uuid": uuid, "route": route, "verified": true, "session_id": sensorSessionID(item)} + status["control_endpoints"] = []any{endpoint} + fakeUSB(t, s.usbRoot, "2-8", "", "USB CANFD DEBUG", "8") + for key, value := range map[string]string{"idVendor": "04d8", "idProduct": "0053"} { + if err := os.WriteFile(filepath.Join(s.usbRoot, "2-8", key), []byte(value), 0600); err != nil { t.Fatal(err) } + } + adapterAttachment := discoverSensors(s.usbRoot)[0].id + status["control_adapters"] = []any{map[string]any{"id": "usbcan_synthetic", "attachment_id": adapterAttachment}} + check(true) + fakeVESC(t, s, "1-2", "3") + attachment := discoverSensors(s.usbRoot)[0].id + status["control_endpoints"] = []any{endpoint, map[string]any{ + "device_id": id, "uuid": uuid, "attachment_id": attachment, "verified": true, + "route": map[string]any{"kind": "usb", "uuid": uuid}, + }} + check(true) // Both wires still produce exactly one logical controller. + if err := os.RemoveAll(filepath.Join(s.usbRoot, "1-2")); err != nil { + t.Fatal(err) + } + status["control_endpoints"] = []any{endpoint} + endpoint["session_id"] = "stale" + check(false) + endpoint["session_id"] = sensorSessionID(item) + status["control_adapters"] = []any{} + check(true) + status["control_adapters"] = []any{map[string]any{"id": "usbcan_synthetic", "attachment_id": adapterAttachment}} + // Cached driver says online, but the selected OS adapter was unplugged. + if err := os.RemoveAll(filepath.Join(s.usbRoot, "2-8")); err != nil { t.Fatal(err) } + items := s.Inventory()["items"].([]any) + if len(items) != 1 { t.Fatal("assigned UUID metadata must survive adapter detach", items) } + offline := items[0].(map[string]any) + offstatus := offline["vesc_status"].(map[string]any) + if offline["online"] != false || offline["verified"] != false || offstatus["connected"] != false || offstatus["telemetry_ready"] != false { + t.Fatal("cached CAN driver outlived its physical adapter", offline) + } + // Reconnecting another USB generation must not revive the old CAN session. + fakeUSB(t, s.usbRoot, "2-8", "", "USB CANFD DEBUG", "9") + for key, value := range map[string]string{"idVendor": "04d8", "idProduct": "0053"} { + if err := os.WriteFile(filepath.Join(s.usbRoot, "2-8", key), []byte(value), 0600); err != nil { t.Fatal(err) } + } + for _, raw := range s.Inventory()["items"].([]any) { + it := raw.(map[string]any) + if it["id"] == id && it["online"] != false { t.Fatal("old adapter generation revived", it) } + } + route["kind"] = "usb" + check(false) // A stale direct USB observation never uses the CAN exception. + item["online"], item["verified"], status["connected"] = false, false, false + status["identity"] = map[string]any{"uuid": strings.Repeat("02", 12)} + check(false) +} diff --git a/apps/node-agent/internal/node/sensor_vesc_transport.go b/apps/node-agent/internal/node/sensor_vesc_transport.go new file mode 100644 index 00000000..5cc67f9d --- /dev/null +++ b/apps/node-agent/internal/node/sensor_vesc_transport.go @@ -0,0 +1,141 @@ +package node + +import ( + "encoding/json" + "regexp" +) + +var vescUUID = regexp.MustCompile(`^[a-f0-9]{24}$`) + +// Only the current installed VESC driver may project assigned offline metadata +// or a verified CAN endpoint. USB projections retain their existing OS guard. +func vescNonUSBProjection(item map[string]any, model *sensorModel) bool { + if model.ID != "vesc.controller" || !currentCameraSnapshot(item, model) { + return false + } + status, _ := item["vesc_status"].(map[string]any) + identity, _ := status["identity"].(map[string]any) + uuid, _ := identity["uuid"].(string) + id, _ := item["id"].(string) + if !vescUUID.MatchString(uuid) || modelDeviceID(model, "uuid:"+uuid) != id { + return false + } + drive, _ := status["drive_profile"].(map[string]any) + bindings, _ := drive["bindings"].(map[string]any) + assigned := false + for _, raw := range bindings { + binding, _ := raw.(map[string]any) + assigned = assigned || (binding["device_id"] == id && binding["uuid"] == uuid) + } + if !assigned || status["board_settings_supported"] != true { + return false + } + if item["online"] == false && item["verified"] == false && status["connected"] == false { + return true // Metadata only, never an available control endpoint. + } + if item["online"] != true || item["verified"] != true || status["connected"] != true { + return false + } + profile, _ := status["control_transport"].(map[string]any) + routes, _ := profile["routes"].(map[string]any) + route, _ := routes[id].(map[string]any) + if route["kind"] != "can" || route["uuid"] != uuid { + return false + } + adapterID, _ := route["adapter_id"].(string) + adapters, _ := status["control_adapters"].([]any) + present := false + for _, raw := range adapters { + adapter, _ := raw.(map[string]any) + present = present || (adapterID != "" && adapter["id"] == adapterID) + } + if !present { + return false + } + selected, err := json.Marshal(route) + if err != nil { + return false + } + endpoints, _ := status["control_endpoints"].([]any) + for _, raw := range endpoints { + endpoint, _ := raw.(map[string]any) + actual, err := json.Marshal(endpoint["route"]) + if err == nil && endpoint["device_id"] == id && endpoint["uuid"] == uuid && + endpoint["verified"] == true && endpoint["session_id"] == sensorSessionID(item) && + string(actual) == string(selected) { + return true + } + } + return false +} + +// A verified USB endpoint of the same MCU is an alias, not a second controller +// when its selected route is CAN or temporarily unavailable. +func vescUSBEndpointAlias(item map[string]any, model *sensorModel, attachment string) bool { + if model.ID != "vesc.controller" { + return false + } + status, _ := item["vesc_status"].(map[string]any) + identity, _ := status["identity"].(map[string]any) + uuid, _ := identity["uuid"].(string) + if !vescUUID.MatchString(uuid) || item["id"] != modelDeviceID(model, "uuid:"+uuid) { + return false + } + endpoints, _ := status["control_endpoints"].([]any) + for _, raw := range endpoints { + e, _ := raw.(map[string]any) + route, _ := e["route"].(map[string]any) + if e["device_id"] == item["id"] && e["uuid"] == uuid && e["verified"] == true && + e["attachment_id"] == attachment && route["kind"] == "usb" && route["uuid"] == uuid { + return true + } + } + return false +} + +// Invalidate a selected CAN route in the same OS inventory that loses its USB +// adapter, even while the VESC discovery thread is waiting for a reply/cleanup. +// Preserve UUID/configuration metadata; absence never changes the saved route. +func vescReconcileCANPresence(item map[string]any, model *sensorModel, usb []usbSensor) { + if model.ID != "vesc.controller" || !currentCameraSnapshot(item, model) { return } + status, _ := item["vesc_status"].(map[string]any) + profile, _ := status["control_transport"].(map[string]any) + routes, _ := profile["routes"].(map[string]any) + id, _ := item["id"].(string) + route, _ := routes[id].(map[string]any) + if route["kind"] != "can" { return } + adapters, _ := status["control_adapters"].([]any) + live := map[string]bool{} + current := []any{} + for _, raw := range adapters { + adapter, _ := raw.(map[string]any) + aid, _ := adapter["id"].(string) + attachment, _ := adapter["attachment_id"].(string) + for _, physical := range usb { + if aid != "" && attachment != "" && physical.model.ID == "waveshare.usb-can-fd-b" && physical.id == attachment { + live[aid] = true + current = append(current, raw) + break + } + } + } + status["control_adapters"] = current + endpoints, _ := status["control_endpoints"].([]any) + for _, raw := range endpoints { + endpoint, _ := raw.(map[string]any) + r, _ := endpoint["route"].(map[string]any) + aid, _ := r["adapter_id"].(string) + if r["kind"] == "can" && !live[aid] { endpoint["verified"] = false } + } + aid, _ := route["adapter_id"].(string) + if live[aid] { return } + item["online"], item["verified"] = false, false + status["connected"], status["readable"], status["telemetry_ready"], status["test_supported"] = false, false, false, false + status["telemetry"] = nil + status["message"] = "CAN-адаптер недоступен." + snapshot, _ := item["snapshot"].(map[string]any) + if snapshot != nil { + snapshot["connectivity"] = "offline" + snapshot["message"] = status["message"] + } +} diff --git a/apps/node-agent/internal/node/sensors.go b/apps/node-agent/internal/node/sensors.go index f2a6c696..da5ec21d 100644 --- a/apps/node-agent/internal/node/sensors.go +++ b/apps/node-agent/internal/node/sensors.go @@ -247,6 +247,7 @@ func (s *Sensors) Inventory() map[string]any { if !currentCameraSnapshot(item, model) { continue } + vescReconcileCANPresence(item, model, usb) attachment, _ := item["attachment_id"].(string) matched := false for _, candidate := range usb { @@ -254,10 +255,17 @@ func (s *Sensors) Inventory() map[string]any { matched = true } } - if !matched { + if !matched && !vescNonUSBProjection(item, model) { continue } - seen[attachment] = true + if matched { + seen[attachment] = true + } + for _, candidate := range usb { + if candidate.model == model && vescUSBEndpointAlias(item, model, candidate.id) { + seen[candidate.id] = true + } + } } s.mu.Lock() if model.PrepareUnit != "" && !model.ProtocolIdentity { @@ -354,7 +362,7 @@ func (s *Sensors) discovery(id, speed string, online bool) map[string]any { } func sensorViewAction(action string) bool { - return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.config.backup" + return action == "can.status" || action == "vesc.firmware.status" || action == "vesc.firmware.cancel" || action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list" || action == "vesc.telemetry.read" || action == "vesc.limits.read" || action == "vesc.configuration.read" || action == "vesc.diagnostics.read" || action == "vesc.config.backup" } func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) { @@ -388,10 +396,10 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) return nil, errors.New("Срок команды истёк. Устройство не изменено.") } for _, v := range s.operations { - if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model { + if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && c.Action != "vesc.motor.stop" && c.Action != "can.stop" && c.Action != "can.transmit.stop" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model { return nil, errors.New("Подготовка модели ещё выполняется.") } - if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) { + if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && c.Action != "vesc.motor.stop" && c.Action != "can.stop" && c.Action != "can.transmit.stop" && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) { return nil, errors.New("Другая операция устройства ещё выполняется.") } } @@ -407,7 +415,7 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) return nil, errors.New("Журнал операций заполнен. Повторите позже.") } value := &SensorOperation{Command: c, State: "running", Remote: remote, Updated: time.Now().Unix()} - if e = s.write(c.ID+".json", value); e != nil { + if e = s.writeOperation(value); e != nil { return nil, e } s.operations[c.ID] = value @@ -444,6 +452,8 @@ func (s *Sensors) execute(c SensorCommand) { } else if c.Action == "prepare" { result, err = s.prepare(c, item) uncertain = errors.Is(err, errPreparationUncertain) + } else if c.Action == "vesc.packages.refresh" { + result, err = s.refreshVescPackages(c) } else if c.Action == "rename" { name, ok := c.Parameters["name"].(string) if !ok || strings.TrimSpace(name) == "" || len([]rune(name)) > 80 || strings.ContainsAny(name, "\n\r\t") { @@ -463,9 +473,8 @@ func (s *Sensors) execute(c SensorCommand) { cancel() uncertain = err != nil || v["state"] == "unknown" if err == nil { - if v["state"] == "complete" { - result = v["result"] - } else { + result = v["result"] + if v["state"] != "complete" { message, _ := v["error"].(string) err = errors.New(message) } @@ -487,6 +496,8 @@ func (s *Sensors) execute(c SensorCommand) { } v := s.operations[c.ID] v.Updated = time.Now().Unix() + // Preserve bounded driver diagnostics on error as well as successful data. + v.Result = result if err != nil { v.State = "error" if uncertain { @@ -497,7 +508,7 @@ func (s *Sensors) execute(c SensorCommand) { v.State = "complete" v.Result = result } - if s.write(c.ID+".json", v) != nil { + if s.writeOperation(v) != nil { v.State = "unknown" v.Error = "Не удалось сохранить результат операции. Обновите состояние устройства." } @@ -506,6 +517,9 @@ func (s *Sensors) Get(id string) *SensorOperation { s.mu.Lock() defer s.mu.Unlock() if v := s.operations[id]; v != nil { + if sensorSnapshot(v.Command.Action) && v.Result != nil && time.Now().Unix()-v.Updated >= 600 { + *v = expiredSensorSnapshot(*v) + } copy := *v return © } @@ -525,6 +539,7 @@ func (s *Sensors) RemoteResults() []any { } func (s *Sensors) Routes(mux *http.ServeMux, server *Server) { s.configurationRoutes(mux, server) + s.telemetryRoutes(mux, server) mux.HandleFunc("GET /api/devices/events", func(w http.ResponseWriter, r *http.Request) { s.stream(w, r, server) }) mux.HandleFunc("GET /api/devices", func(w http.ResponseWriter, r *http.Request) { if server.authorized(w, r) { @@ -567,7 +582,7 @@ func (s *Sensors) Acknowledge(ids []string) { for _, id := range ids { if v := s.operations[id]; v != nil && v.State != "running" { v.Remote = false - _ = s.write(id+".json", v) + _ = s.writeOperation(v) } } } diff --git a/apps/node-agent/internal/node/server.go b/apps/node-agent/internal/node/server.go index 27201eb2..2de93820 100644 --- a/apps/node-agent/internal/node/server.go +++ b/apps/node-agent/internal/node/server.go @@ -13,6 +13,7 @@ import ( ) type Server struct { + Budget *LinkBudget Monitor *Monitor Store *Store Pairing *Pairing @@ -82,6 +83,8 @@ func reply(w http.ResponseWriter, status int, v any) { func (s *Server) Handler() http.Handler { mux := http.NewServeMux() + s.routerRoutes(mux) + s.linkBudgetRoutes(mux) s.localPreviewRoutes(mux) s.monitorRoutes(mux) if s.Presentation != nil { @@ -95,6 +98,7 @@ func (s *Server) Handler() http.Handler { } if s.Pairing != nil { s.Pairing.localRoutes(mux, s) + s.Pairing.networkLocalRoutes(mux, s) } if s.Access != nil { s.accessRoutes(mux) diff --git a/apps/node-agent/internal/node/testdata/command-jitter-redacted.json b/apps/node-agent/internal/node/testdata/command-jitter-redacted.json new file mode 100644 index 00000000..53b64229 --- /dev/null +++ b/apps/node-agent/internal/node/testdata/command-jitter-redacted.json @@ -0,0 +1,1388 @@ +[ +[0.0,12.116,87.244], +[8.169,8.169,84.548], +[121.076,112.906,175.577], +[121.187,0.11,120.488], +[131.843,10.656,86.901], +[187.449,55.606,88.892], +[229.396,41.946,81.511], +[309.854,80.457,89.535], +[331.929,22.075,86.046], +[384.198,52.268,83.181], +[430.078,45.88,82.442], +[497.762,67.684,91.626], +[543.09,45.327,91.091], +[652.767,109.676,145.692], +[652.849,0.082,106.343], +[694.781,41.932,93.184], +[735.768,40.986,89.568], +[789.452,53.683,88.001], +[844.888,55.435,98.191], +[892.081,47.192,94.092], +[945.578,53.497,94.45], +[983.474,37.895,83.737], +[1044.441,60.967,93.212], +[1165.792,121.35,164.322], +[1165.872,0.079,108.473], +[1194.758,28.885,92.124], +[1252.136,57.378,94.045], +[1350.327,98.19,97.924], +[1438.174,87.847,116.071], +[1438.248,0.074,87.428], +[1481.862,43.613,75.816], +[1538.581,56.718,80.947], +[1591.926,53.345,81.492], +[1714.838,122.911,156.806], +[1714.916,0.078,103.796], +[1732.125,17.208,72.801], +[1792.519,60.394,80.425], +[1846.924,54.404,86.298], +[1904.761,57.837,88.783], +[1958.129,53.367,85.988], +[1958.206,0.077,84.755], +[2015.236,57.029,86.639], +[2055.589,40.352,82.395], +[2115.182,59.593,86.803], +[2232.359,117.176,157.901], +[2232.439,0.079,102.535], +[2406.884,174.445,211.857], +[2406.951,0.067,172.569], +[2406.995,0.044,116.971], +[2410.853,3.857,74.852], +[2493.136,82.282,104.911], +[2519.708,26.572,82.519], +[2584.932,65.224,85.937], +[2633.657,48.725,91.391], +[2754.364,120.707,157.459], +[2754.446,0.081,110.229], +[2789.323,34.877,89.758], +[2832.71,43.386,87.578], +[2886.256,53.545,85.921], +[2954.542,68.286,87.718], +[2983.815,29.273,76.066], +[3045.964,62.149,96.003], +[3058.589,12.624,90.542], +[3120.772,62.183,99.594], +[3177.071,56.298,107.991], +[3269.726,92.654,146.621], +[3269.799,0.073,99.868], +[3326.151,56.351,99.986], +[3364.377,38.226,86.07], +[3399.941,35.563,98.151], +[3441.501,41.559,86.606], +[3496.913,55.412,88.262], +[3514.642,17.729,86.68], +[3628.649,114.006,92.339], +[3677.646,48.997,89.403], +[3808.833,131.187,170.669], +[3808.913,0.079,117.866], +[3840.04,31.127,100.275], +[3882.961,42.92,91.053], +[3934.392,51.43,92.6], +[4011.222,76.83,86.262], +[4037.656,26.433,90.926], +[4081.843,44.187,80.158], +[4134.699,52.856,86.511], +[4320.63,185.93,217.278], +[4320.804,0.173,171.18], +[4321.159,0.354,105.437], +[4335.005,13.846,83.661], +[4389.041,54.035,85.699], +[4432.952,43.911,80.935], +[4489.558,56.605,82.44], +[4562.313,72.754,90.842], +[4562.374,0.061,90.667], +[4611.518,49.144,85.972], +[4679.449,67.93,87.439], +[4754.882,75.433,99.505], +[4863.905,109.022,172.927], +[4863.966,0.06,117.749], +[4987.744,123.777,197.034], +[4990.362,2.617,144.329], +[4990.421,0.058,110.292], +[5014.712,24.29,83.506], +[5047.147,32.435,97.859], +[5093.303,46.155,91.792], +[5139.351,46.048,89.535], +[5199.114,59.762,95.626], +[5236.727,37.613,82.384], +[5365.791,129.063,155.497], +[5365.881,0.09,116.6], +[5405.874,39.992,83.968], +[5442.697,36.823,90.676], +[5489.084,46.386,84.308], +[5533.908,44.824,83.359], +[5603.432,69.523,93.188], +[5633.415,29.983,77.865], +[5691.95,58.535,81.053], +[5737.904,45.953,79.853], +[5779.432,41.528,70.668], +[5883.922,104.489,125.972], +[5883.997,0.075,71.962], +[5931.386,47.389,74.334], +[5984.415,53.029,71.56], +[6049.088,64.672,74.211], +[6050.336,1.247,75.033], +[6114.622,64.286,78.993], +[6191.83,77.207,82.059], +[6230.183,38.353,76.345], +[6294.828,64.644,77.094], +[6407.045,112.217,151.594], +[6407.132,0.087,96.513], +[6425.766,18.633,68.221], +[6490.196,64.429,77.409], +[6547.581,57.385,93.156], +[6587.123,39.542,79.954], +[6643.413,56.289,86.399], +[6688.957,45.544,78.039], +[6764.218,75.26,107.164], +[6801.789,37.571,79.107], +[6982.419,180.63,211.305], +[6982.499,0.08,156.078], +[6986.879,4.379,132.997], +[7074.844,87.964,169.973], +[7074.921,0.077,118.647], +[7087.453,12.531,75.335], +[7138.76,51.307,82.955], +[7187.046,48.286,76.901], +[7238.429,51.383,79.071], +[7286.64,48.21,74.76], +[7487.095,200.454,230.951], +[7487.17,0.075,175.314], +[7487.203,0.033,132.711], +[7503.397,16.193,73.324], +[7531.759,28.361,71.625], +[7598.365,66.606,85.157], +[7660.057,61.692,93.149], +[7700.864,40.807,78.868], +[7732.163,31.298,78.668], +[7781.02,48.857,73.805], +[7859.035,78.015,104.999], +[7902.558,43.522,93.282], +[8001.594,99.036,148.623], +[8001.675,0.08,93.306], +[8127.643,125.968,170.422], +[8127.727,0.084,117.309], +[8311.331,183.603,238.608], +[8311.447,0.115,237.97], +[8311.487,0.039,181.24], +[8311.507,0.02,157.216], +[8323.993,12.486,106.75], +[8366.257,42.263,111.468], +[8398.983,32.726,89.084], +[8517.963,118.98,165.039], +[8519.739,1.775,111.51], +[8559.5,39.76,106.182], +[8608.02,48.519,98.741], +[8635.043,27.023,78.059], +[8699.441,64.397,88.953], +[8779.297,79.855,122.952], +[8787.083,7.786,76.721], +[8839.871,52.788,84.44], +[8896.355,56.483,75.88], +[8928.762,32.407,74.516], +[9032.273,103.511,126.992], +[9032.342,0.068,80.87], +[9090.943,58.601,84.12], +[9141.486,50.543,89.231], +[9178.789,37.302,71.229], +[9242.217,63.428,78.155], +[9296.674,54.457,79.876], +[9372.411,75.737,82.638], +[9395.693,23.281,82.825], +[9443.142,47.449,84.92], +[9556.142,112.999,146.174], +[9559.443,3.3,106.991], +[9602.282,42.838,83.093], +[9646.069,43.786,81.758], +[9699.85,53.781,80.391], +[9736.456,36.605,82.26], +[9789.918,53.462,80.62], +[9833.149,43.23,80.828], +[9889.816,56.667,82.216], +[9928.214,38.397,73.707], +[9981.573,53.359,71.897], +[10080.426,98.853,123.392], +[10090.409,9.983,80.649], +[10131.822,41.412,79.154], +[10188.722,56.9,78.489], +[10243.795,55.072,82.187], +[10314.837,71.042,76.96], +[10330.613,15.775,70.36], +[10392.327,61.714,81.908], +[10438.621,46.293,85.015], +[10489.965,51.344,81.206], +[10602.508,112.542,151.039], +[10602.58,0.072,95.689], +[10628.481,25.901,77.386], +[10672.043,43.561,67.269], +[10725.93,53.886,68.699], +[10779.811,53.881,69.801], +[10835.637,55.826,78.802], +[10880.71,45.072,72.731], +[10939.838,59.128,74.04], +[10939.899,0.06,72.433], +[11010.516,70.617,74.277], +[11128.622,118.105,161.93], +[11128.694,0.071,109.617], +[11128.725,0.031,75.896], +[11184.228,55.502,76.265], +[11229.546,45.318,72.737], +[11292.516,62.97,80.385], +[11350.699,58.182,93.144], +[11386.971,36.271,73.56], +[11462.905,75.933,103.356], +[11485.507,22.602,74.053], +[11531.393,45.885,74.886], +[11655.561,124.167,145.669], +[11655.639,0.078,100.211], +[11692.552,36.913,68.917], +[11741.484,48.931,73.381], +[11788.552,47.067,65.291], +[11835.151,46.598,80.93], +[11961.34,126.189,150.523], +[11961.425,0.084,105.194], +[11975.316,13.891,65.842], +[12058.228,82.912,101.449], +[12081.352,23.123,63.876], +[12170.003,88.65,106.657], +[12181.893,11.89,67.496], +[12254.608,72.715,88.743], +[12306.917,52.308,69.585], +[12343.879,36.962,69.829], +[12459.343,115.464,85.078], +[12460.37,1.026,83.934], +[12501.816,41.445,70.242], +[12537.258,35.442,73.176], +[12588.084,50.826,68.967], +[12710.688,122.603,136.596], +[12711.22,0.531,81.853], +[12735.904,24.684,73.683], +[12792.546,56.642,77.766], +[12840.579,48.032,75.894], +[12889.881,49.302,69.745], +[12945.119,55.237,82.185], +[12987.163,42.043,67.898], +[13053.38,66.216,78.448], +[13053.461,0.081,78.169], +[13113.782,60.321,80.494], +[13132.03,18.248,68.677], +[13223.609,91.578,105.261], +[13232.915,9.305,71.492], +[13256.262,23.347,66.65], +[13270.052,13.79,66.655], +[13375.229,105.176,116.561], +[13375.305,0.076,112.215], +[13409.95,34.644,91.813], +[13434.32,24.37,70.606], +[13491.67,57.35,75.437], +[13525.076,33.405,75.201], +[13529.893,4.817,73.028], +[13538.951,9.057,73.725], +[13594.24,55.288,75.539], +[13644.584,50.344,75.82], +[13761.183,116.598,141.001], +[13761.266,0.083,84.039], +[13813.325,52.059,80.492], +[13835.581,22.256,74.88], +[13887.77,52.188,71.999], +[14048.117,160.346,184.009], +[14048.193,0.076,129.749], +[14048.215,0.021,83.18], +[14096.038,47.823,75.234], +[14159.65,63.612,95.266], +[14321.537,161.886,201.134], +[14321.617,0.08,133.969], +[14321.669,0.051,131.407], +[14326.84,5.171,79.833], +[14351.803,24.962,80.432], +[14497.587,145.784,168.015], +[14497.652,0.064,135.383], +[14502.792,5.14,85.264], +[14541.934,39.142,82.032], +[14591.945,50.01,80.495], +[14599.237,7.291,79.293], +[14610.435,11.198,74.913], +[14685.918,75.482,120.87], +[14701.972,16.053,85.928], +[14804.398,102.426,141.179], +[14805.208,0.809,86.004], +[14878.422,73.214,115.659], +[14889.005,10.583,77.869], +[14909.544,20.538,74.864], +[14937.959,28.415,70.235], +[15002.76,64.8,75.149], +[15058.315,55.555,83.71], +[15118.291,59.975,71.335], +[15129.052,10.761,69.74], +[15184.503,55.45,70.162], +[15321.662,137.158,158.528], +[15326.916,5.254,109.952], +[15335.313,8.397,75.132], +[15396.708,61.394,81.403], +[15443.692,46.984,82.24], +[15499.855,56.162,87.288], +[15542.049,42.194,77.538], +[15594.282,52.233,78.39], +[15660.897,66.615,93.547], +[15660.962,0.065,93.211], +[15745.362,84.399,117.126], +[15749.58,4.218,90.778], +[15849.172,99.591,136.716], +[15849.25,0.078,87.936], +[15908.418,59.167,81.439], +[15939.493,31.075,76.681], +[16001.687,62.194,83.749], +[16029.367,27.679,70.814], +[16088.168,58.801,75.882], +[16169.068,80.899,108.646], +[16169.118,0.05,96.724], +[16171.235,2.116,82.494], +[16210.94,39.705,69.97], +[16241.148,30.208,77.568], +[16372.493,131.344,138.149], +[16372.576,0.083,105.163], +[16399.754,27.178,74.434], +[16430.218,30.464,68.879], +[16498.533,68.315,82.07], +[16527.932,29.398,67.529], +[16588.2,60.268,74.946], +[16661.515,73.315,99.555], +[16668.525,7.01,79.466], +[16696.834,28.308,81.305], +[16731.359,34.524,94.328], +[16745.917,14.558,82.331], +[16787.78,41.863,71.736], +[16889.638,101.857,128.173], +[16893.641,4.002,77.401], +[16931.929,38.288,71.445], +[16987.504,55.574,71.824], +[17050.268,62.763,89.001], +[17096.142,45.874,81.226], +[17152.205,56.063,92.192], +[17219.281,67.075,104.216], +[17251.108,31.826,88.034], +[17289.931,38.823,70.418], +[17413.492,123.56,153.857], +[17418.723,5.23,103.785], +[17425.03,6.306,65.05], +[17493.448,68.418,77.854], +[17537.804,44.356,81.616], +[17597.617,59.813,77.633], +[17631.429,33.811,65.116], +[17694.741,63.311,73.275], +[17740.822,46.081,83.026], +[17833.099,92.276,120.206], +[17833.179,0.08,74.941], +[17936.816,103.637,125.212], +[17936.977,0.16,80.054], +[17994.746,57.769,81.856], +[18033.446,38.7,73.817], +[18092.187,58.74,77.067], +[18126.465,34.278,69.285], +[18183.439,56.973,73.285], +[18230.485,47.045,68.843], +[18256.833,26.347,79.012], +[18312.274,55.441,66.055], +[18332.973,20.698,68.699], +[18473.295,140.322,141.799], +[18473.36,0.065,117.652], +[18491.843,18.482,80.969], +[18530.39,38.547,74.133], +[18579.66,49.269,72.846], +[18642.889,63.229,85.428], +[18683.591,40.701,72.566], +[18705.064,21.472,73.937], +[18780.916,75.852,137.69], +[18782.132,1.216,120.611], +[18786.56,4.427,74.102], +[18828.113,41.553,70.992], +[18882.084,53.97,69.712], +[18991.031,108.947,131.183], +[18992.972,1.941,76.606], +[19040.292,47.319,85.125], +[19152.711,112.418,122.738], +[19153.9,1.189,95.903], +[19185.737,31.836,72.626], +[19241.945,56.208,74.198], +[19298.004,56.058,74.817], +[19338.286,40.282,80.32], +[19391.582,53.296,79.14], +[19520.353,128.77,164.16], +[19520.459,0.106,108.76], +[19537.19,16.73,80.03], +[19649.419,112.229,135.654], +[19649.514,0.095,91.102], +[19789.199,139.684,175.857], +[19789.271,0.072,131.719], +[19799.296,10.025,87.018], +[19850.688,51.391,93.762], +[19894.498,43.81,85.531], +[19940.955,46.456,83.978], +[20057.96,117.004,146.071], +[20058.03,0.07,103.281], +[20115.425,57.395,104.836], +[20145.793,30.367,89.938], +[20232.46,86.666,121.011], +[20257.754,25.294,93.458], +[20303.081,45.326,123.44], +[20349.108,46.027,97.746], +[20367.781,18.672,97.929], +[20420.859,53.077,84.174], +[20440.955,20.096,86.961], +[20580.749,139.794,175.011], +[20580.821,0.071,125.818], +[20598.932,18.11,88.702], +[20644.52,45.588,90.119], +[20713.33,68.81,80.707], +[20742.073,28.742,86.065], +[20862.375,120.301,151.079], +[20862.467,0.092,108.541], +[20881.136,18.669,74.579], +[20945.868,64.731,75.262], +[20953.67,7.801,78.781], +[21093.308,139.637,157.086], +[21093.369,0.061,129.605], +[21117.013,23.643,97.454], +[21250.281,133.267,197.235], +[21250.345,0.063,141.896], +[21258.491,8.146,104.859], +[21335.185,76.693,130.605], +[21428.153,92.968,174.846], +[21428.222,0.068,119.257], +[21485.681,57.459,128.531], +[21496.353,10.672,87.919], +[21612.995,116.641,159.347], +[21613.086,0.09,104.055], +[21660.674,47.587,106.451], +[21797.143,136.469,127.058], +[21797.217,0.073,126.375], +[21816.53,19.312,76.935], +[21839.467,22.937,86.896], +[21887.565,48.098,83.841], +[21935.659,48.094,80.552], +[21982.993,47.334,72.806], +[22025.776,42.782,72.995], +[22134.145,108.369,129.15], +[22134.207,0.061,80.609], +[22159.839,25.631,82.346], +[22173.463,13.623,89.464], +[22214.722,41.259,79.562], +[22239.459,24.737,81.455], +[22304.167,64.708,71.549], +[22369.856,65.688,77.021], +[22380.204,10.347,83.951], +[22438.714,58.51,79.453], +[22438.795,0.081,77.655], +[22469.815,31.019,78.791], +[22505.906,36.09,81.247], +[22536.559,30.653,81.708], +[22667.185,130.625,157.27], +[22667.247,0.062,111.059], +[22684.008,16.761,72.506], +[22740.44,56.431,83.61], +[22780.591,40.15,72.699], +[22824.854,44.263,71.521], +[22884.782,59.927,74.14], +[22939.304,54.522,85.26], +[23011.609,72.305,101.146], +[23034.911,23.301,71.161], +[23034.995,0.083,70.751], +[23180.219,145.224,150.368], +[23180.291,0.071,119.183], +[23186.136,5.845,71.79], +[23241.612,55.475,85.501], +[23337.835,96.223,129.049], +[23338.025,0.189,82.49], +[23386.843,48.818,78.032], +[23432.565,45.722,76.544], +[23489.987,57.421,80.72], +[23529.032,39.045,73.4], +[23589.012,59.979,77.853], +[23712.825,123.813,157.14], +[23712.924,0.098,101.618], +[23783.358,70.434,126.739], +[23805.513,22.154,84.802], +[23847.625,42.112,79.315], +[23904.833,57.208,83.189], +[23982.071,77.237,80.804], +[23985.676,3.604,81.374], +[24024.285,38.609,70.383], +[24087.697,63.411,78.663], +[24128.878,41.181,74.182], +[24237.5,108.622,127.525], +[24354.787,117.287,153.976], +[24354.951,0.164,118.281], +[24355.152,0.2,115.572], +[24371.451,16.298,126.222], +[24371.526,0.074,114.269], +[24390.809,19.282,71.334], +[24436.667,45.858,73.828], +[24490.566,53.898,74.548], +[24524.049,33.483,70.272], +[24584.785,60.736,81.588], +[24584.844,0.058,70.058], +[24622.157,37.313,67.909], +[24781.297,159.139,171.827], +[24781.354,0.057,127.293], +[24798.957,17.602,91.814], +[24837.944,38.987,83.615], +[24881.761,43.816,71.938], +[24920.945,39.184,66.201], +[24978.041,57.095,69.702], +[25024.709,46.667,61.46], +[25083.044,58.335,63.257], +[25121.069,38.025,63.145], +[25178.321,57.251,65.232], +[25279.827,101.506,122.491], +[25279.917,0.089,68.516], +[25388.858,108.941,131.025], +[25389.118,0.259,75.974], +[25421.333,32.215,61.935], +[25546.596,125.262,135.413], +[25570.632,24.036,77.442], +[25593.164,22.531,84.916], +[25655.294,62.13,97.449], +[25696.299,41.004,72.339], +[25804.136,107.837,144.562], +[25804.234,0.097,143.488], +[25804.317,0.083,88.229], +[25804.348,0.03,72.399], +[25832.88,28.532,76.375], +[25890.216,57.335,79.17], +[25970.12,79.903,112.135], +[25977.313,7.193,66.136], +[26026.395,49.082,68.454], +[26082.292,55.897,71.25], +[26135.802,53.509,72.087], +[26195.525,59.723,70.347], +[26369.526,174.001,211.059], +[26369.621,0.094,146.75], +[26369.668,0.046,113.225], +[26395.854,26.186,125.366], +[26401.918,6.063,114.148], +[26413.047,11.129,68.163], +[26439.319,26.272,76.642], +[26489.753,50.433,68.495], +[26529.12,39.367,71.989], +[26583.553,54.432,72.538], +[26596.202,12.649,64.446], +[26672.715,76.512,106.366], +[26685.465,12.75,63.766], +[26759.258,73.792,101.519], +[26848.902,89.643,139.808], +[26879.516,30.613,122.215], +[26879.702,0.186,68.034], +[26923.303,43.601,66.025], +[27015.123,91.819,105.46], +[27034.512,19.389,64.524], +[27037.791,3.279,66.046], +[27097.522,59.731,70.697], +[27125.062,27.539,68.034], +[27252.782,127.72,122.158], +[27256.539,3.756,100.597], +[27282.966,26.426,72.882], +[27380.497,97.531,124.188], +[27380.595,0.097,81.618], +[27412.459,31.864,97.171], +[27434.637,22.178,77.265], +[27482.166,47.528,69.409], +[27523.347,41.181,65.871], +[27579.518,56.171,68.631], +[27627.078,47.559,70.966], +[27647.013,19.934,89.369], +[27650.45,3.437,71.867], +[27711.898,61.447,74.542], +[27762.097,50.199,105.414], +[27780.922,18.824,73.501], +[27905.688,124.766,150.39], +[27905.795,0.106,96.142], +[27923.183,17.388,66.687], +[27982.249,59.065,71.686], +[28030.811,48.562,73.875], +[28077.93,47.118,68.804], +[28134.838,56.908,72.18], +[28186.277,51.438,72.886], +[28229.593,43.316,73.163], +[28297.042,67.449,66.418], +[28329.7,32.658,66.863], +[28418.059,88.358,110.39], +[28420.661,2.602,96.65], +[28422.808,2.147,67.687], +[28473.595,50.786,64.538], +[28519.275,45.679,57.058], +[28571.35,52.075,57.762], +[28620.567,49.216,55.317], +[28663.908,43.34,97.256], +[28664.016,0.107,89.188], +[28684.457,20.441,55.436], +[28721.199,36.742,55.689], +[28796.389,75.189,64.927], +[28948.183,151.794,183.432], +[28948.439,0.256,128.454], +[28948.524,0.084,84.058], +[28988.065,39.541,57.52], +[29070.563,82.497,93.67], +[29101.673,31.11,71.56], +[29128.916,27.242,64.748], +[29182.59,53.674,63.278], +[29222.513,39.922,56.306], +[29281.634,59.12,63.949], +[29332.577,50.942,66.896], +[29376.165,43.588,58.838], +[29467.269,91.103,102.574], +[29473.264,5.995,56.625], +[29522.397,49.132,57.504], +[29579.655,57.258,62.488], +[29627.905,48.249,55.275], +[29629.336,1.43,54.669], +[29714.939,85.603,60.532], +[29725.651,10.712,56.335], +[29781.017,55.365,56.132], +[29825.314,44.297,62.388], +[29873.751,48.436,56.645], +[29990.186,116.434,126.272], +[29990.269,0.083,72.672], +[30023.68,33.41,59.002], +[30075.298,51.618,55.637], +[30119.107,43.808,56.232], +[30175.57,56.463,58.439], +[30225.095,49.525,60.002], +[30307.403,82.307,87.754], +[30356.945,49.541,83.911], +[30429.85,72.905,81.582], +[30520.288,90.438,149.766], +[30520.367,0.078,79.324], +[30521.939,1.572,59.404], +[30589.93,67.99,72.375], +[30656.559,66.628,86.675], +[30691.651,35.092,69.802], +[30724.128,32.476,60.529], +[30773.74,49.612,58.761], +[30823.987,50.246,59.784], +[30892.481,68.494,72.536], +[30932.503,40.021,67.084], +[31043.105,110.601,124.733], +[31043.177,0.072,77.704], +[31092.393,49.215,58.542], +[31138.154,45.761,57.45], +[31199.647,61.492,65.036], +[31236.481,36.834,63.743], +[31285.352,48.87,57.435], +[31321.476,36.123,57.891], +[31375.995,54.518,57.125], +[31422.417,46.422,57.57], +[31476.353,53.935,59.754], +[31633.317,156.964,168.575], +[31644.255,10.937,125.477], +[31644.317,0.062,80.506], +[31695.642,51.324,76.252], +[31725.846,30.203,57.345], +[31787.444,61.597,60.323], +[31827.659,40.215,64.812], +[31875.214,47.555,55.166], +[31932.265,57.051,64.123], +[31996.957,64.691,57.35], +[32094.038,97.08,116.843], +[32094.118,0.08,62.634], +[32120.408,26.29,53.807], +[32185.008,64.599,63.171], +[32228.57,43.562,62.77], +[32302.957,74.386,74.026], +[32333.949,30.992,69.698], +[32388.745,54.795,66.161], +[32437.645,48.9,70.594], +[32489.502,51.856,68.797], +[32530.86,41.358,66.341], +[32622.943,92.082,103.333], +[32638.816,15.873,71.771], +[32701.852,63.035,80.274], +[32752.075,50.223,86.312], +[32781.477,29.401,61.695], +[32830.956,49.478,65.877], +[32880.923,49.967,63.479], +[32939.492,58.569,74.887], +[33015.087,75.595,80.715], +[33032.094,17.006,65.368], +[33145.708,113.614,108.637], +[33145.804,0.095,81.915], +[33177.501,31.697,58.488], +[33233.085,55.583,62.732], +[33246.829,13.743,68.847], +[33300.195,53.366,66.818], +[33332.101,31.905,68.206], +[33474.044,141.942,156.124], +[33474.12,0.075,107.613], +[33501.773,27.653,79.999], +[33525.743,23.97,61.073], +[33585.523,59.78,68.935], +[33672.673,87.15,99.439], +[33672.781,0.107,99.155], +[33695.45,22.668,63.545], +[33727.974,32.524,64.663], +[33777.304,49.329,58.519], +[33831.764,54.46,68.936], +[33874.806,43.042,58.025], +[33924.405,49.598,61.102], +[33979.509,55.104,61.211], +[34020.551,41.042,56.529], +[34083.798,63.246,66.911], +[34184.062,100.264,120.261], +[34185.21,1.147,66.582], +[34185.276,0.066,62.97], +[34212.305,27.029,56.267], +[34222.663,10.357,58.046], +[34301.077,78.413,66.218], +[34350.246,49.169,76.882], +[34407.946,57.699,73.448], +[34439.085,31.139,76.113], +[34525.617,86.531,109.615], +[34591.519,65.901,129.532], +[34591.583,0.064,112.958], +[34591.615,0.031,86.162], +[34619.456,27.841,58.462], +[34621.966,2.509,58.39], +[34718.632,96.666,102.222], +[34734.323,15.69,65.487], +[34864.043,129.719,141.723], +[34865.951,1.907,103.163], +[34883.441,17.489,65.924], +[35059.415,175.974,196.795], +[35104.609,45.193,182.646], +[35104.751,0.142,135.69], +[35240.0,135.249,216.334], +[35240.068,0.068,178.4], +[35287.233,47.164,170.462], +[35291.815,4.582,171.227], +[35291.9,0.085,93.441], +[35322.298,30.397,123.326], +[35322.385,0.087,67.777], +[35322.421,0.035,61.311], +[35378.391,55.969,62.172], +[35427.102,48.711,66.515], +[35479.015,51.912,63.195], +[35520.139,41.124,58.017], +[35586.745,66.606,69.118], +[35645.565,58.82,84.025], +[35766.611,121.045,146.501], +[35766.719,0.108,106.418], +[35766.948,0.229,63.7], +[35770.363,3.414,59.694], +[35831.465,61.101,69.652], +[35893.233,61.768,78.369], +[35951.495,58.262,90.001], +[35961.058,9.562,67.205], +[36012.867,51.808,63.362], +[36025.432,12.565,63.006], +[36087.861,62.428,71.371], +[36131.353,43.492,68.693], +[36182.546,51.192,68.901], +[36325.46,142.914,152.786], +[36325.552,0.091,152.503], +[36325.598,0.046,83.046], +[36336.21,10.611,63.879], +[36385.242,49.032,57.716], +[36434.605,49.362,73.95], +[36464.563,29.958,63.884], +[36525.769,61.206,69.987], +[36525.852,0.082,65.83], +[36535.853,10.001,61.141], +[36591.03,55.176,65.302], +[36616.509,25.479,55.428], +[36654.501,37.992,58.62], +[36710.982,56.48,68.28], +[36816.358,105.376,151.723], +[36816.451,0.093,97.935], +[36816.491,0.039,90.277], +[36825.25,8.759,61.443], +[36897.326,72.075,66.189], +[36899.308,1.981,65.385], +[36995.959,96.651,131.18], +[36996.03,0.071,87.328], +[37019.231,23.2,58.381], +[37039.786,20.555,61.845], +[37106.048,66.261,73.008], +[37154.333,48.285,94.143], +[37154.408,0.074,92.691], +[37174.219,19.811,57.237], +[37214.389,40.17,60.977], +[37222.847,8.457,58.946], +[37240.532,17.685,69.317], +[37344.068,103.535,117.678], +[37344.165,0.097,83.281], +[37358.289,14.123,70.639], +[37403.232,44.943,62.613], +[37403.313,0.08,61.144], +[37420.915,17.601,59.34], +[37478.251,57.335,61.366], +[37537.633,59.382,62.9], +[37672.667,135.033,140.403], +[37672.813,0.146,72.56], +[37672.863,0.049,69.184], +[37730.617,57.754,71.201], +[37734.747,4.129,73.623], +[37884.469,149.722,170.802], +[37884.593,0.124,124.25], +[37884.853,0.26,69.066], +[37912.378,27.525,73.521], +[37941.468,29.089,81.303], +[37978.745,37.276,63.068], +[37989.495,10.749,66.896], +[38022.786,33.291,62.089], +[38067.606,44.819,61.887], +[38140.192,72.586,79.782], +[38232.195,92.002,143.906], +[38232.266,0.071,90.31], +[38242.378,10.111,68.838], +[38245.628,3.25,71.777], +[38434.795,189.166,182.643], +[38437.428,2.632,146.656], +[38442.487,5.058,136.756], +[38442.704,0.217,101.818], +[38447.989,5.285,88.953], +[38578.684,130.694,156.518], +[38605.531,26.847,145.33], +[38625.69,20.159,165.013], +[38712.967,87.276,208.091], +[38713.044,0.077,204.576], +[38736.67,23.625,177.211], +[38736.762,0.092,159.79], +[38736.796,0.033,104.728], +[38737.559,0.763,76.467], +[38787.055,49.495,74.195], +[38908.123,121.068,148.535], +[38908.195,0.071,96.077], +[38933.922,25.727,72.074], +[38997.052,63.129,79.437], +[39026.159,29.106,62.965], +[39084.233,58.074,65.905], +[39136.9,52.667,77.347], +[39150.071,13.17,72.462], +[39193.612,43.54,60.954], +[39233.402,39.79,74.443], +[39233.502,0.099,65.574], +[39289.33,55.827,68.226], +[39319.201,29.871,75.734], +[39341.211,22.009,81.565], +[39445.013,103.801,129.884], +[39445.094,0.081,113.887], +[39445.126,0.032,85.82], +[39483.355,38.229,72.072], +[39594.187,110.831,134.191], +[39606.407,12.22,108.862], +[39609.805,3.398,59.272], +[39669.342,59.536,88.639], +[39669.41,0.067,88.414], +[39747.303,77.893,103.246], +[39747.367,0.063,89.292], +[39747.411,0.044,83.547], +[39793.03,45.619,74.073], +[39816.707,23.676,71.811], +[39822.293,5.585,64.907], +[39963.331,141.038,150.682], +[39963.424,0.093,134.002], +[39963.618,0.193,105.503], +[40052.707,89.088,142.501], +[40052.791,0.083,140.316], +[40052.833,0.042,93.794], +[40066.794,13.96,68.392], +[40149.131,82.336,67.298], +[40175.496,26.364,73.31], +[40175.579,0.083,70.425], +[40242.536,66.957,80.28], +[40242.633,0.096,79.445], +[40369.513,126.879,120.841], +[40369.628,0.115,115.697], +[40369.673,0.045,100.019], +[40559.277,189.603,238.089], +[40559.365,0.087,229.717], +[40559.406,0.04,201.85], +[40559.434,0.028,150.243], +[40567.03,7.595,153.925], +[40588.028,20.998,130.532], +[40591.9,3.871,94.339], +[40628.524,36.624,76.133], +[40663.133,34.608,105.273], +[40663.221,0.087,82.893], +[40697.999,34.777,64.903], +[40722.075,24.075,63.717], +[40727.39,5.315,62.718], +[40783.247,55.857,63.489], +[40810.712,27.465,64.234], +[40817.368,6.655,60.066], +[40884.692,67.324,75.329], +[40911.366,26.673,61.784], +[41058.384,147.017,194.62], +[41060.445,2.061,139.258], +[41060.513,0.067,138.572], +[41060.542,0.028,103.074], +[41065.882,5.339,64.282], +[41118.292,52.41,64.787], +[41121.622,3.33,62.37], +[41185.981,64.358,71.455], +[41239.154,53.173,80.392], +[41315.487,76.333,100.354], +[41325.705,10.217,68.134], +[41379.321,53.616,68.789], +[41430.051,50.729,71.877], +[41534.247,104.195,123.004], +[41534.312,0.065,77.157], +[41567.685,33.373,71.011], +[41639.716,72.031,75.981], +[41639.858,0.141,75.387], +[41658.011,18.153,79.09], +[41706.148,48.136,72.945], +[41815.506,109.358,157.599], +[41815.595,0.088,101.677], +[41815.636,0.04,99.067], +[41815.686,0.049,65.673], +[41842.431,26.745,77.425], +[41890.754,48.322,70.795], +[41898.393,7.639,70.317], +[41942.701,44.308,86.913], +[42091.646,148.944,180.405], +[42091.713,0.066,179.196], +[42091.778,0.065,134.671], +[42117.308,25.53,115.284], +[42121.926,4.617,64.162], +[42138.991,17.065,79.232], +[42143.596,4.605,65.144], +[42217.154,73.557,75.258], +[42234.982,17.828,65.116], +[42235.086,0.103,62.901], +[42302.383,67.296,62.8], +[42337.077,34.694,63.927], +[42337.128,0.05,63.537], +[42397.25,60.122,60.666], +[42426.363,29.112,61.864], +[42473.644,47.28,55.518], +[42477.26,3.616,57.621], +[42622.891,145.63,187.179], +[42622.977,0.086,158.916], +[42623.031,0.053,103.648], +[42650.049,27.018,84.953], +[42680.331,30.281,61.862], +[42756.97,76.639,91.088], +[42849.532,92.561,128.15], +[42849.629,0.096,85.211], +[42883.151,33.522,65.334], +[42925.201,42.05,57.259], +[42978.581,53.379,59.565], +[42992.515,13.934,56.642], +[43102.445,109.93,138.474], +[43102.532,0.086,84.97], +[43102.584,0.052,84.743], +[43126.36,23.775,62.632], +[43158.01,31.65,55.965], +[43216.457,58.447,59.312], +[43221.375,4.918,56.316], +[43240.615,19.239,54.688], +[43315.149,74.534,74.012], +[43329.053,13.903,65.828], +[43333.172,4.118,64.274], +[43402.937,69.765,78.912], +[43419.623,16.686,57.918], +[43426.136,6.512,63.081], +[43485.629,59.492,71.659], +[43506.182,20.553,70.102], +[43530.338,24.155,61.137], +[43632.783,102.445,106.868], +[43632.864,0.08,105.223], +[43634.31,1.446,65.677], +[43685.085,50.774,80.539], +[43762.066,76.981,106.562], +[43762.141,0.075,98.716], +[43762.238,0.096,74.107], +[43818.767,56.529,78.065], +[43831.514,12.746,67.757], +[43895.003,63.488,75.61], +[43932.918,37.915,69.972], +[43984.747,51.829,67.572], +[44039.457,54.71,74.864], +[44044.522,5.064,75.408], +[44167.112,122.589,146.929], +[44169.308,2.196,106.107], +[44299.835,130.526,184.773], +[44299.922,0.086,128.513], +[44299.964,0.042,126.843], +[44309.075,9.111,74.166], +[44348.43,39.355,74.542], +[44389.48,41.049,61.111], +[44427.162,37.681,64.579], +[44482.211,55.049,66.021], +[44527.265,45.053,63.921], +[44531.044,3.779,62.017], +[44594.501,63.456,70.78], +[44676.23,81.729,128.483], +[44676.314,0.083,112.604], +[44679.531,3.216,62.568], +[44696.982,17.451,62.702], +[44730.814,33.831,65.296], +[44786.006,55.191,71.745], +[44828.259,42.252,65.704], +[44875.741,47.481,73.282], +[44915.735,39.994,61.709], +[44931.476,15.741,61.929], +[44958.553,27.076,74.376], +[45033.523,74.97,64.092], +[45033.62,0.096,61.188], +[45033.692,0.072,60.93], +[45094.64,60.947,66.559], +[45110.978,16.338,61.974], +[45201.567,90.588,140.606], +[45201.669,0.101,85.52], +[45201.707,0.037,68.132], +[45227.935,26.228,64.772], +[45280.874,52.939,63.046], +[45280.944,0.07,61.656], +[45323.904,42.959,61.315], +[45359.554,35.649,59.709], +[45471.243,111.689,119.413], +[45471.326,0.083,110.086], +[45471.367,0.041,87.624], +[45517.368,46,79.244], +[45520.545,3.177,58.947], +[45526.719,6.174,59.142], +[45596.005,69.285,57.415], +[45625.156,29.151,71.996], +[45637.359,12.203,67.997], +[45723.046,85.686,98.508], +[45723.109,0.062,89.553], +[45723.145,0.036,62.195], +[45789.627,66.481,74.305], +[45793.997,4.369,77.958], +[45821.617,27.62,60.648], +[45865.909,44.292,66.153], +[45915.899,49.989,60.693], +[45926.124,10.224,64.816], +[45950.027,23.902,65.368], +[46009.273,59.246,69.893], +[46081.915,72.642,114.226], +[46088.979,7.064,94.317], +[46110.982,22.002,64.778], +[46136.306,25.324,86.794], +[46136.394,0.087,72.26], +[46250.613,114.219,130.975], +[46250.753,0.139,117.519], +[46250.799,0.046,89.422], +[46305.896,55.096,67.135], +[46307.553,1.657,66.955], +[46351.938,44.384,80.867], +[46359.432,7.494,58.621], +[46465.802,106.37,84.452], +[46465.853,0.05,83.644], +[46465.884,0.03,82.951], +[46495.562,29.677,57.514], +[46527.158,31.596,65.689], +[46538.973,11.814,72.616], +[46589.991,51.018,57.838], +[46638.476,48.485,69.878], +[46638.554,0.077,69.749], +[46778.069,139.515,155.818], +[46778.158,0.088,146.348], +[46778.227,0.068,119.013], +[46782.662,4.435,68.782], +[46782.748,0.086,67.255], +[46832.529,49.78,72.153], +[46870.595,38.066,69.611], +[46917.312,46.717,62.027], +[46928.776,11.463,67.762], +[46959.225,30.449,73.798], +[47014.819,55.593,56.023], +[47030.526,15.707,56.697], +[47031.916,1.39,57.807], +[47099.43,67.513,56.132], +[47107.915,8.485,57.033], +[47118.561,10.645,57.359], +[47196.512,77.95,78.527], +[47212.921,16.409,77.328], +[47314.045,101.123,149.982], +[47314.121,0.076,95.475], +[47329.82,15.698,61.877], +[47359.115,29.294,55.997], +[47419.336,60.221,61.154], +[47423.255,3.919,59.76], +[47445.446,22.19,56.167], +[47500.606,55.16,58.531], +[47519.288,18.681,56.29], +[47532.948,13.659,63.425], +[47586.269,53.321,61.838], +[47610.982,24.713,58.206], +[47623.498,12.515,58.162], +[47697.426,73.928,71.764], +[47705.886,8.46,65.799], +[47728.486,22.6,59.469], +[47820.778,92.292,103.011], +[47824.463,3.684,61.838], +[47863.794,39.331,60.917], +[47917.283,53.488,59.121], +[47921.71,4.426,58.81], +[47943.877,22.167,58.17], +[47999.08,55.202,58.702], +[48028.918,29.838,60.737], +[48032.062,3.144,59.512], +[48137.378,105.315,109.526], +[48137.452,0.073,85.449], +[48137.49,0.038,74.938], +[48176.85,39.359,60.426], +[48253.667,76.817,80.888], +[48254.644,0.976,59.008], +[48358.487,103.843,162.338], +[48358.558,0.07,106.297], +[48360.429,1.871,107.583], +[48402.13,41.701,133.853], +[48402.232,0.101,89.015], +[48439.093,36.861,66.03], +[48448.777,9.684,60.497], +[48513.48,64.703,69.911], +[48529.019,15.538,66.521], +[48534.185,5.165,66.516], +[48585.273,51.088,65.716], +[48609.178,23.905,58.063], +[48623.349,14.171,61.191], +[48695.623,72.273,80.101], +[48701.149,5.526,66.677], +[48724.879,23.729,63.478], +[48781.511,56.631,67.009], +[48784.45,2.938,65.235], +[48874.838,90.387,112.198], +[48874.913,0.075,70.017], +[48922.608,47.695,63.662], +[48927.203,4.595,64.143], +[48944.851,17.647,59.419], +[48996.37,51.519,59.518], +[49033.853,37.482,60.93], +[49033.938,0.084,60.752], +[49100.227,66.288,58.591], +[49112.692,12.465,59.529], +[49121.327,8.634,60.284], +[49174.146,52.818,56.527], +[49194.159,20.013,56.328], +[49222.096,27.936,58.547], +[49272.817,50.721,56.278], +[49278.237,5.42,57.717], +[49393.185,114.948,126.533], +[49393.271,0.086,89.06], +[49419.966,26.694,62.729], +[49425.237,5.27,61.987], +[49446.678,21.44,58.045], +[49499.126,52.448,57.733], +[49520.387,21.26,57.33], +[49529.469,9.081,57.903], +[49581.658,52.189,58.856], +[49613.059,31.401,57.561], +[49622.329,9.269,58.62], +[49744.847,122.518,116.666], +[49744.929,0.081,100.755], +[49744.972,0.043,70.482], +[49793.935,48.962,72.685], +[49818.822,24.886,56.361], +[49922.993,104.171,90.197], +[49924.131,1.137,88.419], +[49925.901,1.769,63.575], +[49978.798,52.896,61.383], +[50024.677,45.878,62.363], +[50079.67,54.993,64.032], +[50127.014,47.343,64.333], +[50179.568,52.553,63.643], +[50226.803,47.235,62.519], +[50282.332,55.528,60.257], +[50285.678,3.346,61.542], +[50328.356,42.677,61.713], +[50450.833,122.476,119.162], +[50450.923,0.09,89.169], +[50485.479,34.556,73.32], +[50575.497,90.017,114.225], +[50575.591,0.093,104.671], +[50599.574,23.983,73.47], +[50656.737,57.162,95.026], +[50679.911,23.174,63.025], +[50735.631,55.72,72.83], +[50839.1,103.469,120.183], +[50839.196,0.095,77.078], +[50978.387,139.19,162.93], +[50978.468,0.081,124.103], +[50978.52,0.051,117.449], +[51005.959,27.439,93.68], +[51017.436,11.477,63.387], +[51034.874,17.437,65.82], +[51102.4,67.526,74.361], +[51125.851,23.451,63.906], +[51277.96,152.108,160.938], +[51278.022,0.062,116.73], +[51293.744,15.722,79.454], +[51341.181,47.436,76.426], +[51389.992,48.811,70.647], +[51539.011,149.018,184.978], +[51543.445,4.434,182.118], +[51543.603,0.157,117.73], +[51631.795,88.192,171.647], +[51637.159,5.363,121.837], +[51639.294,2.135,79.359], +[51659.756,20.461,67.312], +[51716.129,56.373,68.031], +[51763.453,47.323,103.842], +[51786.251,22.798,72.23], +[51828.34,42.088,68.225], +[51884.158,55.817,70.247], +[51933.104,48.946,72.272], +[52021.457,88.353,106.922], +[52032.362,10.904,69.256], +[52088.718,56.356,69.318], +[52127.31,38.591,66.611], +[52164.057,36.747,67.348], +[52222.898,58.841,74.7], +[52237.557,14.659,76.302], +[52294.433,56.875,72.122], +[52383.199,88.766,110.71], +[52383.275,0.076,81.363], +[52407.841,24.565,67.341], +[52432.93,25.088,72.978], +[52544.552,111.622,133.833], +[52544.617,0.065,120.066], +[52544.647,0.03,85.15], +[52594.855,50.207,87.394], +[52629.162,34.307,68.847], +[52686.333,57.17,82.921], +[52736.606,50.272,82.481], +[52736.665,0.059,75.586], +[52743.218,6.553,64.494], +[52804.296,61.077,72.928], +[52831.746,27.45,71.072], +[52863.268,31.521,63.485], +[52983.937,120.668,140.969], +[52984.017,0.08,124.384], +[53063.88,79.862,148.811], +[53063.962,0.082,133.676], +[53065.898,1.936,104.392], +[53094.067,28.168,70.02], +[53111.365,17.297,64.385], +[53119.743,8.378,59.703], +[53165.507,45.763,73.741], +[53219.66,54.153,72.781], +[53222.475,2.815,64.217], +[53246.566,24.09,71.612], +[53321.654,75.088,91.59], +[53325.378,3.723,61.263], +[53325.438,0.06,60.889], +[53393.649,68.211,73.698], +[53410.824,17.174,68.952], +[53422.33,11.506,63.088], +[53472.456,50.125,60.512], +[53486.601,14.145,61.354], +[53592.892,106.291,133.902], +[53592.982,0.09,82.852], +[53650.92,57.937,71.644], +[53651.615,0.695,71.932], +[53673.542,21.926,64.34], +[53777.464,103.922,119.334], +[53777.538,0.073,101.897], +[53793.345,15.807,62.753], +[53827.57,34.224,69.495], +[53836.468,8.898,74.553], +[53888.837,52.368,66.156], +[53894.342,5.505,64.822], +[53903.809,9.467,60.184], +[53924.275,20.466,60.835], +[53988.765,64.49,68.968], +[54051.147,62.381,87.166], +[54182.906,131.759,163.882], +[54286.31,103.403,222.093], +[54286.405,0.094,168.999], +[54319.944,33.539,151.083], +[54320.031,0.087,92.184], +[54368.197,48.165,84.042], +[54377.691,9.493,77.998], +[54410.256,32.564,72.006], +[54448.68,38.424,75.726], +[54484.554,35.873,56.469], +[54517.833,33.279,55.517], +[54638.968,121.134,121.452], +[54652.85,13.881,123.844], +[54652.93,0.08,89.349], +[54700.087,47.156,72.236], +[54731.478,31.391,66.498], +[54791.196,59.717,74.902], +[54818.953,27.757,56.141], +[54883.487,64.533,66.902], +[54931.395,47.907,67.897], +[55002.424,71.029,60.114], +[55066.433,64.008,93.367], +[55169.356,102.923,152.603], +[55169.412,0.055,107.225], +[55228.532,59.119,114.122], +[55234.042,5.51,70.782], +[55242.223,8.18,68.742], +[55307.77,65.546,78.978], +[55391.447,83.677,129.149], +[55391.754,0.307,78.351], +[55432.873,41.118,69.071], +[55510.366,77.492,93.74], +[55532.053,21.687,68.679], +[55586.164,54.11,70.501], +[55686.788,100.624,124.306], +[55687.848,1.059,73.74], +[55757.451,69.603,81.309], +[55757.515,0.064,80.937], +[55757.56,0.044,80.763], +[55800.85,43.289,57.848], +[55829.676,28.826,67.275], +[55834.484,4.807,71.595], +[55877.551,43.067,78.051], +[55914.399,36.848,64.062], +[55920.974,6.574,59.242], +[55957.774,36.8,63.73], +[56012.819,55.045,63.422], +[56023.482,10.662,61.007], +[56082.599,59.116,67.518], +[56207.463,124.863,142.433], +[56207.539,0.075,90.766], +[56223.091,15.551,59.455], +[56299.504,76.413,60.192], +[56372.388,72.884,73.102], +[56372.497,0.108,72.13], +[56423.799,51.302,71.705], +[56432.475,8.676,65.184], +[56461.639,29.163,64.305], +[56524.344,62.704,72.134], +[56528.806,4.462,68.171], +[56543.9,15.093,65.959], +[56599.42,55.52,66.356], +[56627.468,28.047,66.257], +[56766.587,139.118,159.866], +[56766.676,0.089,121.731], +[56766.747,0.07,105.261], +[56801.777,35.029,86.281], +[56804.839,3.061,77.04], +[56835.013,30.174,80.551], +[56835.101,0.088,73.679], +[56876.575,41.473,62.365], +[56943.417,66.842,81.736], +[57019.416,75.998,103.965], +[57029.786,10.369,60.846], +[57031.691,1.905,62.21], +[57118.313,86.621,90.345], +[57132.051,13.737,71.248], +[57258.287,126.236,142.353], +[57258.358,0.071,97.216], +[57279.54,21.181,63.243], +[57317.515,37.974,64.854], +[57325.055,7.54,64.351], +[57377.18,52.125,60.998], +[57402.75,25.57,64.749], +[57426.232,23.481,59.15], +[57508.287,82.054,89.499], +[57632.48,124.193,171.625], +[57632.565,0.085,129.82], +[57632.608,0.042,122.332], +[57667.722,35.113,105.915], +[57682.663,14.941,61.32], +[57798.156,115.492,132.364], +[57798.239,0.082,76.834], +[57842.725,44.486,83.159], +[57893.955,51.23,80.42], +[57945.071,51.115,65.797], +[57986.93,41.859,92.649], +[58052.675,65.744,89.375], +[58105.581,52.905,87.085] +] diff --git a/apps/wireguard-client/build_macos.py b/apps/wireguard-client/build_macos.py new file mode 100644 index 00000000..3748aafc --- /dev/null +++ b/apps/wireguard-client/build_macos.py @@ -0,0 +1,50 @@ +"""Pinned third-party client build; all outputs remain in owned product staging.""" +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess + +REPO = Path(__file__).resolve().parents[2] +BUILD = REPO / ".runtime/wireguard-build" +OUT = REPO / "apps/wireguard-client/build/macos-arm64" +SOURCES = { + "wireguard-go": ("0.0.20250522", "f333402bd9cbe0f3eeb02507bd14e23d7d639280"), + "wireguard-tools": ("v1.0.20260223", "49ce333da02056ae7b22ee2aeb6afe8aaed79b19"), +} + +def run(args, cwd=None, env=None): + subprocess.run(args, cwd=cwd, env=env, check=True) + + +def main(): + BUILD.mkdir(parents=True, exist_ok=True) + OUT.mkdir(parents=True, exist_ok=True) + for name, (tag, commit) in SOURCES.items(): + target = BUILD / name + if not target.exists(): + run(["git", "clone", "--quiet", "--depth", "1", "--branch", tag, "https://git.zx2c4.com/" + name, str(target)]) + found = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip() + if found != commit: + raise ValueError("Third-party source identity differs") + go = REPO / "apps/node-agent/build/_toolchain/go/bin/go" + env = dict(os.environ, GOMAXPROCS="2", GOMEMLIMIT="512MiB", GOCACHE=str(BUILD / "go-cache"), + GOPATH=str(BUILD / "go-modules"), CGO_ENABLED="0", GOOS="darwin", GOARCH="arm64") + run([str(go), "build", "-p", "1", "-trimpath", "-ldflags=-s -w", "-o", str(OUT / "wireguard-go"), "."], BUILD / "wireguard-go", env) + run(["make", "-j1", "wg"], BUILD / "wireguard-tools/src") + shutil.copy2(BUILD / "wireguard-tools/src/wg", OUT / "wg") + for binary in (OUT / "wg", OUT / "wireguard-go"): + run(["codesign", "--force", "--sign", "-", str(binary)]) + licenses = OUT / "licenses" + licenses.mkdir(exist_ok=True) + for name in SOURCES: + shutil.copy2(BUILD / name / ("LICENSE" if name == "wireguard-go" else "COPYING"), licenses / (name + ".txt")) + manifest = {"platform": "darwin-arm64", "sources": SOURCES, + "files": {str(p.relative_to(OUT)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(OUT.rglob("*")) if p.is_file() and p.name != "manifest.json"}} + (OUT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + print(json.dumps(manifest)) + +if __name__ == "__main__": + main() diff --git a/apps/wireguard-client/helper.py b/apps/wireguard-client/helper.py new file mode 100644 index 00000000..1bcadbe4 --- /dev/null +++ b/apps/wireguard-client/helper.py @@ -0,0 +1,411 @@ +"""Privileged, fixed-operation WireGuard helper. Socket is owned by one operator/Node UID.""" +import base64 +import hashlib +import ipaddress +import json +import os +import platform +import re +import socket +import socketserver +import subprocess +import threading +import time +from pathlib import Path + +DARWIN = platform.system() == "Darwin" +HOME = Path("/Library/Application Support/NODE.DC/MissionWireGuard" if DARWIN else "/var/lib/mission-core-wireguard") +SOCKET = "/var/run/ndc-mission-wireguard.sock" if DARWIN else "/run/mission-core-wireguard/control.sock" +BIN = Path(__file__).resolve().parent +WG = str(BIN / "wg") if DARWIN else "/usr/bin/wg" + + +def run(*args, data=None, check=True): + return subprocess.run(args, input=data, check=check, capture_output=True, timeout=15) + + +def save(path, value): + tmp = path.with_name(path.name + ".new") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as out: + json.dump(value, out) + out.flush() + os.fsync(out.fileno()) + os.replace(tmp, path) + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def server_id(value): + if not isinstance(value, str) or not re.fullmatch(r"wg_[a-f0-9]{32}", value): + raise ValueError("Invalid server identity") + return value + + +def key(value): + if not isinstance(value, str) or len(value) != 44 or len(base64.b64decode(value, validate=True)) != 32: + raise ValueError("Invalid WireGuard key") + return value + + +def validate(value): + required = {"server_id", "address", "subnet", "server_public_key", "endpoint", "allowed_ips", "role"} + if not isinstance(value, dict) or set(value) != required | (set(value) & {"interface"}): + raise ValueError("Invalid connection profile") + server_id(value["server_id"]) + key(value["server_public_key"]) + network = ipaddress.ip_network(value["subnet"]) + permitted = ipaddress.ip_network("10.203.0.0/16") + if network.version != 4 or network.prefixlen != 24 or not network.subnet_of(permitted): + raise ValueError("Only an isolated fleet /24 is supported") + address = ipaddress.ip_address(value["address"]) + if address not in network or value["role"] not in ("core", "node"): + raise ValueError("Invalid peer address") + if (value["role"] == "core" and address != network[2]) or (value["role"] == "node" and not network[3] <= address <= network[253]): + raise ValueError("Address does not match peer role") + allowed = value["allowed_ips"] + if not isinstance(allowed, list) or not 1 <= len(allowed) <= network.num_addresses - 4 or len(set(allowed)) != len(allowed): + raise ValueError("Invalid routes") + for text in allowed: + peer = ipaddress.ip_network(text) + if peer.prefixlen != 32 or not peer.subnet_of(network) or peer.network_address == address: + raise ValueError("Only other fleet peer /32 routes are admitted") + if value["role"] == "node" and peer.network_address not in (network[1], network[2]): + raise ValueError("A board may reach only its Core and the tunnel gateway") + endpoint = value["endpoint"] + if not isinstance(endpoint, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}:51830", endpoint): + raise ValueError("Invalid public WireGuard endpoint") + addresses = {item[4][0] for item in socket.getaddrinfo(endpoint.split(":")[0], None, socket.AF_INET)} + if not addresses or any(not ipaddress.ip_address(a).is_global for a in addresses): + raise ValueError("WireGuard endpoint must be public") + if value.get("interface") and (not DARWIN or not re.fullmatch(r"en[0-9]{1,2}", value["interface"])): + raise ValueError("Unsupported physical interface") + return sorted(addresses)[0] + + +class Manager: + def __init__(self, root=HOME): + self.root = Path(root) + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + self.lock = threading.RLock() + self.path = self.root / "profiles.json" + self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {} + self.children = {} + + def persist(self): + save(self.path, self.profiles) + + def prepare(self, identity): + server_id(identity) + if identity not in self.profiles: + if len(self.profiles) >= 8: + raise ValueError("Maximum eight server profiles") + private = run(WG, "genkey").stdout.strip().decode() + public = run(WG, "pubkey", data=(private + "\n").encode()).stdout.strip().decode() + self.profiles[identity] = {"private_key": private, "public_key": public, + "config": None, "pending": None, "interface": None} + self.persist() + return self.profiles[identity] + + def physical_route(self, config, endpoint, row): + interface = config.get("interface") + if not DARWIN or not interface: + return + gateway = run("/usr/sbin/ipconfig", "getoption", interface, "router").stdout.decode().split()[0] + source = run("/usr/sbin/ipconfig", "getifaddr", interface).stdout.decode().strip() + ipaddress.IPv4Address(gateway) + ipaddress.IPv4Address(source) + result = run("/sbin/route", "-n", "get", endpoint).stdout.decode() + fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line) + # Never replace a foreign explicit /32. Only our saved host route may change. + flags = fields.get("flags", "") + if "HOST" in flags and "WASCLONED" in flags: + # macOS caches a destination under the VPN default route. This is + # not an operator-created static route. Retire only that cache entry. + cached_interface = fields.get("interface", "").strip() + if re.fullmatch(r"(?:utun|en)[0-9]+", cached_interface): + run("/sbin/route", "-n", "delete", "-host", endpoint, "-ifscope", cached_interface, check=False) + flags = "" + owned = row.setdefault("host_routes", {}) + if row.get("host_route"): + owned.setdefault(row["host_route"]["endpoint"], row["host_route"]) + prior = owned.get(endpoint) + actual_gateway = fields.get("gateway", "").strip() + actual_interface = fields.get("interface", "").strip() + is_host = "HOST" in flags + if is_host and prior and (actual_gateway != prior["gateway"] or actual_interface != prior["interface"]): + raise ValueError("An owned host route was changed outside this application") + if is_host and not prior: + if actual_interface != interface or actual_gateway != gateway: + raise ValueError("An existing host route conflicts with this connection") + row["physical_endpoint"] = endpoint + self.persist() + 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. + 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 retire_physical_routes(self, row): + if not DARWIN: + return + used = {value.get("physical_endpoint") for value in self.profiles.values() if value.get("config")} + for endpoint, record in list(row.get("host_routes", {}).items()): + if endpoint in used: + continue + result = run("/sbin/route", "-n", "get", endpoint, check=False).stdout.decode() + fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line) + if ("HOST" in fields.get("flags", "") and fields.get("gateway", "").strip() == record["gateway"] + and fields.get("interface", "").strip() == record["interface"]): + run("/sbin/route", "-n", "delete", "-host", endpoint, record["gateway"], check=False) + del row["host_routes"][endpoint] + row["host_route"] = row.get("host_routes", {}).get(row.get("physical_endpoint")) + self.persist() + + def apply(self, row, config): + if config is None: + self.down(row) + return + endpoint = validate(config) + forward = run("/usr/sbin/sysctl" if DARWIN else "/usr/sbin/sysctl", "-n", "net.inet.ip.forwarding" if DARWIN else "net.ipv4.ip_forward").stdout.strip() + if forward != b"0": + raise ValueError("Host forwarding must be disabled before joining the fleet") + self.physical_route(config, endpoint, row) + name = row.get("interface") + if name: + found = run(WG, "show", name, "public-key", check=False) + if found.returncode == 0 and found.stdout.decode().strip() != row["public_key"]: + raise ValueError("Interface identity changed") + if found.returncode: + name = None + if not name: + if DARWIN: + name_file = self.root / (config["server_id"] + ".interface") + name_file.unlink(missing_ok=True) + env = dict(os.environ, WG_TUN_NAME_FILE=str(name_file)) + child = subprocess.Popen([str(BIN / "wireguard-go"), "-f", "utun"], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.children[config["server_id"]] = child + for _ in range(50): + if name_file.exists(): + name = name_file.read_text().strip() + break + if child.poll() is not None: + raise ValueError("WireGuard interface could not start") + time.sleep(0.1) + if not name or not re.fullmatch(r"utun[0-9]+", name): + raise ValueError("WireGuard interface startup timed out") + else: + name = "mcwg" + config["server_id"][3:11] + # Existence without our durable record is a foreign conflict. + run("/usr/sbin/ip", "link", "add", name, "type", "wireguard") + row["interface"] = name + self.persist() + old_routes = set(row.get("routes", (row.get("config") or {}).get("allowed_ips", []))) + new_routes = set(config["allowed_ips"]) + text = ("[Interface]\nPrivateKey = " + row["private_key"] + "\n[Peer]\nPublicKey = " + + config["server_public_key"] + "\nEndpoint = " + endpoint + ":51830\nAllowedIPs = " + + ", ".join(config["allowed_ips"]) + "\nPersistentKeepalive = 20\n") + path = self.root / "apply.conf" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as out: + out.write(text) + try: + run(WG, "setconf", name, str(path)) + finally: + path.unlink(missing_ok=True) + # Record each owned route immediately. Never replace a foreign host route. + if DARWIN: + run("/sbin/ifconfig", name, "inet", config["address"], config["address"], "netmask", "255.255.255.255") + run("/sbin/ifconfig", name, "mtu", "1280", "up") + else: + run("/usr/sbin/ip", "address", "replace", config["address"] + "/32", "dev", name) + run("/usr/sbin/ip", "link", "set", name, "mtu", "1280", "up") + for route in old_routes - new_routes: + self.remove_route(route, name) + old_routes.remove(route) + row["routes"] = sorted(old_routes) + self.persist() + for route in new_routes: + 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", "") + own = exists and fields.get("interface", "").strip() == name + else: + entries = json.loads(run("/usr/sbin/ip", "-j", "route", "show", "exact", route).stdout) + exists = bool(entries) + own = exists and all(entry.get("dev") == name for entry in entries) + if exists and not own: + raise ValueError("An existing host route conflicts with this fleet") + if not own: + if DARWIN: + run("/sbin/route", "-n", "add", "-host", route[:-3], "-interface", name) + else: + run("/usr/sbin/ip", "route", "add", route, "dev", name) + old_routes.add(route) + row["routes"] = sorted(old_routes) + self.persist() + row["config"] = config + self.persist() + self.retire_physical_routes(row) + + def remove_route(self, route, name): + if DARWIN: + run("/sbin/route", "-n", "delete", "-host", route[:-3], "-interface", name, check=False) + else: + run("/usr/sbin/ip", "route", "del", route, "dev", name, check=False) + + def down(self, row): + name = row.get("interface") + if name: + check = run(WG, "show", name, "public-key", check=False) + if check.returncode == 0 and check.stdout.decode().strip() not in ("", "(none)", row["public_key"]): + raise ValueError("Refusing to remove foreign interface") + if DARWIN: + for route in row.get("routes", (row.get("config") or {}).get("allowed_ips", [])): + run("/sbin/route", "-n", "delete", "-host", route[:-3], "-interface", name, check=False) + Path("/var/run/wireguard", name + ".sock").unlink(missing_ok=True) + else: + run("/usr/sbin/ip", "link", "delete", name, check=False) + row["interface"] = None + row["routes"] = [] + row["config"] = None + row["physical_endpoint"] = None + self.persist() + self.retire_physical_routes(row) + + def view(self, identity, row): + handshake = 0 + if row.get("interface"): + result = run(WG, "show", row["interface"], "latest-handshakes", check=False) + if result.returncode == 0: + handshake = max([int(line.split()[1]) for line in result.stdout.decode().splitlines()] or [0]) + return {"server_id": identity, "public_key": row["public_key"], "config": row["config"], + "interface": row["interface"], "pending": row["pending"] is not None, + "last_handshake": handshake} + + def dispatch(self, body): + if isinstance(body, dict) and body.get("action") == "health" and set(body) <= {"action", "server_id"}: + return {"schema": "missioncore.wireguard-helper/v1", "sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} + if not isinstance(body, dict) or set(body) - {"action", "server_id", "config", "operation_id"}: + raise ValueError("Invalid helper request") + with self.lock: + action = body.get("action") + if action not in ("prepare", "status", "stage", "confirm", "apply", "disable", "rollback"): + raise ValueError("Unknown action") + identity = server_id(body.get("server_id")) + row = self.prepare(identity) + if action in ("stage", "apply"): + config = body["config"] + validate(config) + if config["server_id"] != identity: + raise ValueError("Different server") + if action == "stage": + op = body.get("operation_id") + if not isinstance(op, str) or not re.fullmatch(r"[a-f0-9]{32}", op): + raise ValueError("Operation identity required") + if row["pending"] and row["pending"]["id"] != op: + raise ValueError("Another network change is pending") + if row["pending"] is None: + row["pending"] = {"id": op, "previous": row["config"], "deadline": time.time() + 120} + self.persist() + previous = row["config"] + try: + self.apply(row, config) + except Exception: + self.apply(row, previous) + row["pending"] = None + self.persist() + raise + elif action == "rollback": + record = row["pending"] or row.get("confirmed") + if record and record["id"] == body.get("operation_id"): + self.apply(row, record["previous"]) + row["pending"] = None + row["confirmed"] = None + self.persist() + elif action == "confirm": + if row["pending"] and row["pending"]["id"] != body.get("operation_id"): + raise ValueError("Operation changed") + if row["pending"]: + row["confirmed"] = row["pending"] + row["pending"] = None + self.persist() + elif action == "disable": + self.down(row) + row["pending"] = None + self.persist() + return self.view(identity, row) + + def restore(self, startup=False): + with self.lock: + for row in self.profiles.values(): + 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"]) + + +class Handler(socketserver.StreamRequestHandler): + def handle(self): + self.request.settimeout(10) + try: + raw = self.rfile.readline(16385) + if not raw.endswith(b"\n") or len(raw) > 16384: + raise ValueError("Invalid message") + result = {"ok": True, "result": self.server.manager.dispatch(json.loads(raw))} + except Exception as error: + result = {"ok": False, "error": str(error) if isinstance(error, ValueError) else "System network preparation failed"} + self.wfile.write(json.dumps(result).encode() + b"\n") + + +def secure_socket(path, uid, gid): + # With CAP_CHOWN but no CAP_FOWNER, chmod must precede ownership transfer. + os.chmod(path, 0o600) + os.chown(path, uid, gid) + + +def main(): + if os.geteuid() != 0: + raise ValueError("Installed system helper required") + os.umask(0o077) + if DARWIN: + owner = json.loads((BIN / "owner.json").read_text()) + else: + import pwd + account = pwd.getpwnam("mission-core-node") + owner = {"uid": account.pw_uid, "gid": account.pw_gid} + manager = Manager() + try: + manager.restore(startup=True) + except Exception: + pass # Keep the bounded local control socket available for recovery. + path = Path(SOCKET) + path.parent.mkdir(parents=True, exist_ok=True) + path.unlink(missing_ok=True) + with socketserver.UnixStreamServer(SOCKET, Handler) as server: + server.manager = manager + secure_socket(SOCKET, owner["uid"], owner["gid"]) + server.timeout = 1 + while True: + server.handle_request() + try: + manager.restore() + except Exception: + pass + + +if __name__ == "__main__": + main() diff --git a/apps/wireguard-client/install_macos.py b/apps/wireguard-client/install_macos.py new file mode 100644 index 00000000..91b4e057 --- /dev/null +++ b/apps/wireguard-client/install_macos.py @@ -0,0 +1,86 @@ +"""Install the reviewed client payload through the standard macOS administrator prompt.""" +import argparse +import hashlib +import json +import os +import platform +import plistlib +import pwd +import shutil +import subprocess +import time +import socket +from pathlib import Path + +ROOT = Path("/Library/Application Support/NODE.DC/MissionWireGuard") +PLIST = Path("/Library/LaunchDaemons/com.nodedc.mission-wireguard.plist") +LABEL = "com.nodedc.mission-wireguard" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--uid", type=int, required=True) + args = parser.parse_args() + if os.geteuid() != 0 or platform.system() != "Darwin" or platform.machine() != "arm64" or args.uid < 500: + raise ValueError("macOS Apple Silicon administrator installation required") + user = pwd.getpwuid(args.uid) + source = Path(__file__).resolve().parent + binaries = source / "build/macos-arm64" + manifest = json.loads((binaries / "manifest.json").read_text()) + for name, digest in manifest["files"].items(): + path = binaries / name + if not path.resolve().is_relative_to(binaries.resolve()) or hashlib.sha256(path.read_bytes()).hexdigest() != digest: + raise ValueError("Client payload hash mismatch") + if ROOT.exists() and not (ROOT / "installed.json").is_file(): + raise ValueError("Foreign installation directory") + if PLIST.exists(): + old = plistlib.loads(PLIST.read_bytes()) + if old.get("Label") != LABEL or not str(old.get("ProgramArguments", ["", "", ""])[-1]).startswith(str(ROOT)): + raise ValueError("Foreign launch daemon") + identity = hashlib.sha256((source / "helper.py").read_bytes() + json.dumps(manifest, sort_keys=True).encode()).hexdigest() + ROOT.mkdir(mode=0o700, parents=True, exist_ok=True) + ROOT.chmod(0o700) + release = ROOT / "releases" / identity + release.mkdir(mode=0o700, parents=True, exist_ok=True) + for name in ("wg", "wireguard-go"): + shutil.copy2(binaries / name, release / name) + (release / name).chmod(0o700) + shutil.copy2(source / "helper.py", release / "helper.py") + (release / "helper.py").chmod(0o600) + (release / "owner.json").write_text(json.dumps({"uid": args.uid, "gid": user.pw_gid})) + (release / "owner.json").chmod(0o600) + value = {"Label": LABEL, "ProgramArguments": ["/usr/bin/python3", "-I", str(release / "helper.py")], + "RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 10, + "ProcessType": "Background", "Umask": 63} + previous = PLIST.read_bytes() if PLIST.exists() else None + try: + subprocess.run(["/bin/launchctl", "bootout", "system/" + LABEL], capture_output=True) + PLIST.write_bytes(plistlib.dumps(value)) + PLIST.chmod(0o644) + subprocess.run(["/bin/launchctl", "bootstrap", "system", str(PLIST)], check=True, capture_output=True) + for attempt in range(40): + try: + with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as connection: + connection.settimeout(1) + connection.connect("/var/run/ndc-mission-wireguard.sock") + connection.sendall(b'{"action":"health"}\n') + result=json.loads(connection.recv(4096)) + if result.get("result",{}).get("sha256") != hashlib.sha256((release / "helper.py").read_bytes()).hexdigest(): + raise ValueError("Helper identity mismatch") + break + except Exception: + if attempt == 39: raise ValueError("Installed helper did not become ready") + time.sleep(.25) + (ROOT / "installed.json").write_text(json.dumps({"artifact": identity, "uid": args.uid, "label": LABEL})) + (ROOT / "installed.json").chmod(0o600) + except Exception: + subprocess.run(["/bin/launchctl", "bootout", "system/" + LABEL], capture_output=True) + if previous: + PLIST.write_bytes(previous) + subprocess.run(["/bin/launchctl", "bootstrap", "system", str(PLIST)], capture_output=True) + else: + PLIST.unlink(missing_ok=True) + raise + +if __name__ == "__main__": + main() diff --git a/apps/wireguard-client/test_helper.py b/apps/wireguard-client/test_helper.py new file mode 100644 index 00000000..6ccfa9d1 --- /dev/null +++ b/apps/wireguard-client/test_helper.py @@ -0,0 +1,19 @@ +import importlib.util +import pathlib +import unittest +from unittest.mock import patch + +class SocketOwnershipTest(unittest.TestCase): + def test_no_fowner_capability_is_required_after_chown(self): + spec=importlib.util.spec_from_file_location('wg_helper',pathlib.Path(__file__).with_name('helper.py')) + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + state={'owner':0,'mode':0o700} + def chmod(path,mode): + if state['owner']!=0:raise PermissionError('CAP_FOWNER is deliberately absent') + state['mode']=mode + def chown(path,uid,gid):state['owner']=uid + with patch.object(module.os,'chmod',chmod),patch.object(module.os,'chown',chown): + module.secure_socket('/run/example.sock',123,123) + self.assertEqual(state,{'owner':123,'mode':0o600}) + +if __name__=='__main__':unittest.main() diff --git a/docs/audits/2026-10-26-network-runtime-and-dev.md b/docs/audits/2026-10-26-network-runtime-and-dev.md new file mode 100644 index 00000000..e6a5da2d --- /dev/null +++ b/docs/audits/2026-10-26-network-runtime-and-dev.md @@ -0,0 +1,99 @@ +# Network runtime and configurable DEV capture — 2026-10-26 + +## Product surface brief + +The operator starts one diagnostic capture from the existing DEV action in the +board observation workspace. Before starting, they choose local event sources, +whether to show live rows, whether to transfer Core/browser evidence to the +board, and independent event-payload rate limits. A capture owns immutable +options, its identifier, on-board JSONL writer and explicit stop/export lifecycle. +It never owns motor authority. Opening the modal removes driving input focus. + +Chosen composition: the owner-requested modal using the existing Design Guideline +Window, WindowFooterActions, SettingsCard, Switch, Select, Description and Button. +An always-visible settings panel was considered: it would consume observation +space and imply that choices can mutate a running capture. The modal fits the +one-time pre-start decision. No new workspace, navigation or shared visual entity +is introduced. Local-only event recording is the default; short lifecycle status +still crosses the network. Normal telemetry/video are separate choices. + +Start is disabled until Node advertises option support. Cancel/Escape do not +start capture. Pending, error, closing, completed-file and interrupted-file states +reuse existing controls. The log panel remains available after stop for export. +A file's dropped records and errors remain visible. Capture configuration is not +a claim of recording acceptance until board storage status arrives. + +## Implemented network contracts + +- Packet admission uses cancellable asynchronous Unix IPC. A single absolute + 500 ms frame/datagram lifetime covers queue age, permit wait and actual send. + Expired SCTP entries never wait for another permit; transient IPC/allocation + loss retires payload and preserves the peer. Invalid policy framing is terminal. +- Protocol-only DTLS/RTCP has a bounded 2 KiB/s allowance with an 8 KiB burst per + admitted transport, outside disposable payload backlog. Ordinary payload has + no essential flag. Existing peer counts and aggregate payload gates remain. +- Producer leases carry an explicit operator-primary role. Most recent selection + wins, expires after 3 s, and is released with its peer. Primary video receives + its requested share first; other video shares the residual. Finite metadata + gets at most 32 kbit/s before video, cloud/export receive residual capacity. +- At command pressure (existing 150 ms threshold), only an explicitly selected + video may use at most 384 kbit/s. At 250 ms gap/age/silence all optional payload + yields. This is a new policy requiring field qualification; motor deadlines + (400 ms Core lease, 350 ms stream guard, native watchdog) are unchanged. +- H.264 payloads are bounded to 1100 bytes by a per-sender packetizer. NAL content + and order are preserved; no codec globals are changed. Encoder/frame sizes, + reinitializations, expiry, protocol and permit-wait counters are exposed. +- Full budget summaries run at 1 Hz only after capability negotiation. Actual + motor telemetry cadence/sample clocks remain unchanged. Core retains the budget + summary for at most 2 s, with explicit age, independently of motor freshness. +- X4 view canvases retain the last rendered pixels; the UI shows last-presented + frame age during interruption. Decode progress does not advance presentation + time. This does not measure capture-to-screen latency. + +## Recording contracts + +A strict six-field option schema is negotiated. Core/browser and live event +payloads have independent 8/16/32/64 kbit/s limits; metadata/protocol overhead is +separate. Local-only capture sends no event rows. Local Node events still enter +the on-board file. Recorder lifecycle polls use bounded metadata capacity; +record rows and exports use bulk capacity. Closing a local-only file ends local +polling without waiting for a deliberately disabled live cursor. + +Writer rows are immutable serialized bytes, at most 8192 bytes per record, +4096 entries and 4 MiB queued. Stop is out of band, so saturation cannot discard +it. Accepted rows drain before the footer. Oversized Core rows get an explicit +omission marker so stop cursors can complete; missing rows are never silently +reported as complete evidence. Session manifest includes the selected options. + +## Qualification and rollout + +Node72/X4-22 are qualified and installed through their versioned owner +installers. Core/UI is rebuilt and running; 1344 frontend tests, subsequent +focused checks, typecheck and passive Chrome modal QA passed. X4 passed 126 +Ubuntu package tests. Node72 passed full Go race tests, Node UI, environment, +USB-CAN ABI and 427 VESC tests. Its interrupted dependency-fetch stage was +completed by a pinned packaging continuation with source and ELF hash guards; +the original timeout evidence is retained. No unversioned runtime patch was used. + +Local DEV recorded 1472 events with zero drops; all 12 export chunks were verified. +The minimum-rate live check found metadata consuming event capacity in Node71. +Node72 separates metadata/export from the event allowance and shares remaining +event capacity between row sources. Two regressions include a real-sized 985-byte +motor row. Physical 8-kbit/s acceptance received 13 motor rows in 16 observations; +the full file retained 824 events, zero drops, seven verified export chunks. +Minimal local configuration selected through Chrome retained only capture start +and stop, with all four optional switches off; its manifest and file agree. +The default modal values return on reopening, and camera preview is live. + +Node CAN maintenance restored observation with motor_commands=false. The first +live check during a concurrent large engineering SSH transfer had only 6/16 +fresh received snapshots; after pausing that transfer the repeat had 16/16. +Device age is separate: the repeat's first pre-capture sample was 4600 ms old, +then at most 602 ms in the remaining observations. This is scoped evidence, +not a claim of universal low latency. The application regulator does not own SSH. +Exact hashes and acceptance limits are in +`../../outputs/network-dev-20261026/REPORT.txt`. + +Scope excludes a transport migration to QUIC, speculative vendor codec tuning, +autonomous movement and physical motor tests without an awake operator. The +provided audit's later transport/LiDAR stages remain separate measured decisions. diff --git a/docs/node/04_NODE_CORE_PAIRING_PROTOCOL.md b/docs/node/04_NODE_CORE_PAIRING_PROTOCOL.md index 9323b60a..c893b0e1 100644 --- a/docs/node/04_NODE_CORE_PAIRING_PROTOCOL.md +++ b/docs/node/04_NODE_CORE_PAIRING_PROTOCOL.md @@ -239,3 +239,22 @@ Node также не применяет результаты запросов, миграция LAN→другой LAN этим расширением не заявляется. Установка и аппаратная приёмка NET02 фиксируются отдельно в installation ledger; наличие кода и синтетических тестов само по себе не означает восстановления Rover006. + + +## Актуализация heartbeat, Node 0.8.49-59 / 24.10.2026 + +Текущий общий mTLS endpoint допускает bounded JSON до 8 MiB, DEV endpoint — +до 112 KiB; ранний предел 64 KiB выше относится к исходному этапу pairing. +Полный heartbeat single-flight и использует долю inventory единого бюджета. +Короткая /v1/node/liveness (до 2 KiB, 5 с во время большого upload) имеет то же +доверие, возвращает только подтверждение присутствия и хранится в bounded RAM. +last_seen остаётся временем полного inventory; link_last_seen и inventory_fresh +разделяют присутствие Node и свежесть сведений. Ни один из этих heartbeat не +продлевает управление. Дедлайны paced uploads рассчитываются по размеру и +минимальной выделенной полосе; подробный текущий контракт и приёмка — +[общий бюджет канала](38_SHARED_LINK_BUDGET.md). + + +## Выбор сети Core ↔ Node + +Профили Tailscale/WireGuard, установка VPS, применение через настройки БК и границы приёмки описаны в [WireGuard fleet network](40_WIREGUARD_FLEET_NETWORK.md). Смена маршрута сохраняет существующее доверие Core ↔ Node; Worker остаётся в отдельном контуре. diff --git a/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md b/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md index 7d296dbd..213b8b62 100644 --- a/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md +++ b/docs/node/25_OBSERVATION_AND_REMOTE_CONTROL.md @@ -1,5 +1,53 @@ # Observation and remote control — implementation record +## Remote throttle — 2026-10-16 + +VESC integration 0.7.5 / Node packaging 0.8.49-4 adds an explicit `duty` +capability alongside the compatible bounded `rpm` mode. The operator's task is +to select throttle independently of available torque. A 48 V, 120 Ah battery +was reported by the owner; this does not establish BMS current ratings. The +owner retained the existing 30 A per-motor operator ceiling. No manufacturer +maximum is inferred from the `75_300_R2` firmware name or the controller's +configured protection thresholds. + +Fresh read-only configuration receipts from both controllers show PPM type 4 +(Duty Cycle), motor current limits approximately 34.2/34.4 A, maximum duty 0.95 +and a speed-PID minimum of 900 ERPM. Previously the keyboard always used RPM +control, capped at 3000 ERPM, plus the raised-rig telemetry envelope of 6000 +ERPM / 25% duty. These are software restrictions, not motor ratings. Their +presence is verified; attribution of ground behavior still requires an attended +test. + +The new input is 1–100% of the configured PPM full-throttle output, not km/h or +a measured speed setpoint. The native adapter calls upstream Tool's +`Commands::setDutyCycle`; FW 5.02 PPM uses the same duty endpoint. All configured +motor/battery/ERPM limits remain unchanged. The existing temporary-current +workflow only reduces current scales and restores the original configuration. +The native duty entry point requires a live output lease, read configurations, +PPM Duty Cycle and an effective current ceiling no greater than 30 A in both +directions. The duty request cannot exceed the freshly read controller maximum. +The paired drive uses the slower of the configured PPM ramps for consistent +left/right normalization. Throttle telemetry uses controller ERPM/duty bounds; +the separate bench tests retain their previous envelope. Fault, temperature, +current, stall, input-lease, receiver takeover and reversal checks remain. +Zero input releases current immediately; it does not command braking or a +zero-RPM hold. + +The admitted settings Window removes the separate standstill switch. Pressing +“Включить управление” is the explicit operator admission on a stopped rover; +the adjacent instruction states this requirement. The driver still performs +its existing current/duty/receiver-neutral checks, including the documented +sensorless standstill limitation. No automatic motion or automatic arm is +introduced. Saved ERPM is never converted into a throttle value: v1 settings +migrate to 10%, retaining model and input layout. Old Nodes remain on the +compatible RPM UI; Core rejects percent commands without the new capability. + +Firmware reference: upstream `vedderb/bldc` commit +`3f670137e27e6e383fa79c50cc6b1fa85aab1554`, `datatypes.h` PPM enum and +`applications/app_ppm.c` Duty Cycle branch and ramp. Private read receipts and +build/validation evidence live under `outputs/rover-006-control-20261016`. +No agent-issued arm, drive, calibration or firmware write is part of this work. + Owner request: 2026-09-25. Extend the existing per-vehicle observation center. The operator sees cameras, map, a vehicle model and per-controller telemetry, then explicitly takes keyboard/pointer control. Return goes to the vehicle list. @@ -543,3 +591,372 @@ was sent. Explicit UI Stop completed at 13:21:09 UTC, release confirmed. A subsequent page reload and settings reopen also passed. These are bounded UI/lifecycle checks, not new acceptance of driving or RC takeover. Private entry-startup-result.json contains UTC/monotonic evidence and SHA-256 hashes. + + +Installed 2026-10-16 11:29:05 UTC through owner release +`7e1d42890af25db8f9c81914`; all installer stages succeeded in 19.64 s. APT +upgraded only mission-core-node 0.8.49-3 -> 0.8.49-4 (zero additions/removals). +Read-only verification confirms Node/VESC active, preparation 0.7.5 complete, +and installed native binary hash matches the qualified payload. Core receives +fresh `rpm,duty` capability and both assigned controllers at zero current/ERPM, +fault=0, no control session. Fresh post-install backups have identical motor +and application configuration hashes for both VESCs. + +Browser verification: Gas 10%, current 30 A; 50% accepted without arming, 101% +disables the primary action, 10% restored and retained after Escape/reopen. +Standstill switch absent, primary action present. Canonical Core remains on +8000. No agent-issued arm or movement. Loaded driving, precise ground speed +and physical stopping with the new duty output remain owner-attended tests. + + +2026-10-16 UI follow-up: current-limit settings v3 repairs the legacy empty-input +0 -> 0.5 A clamp to the owner-approved 30 A. Empty/invalid drafts no longer +overwrite valid saved settings; explicitly saved v3 0.5 A remains valid. +The last fresh advertised control capability is retained through stale reads; +missing telemetry no longer makes a duty-capable rover display ERPM. A failed +preparation/session now leaves an operator-visible reason. + +Read-only journal evidence from the owner attempts showed command lease gaps +17–30 ms beyond the then-advertised TTL during preparation. The UI sender +previously serialized fresh intent behind HTTP acknowledgement. It now permits +at most four in-flight requests, with no command queue and sequence-aware +handling of delayed replies. All input-freshness checks, 350 ms HTTP deadline, +Core/Node/native watchdogs and no-resume rules remain unchanged. The gap +evidence alone does not isolate browser scheduling from transport latency. +No Node installation, firmware/configuration change, arm or motion was issued +by the agent for this follow-up. + +Validation: 1103 frontend unit tests, architecture check, TypeScript and build +passed sequentially. Browser QA on canonical 8000 verified Gas 10%, current +30 A, blank current disables Enable, reload restores the preceding valid +30 A, Escape and the expanded view. The bounded delayed-ACK regression proves +latest intent is not serialized behind old replies; hardware preparation and +loaded driving with this correction remain owner-attended verification. +Private logs/screenshots: outputs/rover-006-control-20261016-followup. + + +Owner retry at 12:21:31–12:22:08 UTC reached ready and driving, with observed +peaks near 12400 ERPM and 30 A per motor, fault=0. The session subsequently +expired again: the local command sequence jumped across a 389 ms interval, +longer than its preceding 357 ms TTL. Final stopped telemetry confirmed +release and zero current/ERPM. This trial proves preparation and actual output, +not stable remote operation. Core logs also contain registry lock waits up to +160 ms; their contribution to this particular expiration is not isolated. + +Owner explicitly revised interruption behavior: automatically restore control +readiness after temporary connection loss, without restoring remembered motion. +The frontend now retains the operator's request only in RAM, retires the expired +lease, shows canonical LoadingRegion/status «Восстанавливаем связь», and +reacquires a new zero-demand lease after >=500 ms of consecutive fresh stopped +observations of the same motors/driver/profile, with increasing bounded retry +delay. Retry requires a visible focused document. New readiness creates a fresh +input binding: held/repeated pre-outage keys cannot resume movement. Stop, +pagehide/unmount, RC takeover, changed driver/profile or hardware fault cancel +recovery. Delayed arm acknowledgements after cancellation are explicitly stopped. +Native preparation, neutral admission, lease deadlines, current limit, firmware +and OS configuration remain unchanged. + +Acceptance: 40 focused recovery/input tests and 1111 full frontend unit tests, +architecture, typecheck and production build pass. Browser confirms the new +copy and gas/current persistence even while the real board is unavailable. +Automatic physical recovery has not yet been verified: after the build the +board is stale and SSH does not connect. No agent-issued arm/motion or network +change was performed. The unchanged Node/VESC versions are 0.8.49-4/0.7.5. + + +## 2026-10-16: control admission independent of inventory storage + +Read-only review of the owner's 12:21–12:22 UTC trial confirmed a 389 ms gap +between new command sequences against the preceding 357 ms remaining lifetime. +Local driver calls and telemetry continued through that interval. Current Core +logs also showed the real-time Node channel waiting on the registry writer lock +for up to 179 ms. This is an evidenced latency source; the existing logs do not +prove it accounts for the entire historical command gap. + +The Core now publishes a minimal committed binding projection for the rover +channel. Browser view/arm/command and every authenticated Node telemetry/stream +frame use that short independent lock; inventory validation, configuration +archival and SQLite fsync retain the registry writer lock. Authentication and +endpoint-revision rules share the same functions with ordinary heartbeat. +Failed database commits never publish authority. Explicit computer replacement +holds the channel lock across admission/publication so it cannot race a new arm. +Revocation/replacement discards old transient control state. Restart loads +bindings only, never a previous session, motion or telemetry snapshot. + +The regression gates archive storage in a synthetic heartbeat and verifies +both directions of the production control path complete before releasing that +writer. Additional checks cover revoke, replacement/arm race, certificate +rotation and expiry, endpoint supersession, failed commit and restart. All 134 +fleet tests pass. Node/VESC code, 400 ms command lifetime, current limits, +neutral admission and OS/network configuration are unchanged. + +The observed ~10 s preparation is a separate phase: the VESC owner reads and +checks current controller configuration, archives recovery data, queries CAN +peers and confirms neutral/standstill before granting readiness. Repeated lease +loss restarts that preparation; this change does not skip those checks. Physical +control/recovery acceptance still requires an owner-attended trial. + +Private bounded evidence and before/after measurements: +`outputs/rover-control-channel-20261016`. + +Applied to the canonical local service at 14:16 UTC after confirming observing +state and no active control session; restart recovered health on port 8000. +Two bounded read-only runs, 120 observations each at 4 Hz, both had 120/120 fresh +snapshots. Local API response milliseconds before/after: median 6.8/4.3, +p95 66.2/53.8, maximum 113.5/141.6. These measurements do not demonstrate the +absence of scheduling/network spikes or establish stable driving. The isolated +writer-blocking regression proves removal of that specific contention only. + +Owner-attended retry at 14:21 UTC: preparing 14:21:01, ready 14:21:11, +followed by owner motion input. The observed session identity stayed unchanged, +with no VESC fault reported. Last new telemetry arrived around 14:21:39 and +became stale at 14:21:40. SSH, general heartbeat and tailnet reachability were +also lost. The board returned with a NEW boot at 14:24:12; Node and VESC services +started at 14:24:38. Previous journal ends abruptly (last persisted record +14:21:27) and wtmp marks the session as crash. These establish an interrupted +board boot. The owner subsequently confirmed a loose power lead and manual +power reconnection. Do not attribute this outage to software or count the trial +as continuous control/recovery acceptance. +The agent issued no board reboot, OS change, arm or movement. Canonical Core +remained healthy; Wi-Fi stayed configured and returned after the board boot. + +The next owner-driven session prepared at 14:27:08 UTC, became ready at +14:27:18 and entered fault at 14:27:54. Node/Core delivery remained fresh, with +new command sequences and about 306 ms lifetime remaining at the fault. The +driver reported `Native query timed out or disconnected`; left-controller +telemetry stopped updating while the right continued reporting zero current. +Release confirmation was false, so automatic control recovery was blocked. +No kernel USB disconnect was recorded in that initial interval. This localizes +the failure to the native/controller exchange, but does not distinguish a +controller, physical transport, scheduling or native-engine cause. Stale left +current/ERPM values are not evidence of continuing physical motion. + +At 14:30 UTC, separately, the kernel recorded removal from both direct USB +ports and enumeration attempts on hub ports, with descriptor errors -32/-71. +The owner confirmed manual USB reconnection and subsequent VESC battery-power +cycling, after which the missing controller returned. These later events must not +be retroactively treated as the established cause of the 14:27:54 failure. + +Diagnostic follow-up: remote control bypassed the ordinary operation receipt +that preserves native RPC failure diagnostics. The VESC service now journals +the initiating exception's command, transport events and preceding calls after +cleanup, rather than its subsequently overwritten `last_rpc`. Connection and +observation failures are also logged, limited to once per 30 seconds per device +or observer. Records are bounded to 16 KiB; logging failure cannot bypass fault, +release or ownership cleanup. No telemetry history or motor commands are added. +Installed with Node 0.8.49-5 / VESC 0.7.6 at 15:15 UTC; see acceptance below. + +### Explicit retry after a recovered VESC — 2026-10-16 + +At 14:44 UTC the owner reported both controllers back in telemetry, but manual +arming immediately stopped on a previous failure. A fresh API read confirmed +zero ERPM/current and fault code zero on both devices, while the terminal +session still carried `release_confirmed=false`. Two software causes were +reproduced: a poll during/after a new Core arm could apply the old terminal +snapshot to the new lease, and VESC preparation inherited the previous release +flag until it reached the output loop. + +The UI now accepts the exact preceding terminal snapshot only during an +explicitly requested new lease, until the board acknowledges that lease. +Boot/profile/mode changes still block. Transport recovery cannot suppress a +hardware fault; an error from the newly acknowledged session remains terminal. +The driver sets the new session's release state to unknown, never true, at +preparation admission. Hardware ownership, pending-limit restoration, +identity, neutral/standstill checks and the output watchdog remain unchanged. +No old demand is replayed. Focused regressions include old fault replies before +and after arm acknowledgement, new-session faults and interrupted preparation. + +Installed at 15:15:27 UTC through the normal Node 0.8.49-5 / VESC 0.7.6 +owner release `d24e43f334419d8a3d085161`, together with bounded native failure +diagnostics. APT upgraded one existing package, with zero additions/removals. +The Node and VESC services are active; installed source hashes match the +qualified payload. Five post-install samples were fresh, observing, with no +session, no error, and zero current/ERPM/fault on both controllers. Wi-Fi remains +connected to DCEXPRESS_DIR_5. Existing X4 0.1.3-15 was preserved by the installer. +The qualified installer is published in Core's normal Node installer catalog. + +Validation: architecture checks, TypeScript, 1124 frontend tests, production +build and 158 VESC tests pass; Ubuntu node qualification (including Go race +checks) completed in 285.615 seconds. Two rejected preliminary source inputs +were corrected and retained with their failure logs; neither was installed. +The final package SHA-256 is +`3fb41add4d191324a9ca9df179b0cde11f339465dd0175c68fa8b1dec3a9d7f7`. +No agent-issued arm, motion, controller reboot, firmware flash or network +reconfiguration was performed. Owner trial at 15:18:42 UTC prepared successfully by 15:18:52. The same +session remained active through 15:19:47, including three brief owner-issued +input samples. All 710 observation samples were fresh, with no read errors +or VESC fault codes. This verifies short-session startup/continuity; it does +not prove field reliability or recovery from a newly induced physical failure. + +This update does not establish the physical USB root cause. The upstream +[VESC forum dual-controller case](https://vesc-project.com/node/3050) reports +similar USB enumeration errors on different hardware and discusses ground +loops and isolation. This is a diagnostic lead, not a diagnosis of Rover 006. +Upstream [firmware 5.02 commands.c](https://github.com/vedderb/bldc/blob/5.02/commands.c) +implements COMM_REBOOT and COMM_FORWARD_CAN, but a remote reset still requires +an operational command path. An isolated board-to-CAN interface is a candidate +for reducing reliance on each controller's USB port; a complete processor hang +requires an independent reset/power recovery path. Neither change is installed. + +### Local browser connection contention — 2026-10-16 + +The owner stopped driving and authorized bounded throughput tests. On the +existing Mini Wi-Fi connection, two 25 MB HTTPS downloads measured 49.39 and +49.22 Mbit/s; two 10 MB uploads measured 41.37 and 44.97 Mbit/s. The complete +probe transferred 77 MB of synthetic data. Each concurrent gateway, operator +tailnet and Internet ping received 30/30 replies. Operator RTT under transfer +averaged 50.07 ms and peaked at 118.81 ms. These are short link measurements, +not a field-radio qualification or a capture-to-display latency measurement. +No network configuration, power-saving setting or OS package was changed. + +Independent measurements reproduced a separate operator-side failure while +opening the observation center: a browser GET spent 706 ms waiting before +request transmission, followed by only 4 ms waiting for the Core response. +Other browser GETs reached the 1000 ms deadline while its 100 ms input timer +continued normally. An independent 60-second local API observer obtained +120/120 fresh samples with a 4.36 ms median and 137.8 ms maximum request time. +This establishes browser HTTP connection contention during this reproduction; +it must not be attributed to onboard Wi-Fi or a VESC disconnect. + +The browser now uses a dedicated same-origin WebSocket for rover state and +command acknowledgements, separate from HTTP assets, camera negotiation and +inventory/SSE traffic. The existing authenticated Node channel, driver, +exclusive ownership and motor/output watchdog are unchanged. The socket: + +- requires a loopback client, approved local Host and exactly matching Origin; +- only controls the session it explicitly armed; closing an observer cannot + retire another operator's session; +- bounds pending requests and transport buffering, never replays on reconnect; +- carries a conservative absolute deadline from server monotonic samples; + arrival cannot refresh a delayed command beyond that deadline or 400 ms; +- publishes a post-operation state with each acknowledgement so an old cached + `controlling=false` snapshot cannot cancel a newly acknowledged arm; +- revokes its owned session on disconnect; reconnect restores observation only. + +Engineering timing is bounded and volatile: one latest video interval and at +most 16 operator timing events in DOM data attributes, cleared with their view. +It contains no SDP, endpoints, credentials, motion values or durable telemetry. +WebRTC interval measurements at the time showed 9–12 ms RTT, 32–62 ms receiver +jitter buffering, approximately 2 ms decode time and no reported packet loss. +These exclude camera capture/SDK and pre-encode delay, so the owner's perceived +1–1.5 second visual feedback delay remains unqualified end to end. + +A distinct 15:25 UTC Core outage was traced to another task restarting the +shared canonical service. It is not evidence against the link and does not +explain earlier failures. Private raw evidence, exact timestamps and checksums +are under `outputs/rover-link-latency-20261016`. The file named +`core-during-speed.jsonl` actually starts after the speed probe completed and +must not be used as simultaneous throughput/control evidence. + +### Socket acceptance — 2026-10-16 + +The canonical local service was restarted with control inactive; health returned +in 17.83 seconds. The final built client was reloaded in the in-app browser. +At 16:01:01 UTC the view had collected 298 state samples over approximately +one minute, with zero stale samples after the first fresh state and no slow +or failed state requests. One 200 ms browser timer interval occurred while +control was inactive; no telemetry dropout accompanied it. Both VESCs showed +live voltage/temperature and no fault, and the preparation dialog's enable +button was available with the existing 30 A limit. The agent did not arm or +move the rover. This qualifies observation/startup only, not driving latency +or long-duration wireless/USB reliability. + +The full frontend suite passed 1132 tests. After the final post-arm cache and +small-buffer correction, 26 focused transport/startup/focus tests passed; +53 Python control/channel/socket tests, TypeScript and the production build +also passed. The final update is Core/client-only; the qualified Node 0.8.49-5 +and VESC 0.7.6 installation was not changed again. Network and OS settings +were preserved. Owner-attended physical input-to-motion and scene-to-display +latency measurements remain outstanding. + +### Hidden desktop control pause — 2026-10-16 + +Historical implementation, superseded below by the owner-requested native +neutral hold. Hidden-page release/reprepare was rejected by the owner. + +After the owner accepted the corrected PWM preparation and stationary hold, +they reported control recovery when returning from another macOS desktop. +A read-only DOM observation in the in-app browser showed hidden-page heartbeat +intervals of approximately 996–1005 ms, versus 100 ms while visible. This is +longer than the unchanged 400 ms control lease. That observer had no active +control and no stale samples among 4053 views. It proves the scheduling +mechanism on this host, not the exact event in the owner's separate Chrome +control window. A subsequent bounded Core trace had 30/30 fresh states and +zero VESC faults. + +The client now explicitly relinquishes the session when its document becomes +hidden, discards held input and retains only the existing in-memory request to +resume. Hidden timers never rearm. Returning to a visible, focused document +requests an immediate state refresh; recovery still requires fresh stopped +telemetry, unchanged identities/profile, confirmed release, no receiver +takeover/fault, and the existing new neutral preparation. A fresh physical +press is required for movement. Ordinary blur still sends neutral without +needlessly ending a visible session. Explicit Stop, page navigation, or reload +cancels resumption; late arm acknowledgement while hidden is retired. + +The existing StatusBadge/LoadingRegion now distinguish “Управление на паузе” +and “Возобновляем управление” from real connection recovery. An observed +telemetry/transport failure clears the background-pause classification. No +watchdog deadline, motor current limit, Node firmware, network setting or +browser energy-saving setting was changed. + +Validation: 42 focused control/recovery/input tests, all 1143 frontend tests, +4 architecture checks, TypeScript and production build passed. The final +client was loaded from the canonical 8000 service without restarting Core. +Browser observation collected 152 fresh samples without a stale transition; +normal and expanded view plus Escape were checked without arming. Physical +hidden-desktop resume and input-to-motion latency remain unqualified. Private +evidence is under `outputs/rover-background-pause-20261016`. + + +### Preserve prepared control across desktops — 2026-10-16 + +Owner correction: switching a window or macOS desktop must clear movement +without ending the already prepared session. Returning must accept a new +physical press without another preparation or connection-recovery spinner. + +The browser explicitly hands its existing socket-owned session to Core in +neutral on blur/hidden. Core's native socket loop generates fresh zero-input +frames every 100 ms while that same owner socket and fresh board telemetry +remain available. It cannot repeat or extend nonzero input. Browser intent +sequence and outbound frame sequence are separate, so the first new physical +input after return is accepted within the same session after any number of +native neutral frames. Internal hold metadata is excluded from the Node wire +contract. Observation, Node reads and a second operator cannot claim a hold. + +All commands still have the existing absolute deadline, at most 400 ms. +Maintenance checks expiry before renewal and cannot revive an expired lease. +Socket disconnect, stale telemetry, driver/relay restart, binding revocation, +receiver takeover and the current session's terminal fault/stop retire the +hold. Explicit Stop and page navigation/reload also retire it. Existing +transient-failure recovery remains separate. No motor-current limit, native +output watchdog, controller firmware, Node package or network/OS setting was +changed. No agent-issued physical arm or motion was performed. + +A synthetic socket test withheld every browser command for six seconds while +providing board feedback: the session ID stayed unchanged, all maintained +frames were zero, and a subsequent fresh operator command was accepted without +arming again. Once motion resumed, missing input still expired the lease. +Hook tests cover a five-second desktop absence, lost focus events, late arm +acknowledgement, explicit Stop/navigation and real telemetry loss. Existing +input tests require a new physical press and reject remembered held input. + +Validation: 48 focused frontend control/input/recovery/transport tests and the +focused Python control/channel/socket/stream suite passed. Architecture checks +(4), final TypeScript and production build passed. The full frontend run had +1145 passes and one unrelated map-markup assertion failure: it expects the +exact single class `mission-map__map-actions`, whereas the concurrently edited +map now adds the canonical `nodedc-viewport-controls` class. Those unrelated +files were preserved. Initial typecheck encountered an in-progress simulation +module; the final check passed once that module was available. + +Canonical Core was restarted only after fresh telemetry confirmed stopped, +inactive control and zero current/ERPM on both controllers. The new client +bundle is `app-B4Gm-AzL.js`. Normal and expanded rover views and Escape were +checked in the in-app browser without arming. The owner subsequently confirmed +that, after reloading and enabling control on the stationary rover, leaving for +another macOS desktop for the requested 5–10 seconds and returning kept control +enabled without another preparation. This accepts the stationary desktop-switch +scenario by owner report; it does not establish moving focus-loss latency or +long-duration field reliability. Private evidence is under +`outputs/rover-neutral-hold-20261016`. diff --git a/docs/node/38_SHARED_LINK_BUDGET.md b/docs/node/38_SHARED_LINK_BUDGET.md new file mode 100644 index 00000000..0ece8526 --- /dev/null +++ b/docs/node/38_SHARED_LINK_BUDGET.md @@ -0,0 +1,515 @@ +# Shared Node link budget + +Release status, 2026-10-26: Node75 / VESC 0.20.9 / X4-23 are installed on Rover006. +Node75 corrects selected-video credit starvation under repeated moderate command +age. Full Ubuntu/race/package checks and scoped passive observation passed; +driving/WAN impairment acceptance remains open. Earlier Node72 DEV start/stop, +minimum-rate live view and verified export results retain their original scope. +Detailed release evidence is in the installation ledger and 39_NETWORK_RUNTIME_AB.md. + +The shared regulator was introduced in Node 0.8.49-54, X4 0.1.3-17 and K1 +0.1.15. Node 0.8.49-56 / VESC 0.20.2 add bounded, resumable DEV export in the +same Node/Core stack. Node 0.8.49-58, X4 0.1.3-19, RealSense 0.6.7 and K1 +0.1.16 add producer sizing through that same regulator; qualification and +installation evidence is recorded in the installation ledger. + +## Ownership and routing + +One Go Node regulator owns the board's optional application egress. Critical +rover telemetry and commands never wait for its permits. It does not modify +motor limits, leases, watchdogs, OS routes, VPNs or Tailscale. + +The owner requirement of 2026-10-24 is network-independent operation through +Tailscale. A particular Wi-Fi SSID, physical interface, LAN address, gateway, +operator/board subnet or LTE carrier must not be a product prerequisite or a +persisted workaround. An IP is a current transport locator, never the Node, +Core, vehicle or device identity. Transport reconnection retains the authenticated +binding; it cannot replay expired motion or automatically rearm a stopped session. +The same optional-traffic regulator remains in use after network handover. + +Current scope: mTLS identity is independent of underlay addresses. Pairing +recovery uses previously authenticated tailnet IPv4 observations and can migrate +the Core endpoint without replacing keys. A synthetic heartbeat regression covers +Wi-Fi/Ethernet/cellular interface and private-subnet changes with one unchanged +tailnet identity. This is not physical LTE or roaming acceptance. Discovery of a +new Node tailnet address when every previously reported locator is unavailable +is still outside the implemented recovery scope; see +`04_NODE_CORE_PAIRING_PROTOCOL.md`. Do not describe current recovery as having +passed arbitrary simultaneous tailnet address changes. + +| Sender | Class | Existing carrier | +| --- | --- | --- | +| X4 and RealSense video | video | WebRTC SRTP | +| K1 and RealSense spatial streams | cloud | WebRTC SCTP/DTLS | +| DEV live view/full export | bulk | Existing authenticated mTLS HTTP | +| Large inventory/archive/receipt envelopes | inventory | Same authenticated Node HTTP | + +DEV is capability-negotiated through rover-link. New peers use +`/v1/node/rover-diagnostics` on the same server and certificate/binding checks. +This handler cannot publish telemetry, renew a lease or return motor intent. +Older peers retain their existing transport. Full onboard session recording +is independent of the network view and has no added duration cap. + +## Policy and API + +Installed on Rover 006: Node 0.8.49-67 / X4 0.1.3-20, 2026-10-25: +`{"schema":"missioncore.link-budget/v1","ceiling_kbps":0,"reserve_kbps":512}`. +Zero means automatic useful-demand growth, initially 4000 kbps, with a 100000 kbps +protocol bound. An explicit persisted 1024..100000 kbps ceiling remains authoritative; +existing operator policy files are not silently overwritten. GET/PUT +`/api/network/budget` remains the authenticated configuration owner. + +The same aggregate egress gate now uses weighted water filling with declared +producer demand caps (video/cloud/bulk/inventory weights 7:2:1:1). Unused capped +allocations return to the pool. Idle packet credits may be borrowed within this +optional pool, preserving one packet of donor credit. Producer advice does not +mint permits. Serialized HTTP bodies declare finite demand from their size, +so a small metadata message does not compete as an unlimited continuous stream. +Class bursts remain 4 KiB, aggregate burst 16 KiB; each permit +admits at most 2048 bytes plus a conservative 256-byte overhead allowance. + +During control the reserve is at least the configured 512 kbps and at least +1.5 times observed offered critical traffic. During confirmed observation it is +at least 64 kbps and the same measured critical requirement. Unknown/stale mode +(older than two seconds) restores full protection. Before the first local intent +optional accumulated credits are cleared; command leases/expiry/watchdogs are +unchanged. Serialized telemetry bytes and overhead are counted without pacing +critical requests. These counts are offered bytes, not physical wire measurements. + +The optional send budget reacts to sustained bad exchanges in a two-second +window or three consecutive transport failures, rather than every outlier. +The baseline is the rolling minimum of up to 320 samples / 30 seconds. A +negotiated Core dispatch duration is subtracted; application/clock errors do not +become congestion evidence. The residual still includes local scheduling and +unmeasured server/transport work: it is not a one-way network-delay measurement. +Healthy windows allow bounded useful-traffic growth every two seconds (20% or +128 kbps), up to declared demand / explicit policy. Individual outliers do not +reset recovery. No dummy probe traffic is generated. The result is an adaptive +SEND BUDGET, not a certified capacity estimate or replacement for WebRTC feedback. + +The control runtime continues to use its existing independent delivery deadlines. +No OS qdisc, route, VPN, Tailscale or radio configuration is changed. All ordinary +policy/decision observations remain bounded in RAM; the local budget socket's +GET `/events` returns at most 32 rate decisions. No telemetry history database. + +The local `/run/mission-core-node/budget.sock` provides POST `/permit` +and GET `/status`, plus POST `/producer` for expiring video/cloud sizing leases. It is 0660 in a 0750 directory for the existing +mission-core-node service group. It grants no administrative/device authority; +admin.sock remains 0600 and the Node state directory 0700. + +Core includes `link_budget` in a fresh rover view when supported. It reports +configured/effective/optional rates, baseline RTT and per-class granted bytes +and deferrals/active producer counts. Stale observations do not masquerade as current budget state. + +## Sender behavior and bounds + +The shared Python SDK adapter is pinned to aiortc 1.14.0. It gates encrypted +application datagrams and retransmissions at the existing ICE send boundary. +Small handshake/RTCP feedback is exempt to avoid deadlock. RTP awaits permits +inside its existing sender; SCTP uses one bounded FIFO per transport (64 +packets/64 KiB, max queued age 0.5 s). A missing budget service, overflow or +expired admission closes that media peer; it never silently sends unbudgeted +data. Local capture and recording retain their independent lifecycle. + +A direct await in SCTP's sender was rejected by real RRD loopback qualification +because it allowed reentrant DCEP flushing. The bounded queue preserves its +immediate-enqueue contract. The new RTP pacing-age bound is described below; it +is not a capture-to-screen latency guarantee. + +Node HTTP pacing uses cancellable reads of at most 2 KiB, without control locks. +Node 0.8.49-59 isolates inventory from small DEV polls inside this same regulator. +Paced request deadlines are 8 seconds plus 1.25 times the packetized upload cost +at the minimum per-class rate (128 kbps optional / sum of all weights). Both +inventory and DEV use this size-dependent bound; there is no session duration cap. +General HTTP response headers retain their separate 8-second network timeout. + +During a full snapshot upload, a <=2 KiB `/v1/node/liveness` request runs every +5 seconds on the same mTLS server and binding, through a second connection of +the existing HTTP client. Full snapshots remain single-flight and cancellable; +no second transport stack or command queue is introduced. Cancellation joins the +upload; endpoint/binding changes cancel it. Older Core may return 404; the original +full heartbeat still works. Deploy Core before the new Node for presence support. +Core stores liveness only in bounded RAM (256 entries, 20-second admission expiry). +It neither saves inventory nor acknowledges operations or renews motor leases. +`link_last_seen` identifies connection presence; `last_seen` remains the full +inventory timestamp and `inventory_fresh` is separate, including agent restarts. +A slow snapshot must not be described as fresh just because liveness arrived. + +DEV live rows have a 12 KiB allowance; one negotiated 64 KiB export block has +its own bounded allowance. The diagnostics endpoint accepts at most 112 KiB; +the critical telemetry/control endpoint is unchanged. Newest fitting event +rows are selected for the live view, gaps remain explicit, and full rows stay +on the board. Legacy peers retain 4 KiB export blocks. Node sends a block once +after a successful HTTP response and retries failed exchanges. Status polls +continue while the next offset is being prepared. + +The board fixes a byte length and file-generation snapshot for each export, +with capture/token/offset/total validation and SHA-256 per block. Core verifies +blocks and prefetches at most one next block; current plus prefetched raw data +is at most 128 KiB. No complete log cache is created on Core. Disconnecting +the HTTP consumer cancels a blocked wait without cancelling a newer transfer. +A Core restart can rediscover the paired board's closed file without enabling +recording. + +The existing save dialog streams verified data to the selected JSONL file. +The browser confirms an offset only after a successful write, then resumes +that exact capture/snapshot after a failed connection (four attempts with +1/2/3-second backoff). A 130-second no-progress timeout applies per attempt, +not to session duration. A changed capture, truncation or corrupt chunk cannot +silently complete. Browsers without File System Access use their native raw +streaming download; they do not get application-managed automatic resume. +Core still verifies raw download blocks and supplies Content-Length. + +The first 4 KiB implementation required about 210 seconds for 996,124 bytes. +The initial 64 KiB implementation took 126 seconds; its repeated, already +acknowledged blocks prompted the Node 56 suppression fix. Node 56 completed the same file in 61.14 seconds, and a second transfer +with an intentional client disconnect/resume in 61.75 seconds, with live X4 +video. Both matched the onboard SHA-256; 238/238 observation checks were +fresh with no poll errors. These timings are one Wi-Fi acceptance sample, +not a minimum throughput guarantee. + +## Adaptive producers + +Private `/producer` admits at most 32 process-owned identifiers with three-second +leases. New SDK producers declare their maximum useful demand (`demand_bps`); +legacy producers receive bounded defaults. Weighted, capped allocation redistributes +unused declared demand. Within a video class with insufficient useful shares, +the oldest live viewer retains admission; additional viewers receive zero and +wait without closing capture/recording. This is a deterministic fallback, not an +operator-selectable primary-camera policy. Expired viewers release admission. + +The SDK follows Node's bitrate allocation without the former second five-second +hold. Encoding uses 65% of the wire allowance. Spatial profile increases require +two stable seconds; reductions apply immediately. In observation, the profiles +trade FPS before detail: 1280/15, 1280/8, 960/6, 640/4, 480/2, 320/1. +During control the existing latency/FPS profiles remain: 1280/15, 960/12, +640/10, 480/6, 320/4, 160/2. The source preview still has a qualified 1280-pixel +maximum; raw camera acquisition and recording are unchanged. Zero allocation +pauses a disposable preview without restarting its device. The existing viewer +waiting state accepts this hint for three seconds, then expires it. Resumption +has one bounded first-frame grace period; repeated hints cannot conceal a true +source stall or disconnected peer. + +New Core replies announce pending DEV work with one boolean on the existing +telemetry exchange. A capable idle Node sleeps its optional diagnostics lane; +capture, closing-tail and export wake it. Reconnection retains a discovery poll +and older Core peers retain their original polling contract. This hint acquires +no optional recorder/export lock and carries no diagnostic rows or motor authority. + +RTP pacing now bounds each whole frame from its first paced packet. Fragments +older than 500 ms are discarded, including subsequent late fragments and older +timestamp retransmissions; an in-flight permit RPC can add up to its existing +500 ms socket timeout. The next frame may proceed, and a keyframe is requested +without closing capture/recording. Current sender metrics include actual encoder +time/target, receiver bitrate feedback, expired-frame count and permit waiting. +These are bounded per-peer observations independent of DEV. + +The pinned aiortc 1.14.0 adapter caps each actual H.264/VP8 encoder, including +below aiortc's stock minimums, while retaining the codec's normal receiver REMB +min/max/start policy. REMB does not set resolution/FPS: quiet scenes can have +low observed throughput even on a healthy channel, and feeding that observation +into size/FPS produced a feedback loop in the rejected Node57/X4-18 candidate. It does +not alter codec globals or other peers. Changing aiortc requires requalification. +RTP pacing remains authoritative during bitrate transients. + +K1 coalesces decoded latest frames before encoding its disposable view and +samples point/color/intensity channels together, retaining provenance. Point +count and publication interval follow the current allocation. Existing encoded +RRD batches remain ordered and resumable; raw records are not decimated. +RealSense similarly bounds point count and sends at most a 16 KiB JSON message. +SCTP application producers check both the channel buffer and the budget FIFO +before adding more messages. K1's already encoded native camera fragments still +use bounded pacing; this increment does not transcode that camera. An absent +K1 camera leaves its channel idle rather than resetting SCTP during admission, +so the RRD channel remains independent. + +## Verification and limits + +Go tests cover aggregate limits, class non-starvation, policy persistence, +cancellation and adaptation. Core tests cover authentication and separation +from telemetry/control authority. SDK/media tests exercise RTP and actual RRD +loopback and bounded failure behavior. Ubuntu packaging and service closure +are qualified separately from physical acceptance. + +Live acceptance with X4 video and DEV on Rover006 had 619 telemetry exchanges +without transport error and 220/220 fresh observation checks across three +intervals. 47 checks occurred during the full-file export. The export matched +the onboard SHA-256 and its footer reported zero dropped records. No motor +commands were sent. See the installation ledger for identities and scope. + +This limits integrated Mission Core senders, not all OS traffic or the +operator's LTE network. It does not control SSH, guarantee packet delivery, +or regulate the native K1 camera encoder. Worker 006 synthetic qualification exercises the production budget, bounded +HTTP pacing and command admission together, including one forced bulk +connection loss, virtual command delays up to 700 ms and old-session replay. +The final run admitted 2,800 fresh commands, rejected 1,400 expired commands +and 4,200 old-session replays, and completed three 64 KiB bulk transfers after +one injected disconnect. Command-state access p99 was 3 microseconds; this +is function-call timing, not end-to-end command latency. The temporary +container was removed. This is not a real WAN/WebRTC benchmark. Live K1 and RealSense traffic, actual +network loss/jitter, hour-long sessions and powered driving remain separate +acceptance gates. Future cameras/plugins must opt into the +same SDK budget; they must not create a competing regulator or transport stack. + + +Adaptive-media acceptance on Node 58/X4 19: the same physical X4 peer retained +1280×640 through 96 seconds of a quiet scene (11–12 fps measured), changed to +640×320 at 9.5 fps while three additional admission-only video leases shared +its budget, and recovered to 1280×640 at 12.5 fps after their release. Six +receiver interval samples reported zero lost packets, dropped frames and +freezes; these are sampled two-second intervals, not an all-session guarantee. +The probe produced no packets and is not a multi-camera load qualification. +One browser video continued to supply all three X4 lenses. The policy remained +4,000 kbps with a 512 kbps reserve. + +All 209 Core observation polls succeeded. The first poll retained an older +CAN sample when observation resumed; it is excluded from per-device freshness +acceptance. All subsequent 208 polls contained both VESCs with age at most +432 ms, no VESC fault, zero ERPM/duty/battery current and control disabled. +The temporary peer and all three probe leases were released. This adds short +passive Wi-Fi acceptance only; the physical-cloud, real WAN, long-session and +powered-driving gates above remain open. + +## Heartbeat/DEV floor regression, 2026-10-24 + +An isolated Worker test reproduced the old 8-second failure: a 40 KiB heartbeat +sent only 12 KiB alongside video, and zero bytes with frequent 400-byte DEV polls +sharing its class. Additional deterministic coverage proved floor-congestion +reports cannot reset progress indefinitely. With the Node 59 changes, real +loopback HTTP delivered 41,226 bytes in 31.94 seconds under concurrent video, +cloud and DEV permits at the floor. Seven liveness exchanges continued with a +maximum 5.002-second interval, and DEV progressed. The existing Worker control +state test still rejected expired/replayed synthetic commands. This is a software +qualification without devices, not acceptance of an LTE carrier or an explanation +of every prior motor jerk. Evidence: `outputs/heartbeat-dev-20261024/`. + + +## Local command delivery — Node 0.8.49-61 + +The existing 20 Hz Node delivery tick always checks the current intent deadline, +clock bound and stop revision first. A session/sequence successfully accepted by +the local VESC service is sent once; the following unchanged ticks do not repeat +that private RPC. A newer sequence still goes immediately through the same socket. +Skipping a duplicate does not extend its lease, update a telemetry timestamp or +produce a new device sample. Stop/expiry still sends null intent. Failure to send +a new intent or a stop remains terminal; there is no command replay queue. + +This removes a reproduced failure where a redundant local send exceeded its +25 ms deadline and retired an already delivered, still-valid command. It does +not relax that deadline, the 400 ms input lease or the native output watchdog. +DEV adds the private RPC phase/timing and delivery_mode to the existing trace; +expanded trace remains opt-in. The physical cause of intermittent measured duty +during steady operator demand remains unconfirmed. Qualification and deployment +are recorded in the installation ledgers. + +## Core diagnostic dispatch isolation — 2026-10-24 + +The dedicated DEV endpoint now releases the binding/channel lock before ingesting +optional records or preparing an export response. Previously the outer channel +lock still serialized this work with telemetry, observation, command delivery and +revocation, despite the separate HTTP connection and inner control-lock release. +Two gated regressions reproduced that dependency without hardware or load. + +Admission captures the current binding's diagnostics object under the existing +authentication lock. Optional work uses that object outside the channel/control +locks. Before returning a reply, Core rechecks certificate, binding, endpoint and +object identity. A concurrent revocation cannot be blocked by DEV, publish a stale +reply, recreate a forgotten board or revive motion. The legacy inline transport +is retained; this isolation applies to the negotiated dedicated endpoint. + +DEV additionally records `node_telemetry_handled`: exchange count, maximum Core +dispatch duration and reply monotonic timestamp, aggregated at most once/second. +The measurement excludes request-body transfer and response transmission; compare +it with Node's HTTP trace. It never refreshes telemetry or a control lease, and +does not record endpoints, credentials or request bodies. No diagnostic rows are +added when DEV is off. + +The final Core change passed 225 fleet tests and was loaded by restarting only +the canonical Core service. A 75-second stationary observation with actual X4 +egress and DEV on/off returned 75/75 fresh views; 348 sampled Node HTTP exchanges +had median 15 ms and maximum 193 ms, while 34 Core timing reports reached at most +0.616 ms. All observed ERPM and native output counters were zero. The onboard DEV +file closed with 1,376 written records and zero dropped. This is bounded passive +acceptance, not proof of stable WAN driving or a cause for every earlier jerk. +Later the board became unreachable on both its overlay and physical endpoint; +SSH also timed out. The operator subsequently confirmed a board restart for +that outage; it is not evidence of a Core process failure. +Private evidence and unresolved questions: `outputs/rover-link-delay-20261024/`. + +### 2026-10-25 runtime acceptance + +Node 67 and X4 20 were installed by owner release `0ef1173f23ce64ab48255f00`. +All 24 Ubuntu Node jobs and 125 X4 package tests passed; local Core/SDK checks +passed 63 tests, and frontend typecheck/1344 tests/production build passed. +Both installed SDK copies match the qualified source hashes. CAN admission +barriers were safe, `motor_commands=false`, and observation was restored. + +A bounded 241.76-second passive observation had 120 API samples, no HTTP errors, +and 118 fresh telemetry observations. Automatic send budget remained 5660–5673 +kbps, above the former 4000 default ceiling. Idle DEV bulk bytes did not grow. +The browser received one shared 1280×640 stream for all three X4 views, with +11–11.5 decoded FPS in sampled receiver intervals and zero interval packet-loss, +dropped-frame or freeze deltas. These are stationary observation samples, not +movement or saturated-link acceptance. Normal and expanded views were inspected. + +Two nonconsecutive telemetry checks at 14:17:17/21 UTC were stale, with fresh +checks between and after them. The Node journal records `cancelled` and +`network_timeout` stream reconnections; this evidence does not establish the +underlying cause. Do not claim the network interruption problem resolved by this +quality/runtime change. No physical handover or control-on exercise was performed. +Detailed private evidence: `outputs/network-runtime-20261025/REPORT.md`. + +### Command-stream pressure feedback (introduced Node68, corrected Node70) + +The optional Node-egress gate also observes the authenticated command stream, +independently of telemetry RTT. During control, a 150 ms receive silence, +inter-frame gap or conservative Core-clock age upper bound closes optional byte +admission and clears burst credit. The existing local tick detects silence even +while the stream reader waits. Continuous fresh frames for 200 ms reopen +optional traffic at the current estimate; an instantaneous buffered burst cannot +reopen it. Continuing pressure for 200 ms is required before a capacity reduction, +still at most once per second. A fresh receipt resets that backoff evidence. +An isolated jitter sample yields bytes immediately but neither cuts the estimate +nor erases the independent exchange estimator's recovery progress. The ordinary +bounded demand probe then recovers quality. Telemetry success alone cannot +reopen this gate. Idle +observation does not invoke this command-pressure policy. + +This changes optional admission only. Command expiry, the 350 ms stream read +watchdog, local driver timeout and native output watchdog remain authoritative. +No expired session is replayed or automatically rearmed. The frame-age value is +a conservative clock bound, not a measured one-way network latency. Bytes +already transmitted/queued and Core egress are outside this gate's control. + +DEV receipt and delivery-stop records distinguish Core writes, Node receipt, +retired input and driver delivery. Normal live health exposes bounded command +pressure state without retaining per-frame history when DEV is disabled. +Qualification evidence: `outputs/network-runtime-drive-20261025/`. + +Node68 passive acceptance confirmed the new receipt evidence and clean DEV +closure, not uninterrupted command delivery: two stationary captures still +recorded stream timeouts while telemetry mostly remained fresh. A board-side +packet capture showed 424/496 ms receive gaps and, separately, newer TCP segments +waiting for a missing earlier segment. Optional traffic backoff cannot promise +to repair an underlay interruption or remove TCP ordering. The active-control +policy has regression coverage; its physical-drive effect remains unaccepted. + +### Terminal faults and closed observation (Node69) + +Network priority follows actual remote-control ownership, not a status label. +The VESC snapshot reports `control_active` while its input lease or control +worker (including cleanup) is live. Node combines this with current Core/Node +intent. Legacy terminal `fault`, `stopped`, `observing` and `receiver` states +are inactive; an unknown legacy projection remains conservative. A confirmed +inactive update clears old command-pressure state. Closing observation +intentionally closes the stream and must not starve equipment heartbeats. +Active-control silence still suspends optional egress under the same deadlines; +there is no inventory bypass around the shared budget. + +A missing-device preflight that never reached motor ownership has a separate +read-only availability reconciliation. It requires the same profile and bound +physical UUIDs, newly verified attachment generations and a continuous neutral +sample window, with no live control/firmware/motor owner or unresolved limits. +It returns the current state to stopped, preserving last_stop history and +retired input IDs. It does not fabricate a previous release ACK or rearm motion. +The observer runs during this pending check even with DEV and the observatory +closed. This covers empty/partial device discovery, which previously could +leave a fault with no reconciliation candidate. + +Qualification and installation status: private engineering evidence in +`outputs/vesc-inventory-recovery-20261025/`. This change does not establish the +cause or resolution of earlier physical CAN read timeouts or network outages. + + +## 2026-10-25 — valid optional-media denial is not transport failure + +The media payload deadline (500 ms) was shorter than Node68/69's command-pressure +recovery window (1 second); sustained pressure can still exceed it. A valid denied permit must expire the +payload, not close its WebRTC peer. X4 package21 consumes the shared SDK contract: +expired RTP frames request a clean keyframe and late fragments stay expired; +expired SCTP datagrams are discarded in the existing bounded queue. There is no +unbudgeted media fallback and no buffering of imagery across a policy pause. +Broken/malformed budget-service responses, queue overflow and real ICE failure +retain peer retirement. Local capture and recording are independent. + +The focused regression previously failed with Media egress budget unavailable. +The X4 Ubuntu qualification now exercises real loopback ICE/DTLS/SCTP and resumed +frame decoding after 1.3 seconds of denied permits on the same peer. Deployment +and observed scope are recorded in the installation ledger and private evidence +`outputs/rover-camera-link-20261025-2010/REPORT.md`. The underlying cause of the +owner's earlier TCP interruptions is not established by this correction. + +## 2026-10-25 — isolated command jitter must not collapse video capacity + +The owner's next drive exposed the excessive Node69 reaction: receipt-only +replay of 1,386 active-session frames kept optional admission paused for 74.4% +of 58.1 seconds. Single-sample reductions alone reached the estimate floor. +Node70 separates immediate yielding, fresh-flow recovery and sustained-pressure +backoff as described above. The same receipt replay gives 26.6% paused and no +estimate loss from this branch. This is a policy reconstruction, not measured +historical bandwidth; the exchange estimator and local silence ticks are +qualified separately. Physical-drive quality and the underlying delivery stall +remain acceptance items. No command expiry, motor settings, reserve or rearming +rule is relaxed. + +DEV adds one budget snapshot per second in the optional local recorder loop; +normal operation adds no per-frame history. A rebased receipt-only regression +fixture contains no UTC, device identity, command values or location. Go tests +exercise the production gate with independent virtual watchdog ticks, sustained +silence, old bursts and recovery without estimator collapse. Private evidence +and deployment status: `outputs/rover-drive-20261025-2134/REPORT.md`. + + +## 2026-10-26 — prepared Node71 / X4-22 contract + +- DEV starts through a Core modal with local event recording by default. Strict + capture options independently enable live rows and Core/browser trace, with + 8/16/32/64 kbit/s event limits. Short lifecycle metadata still crosses the + network; full files remain on board and use the existing verified export. + Metadata-only diagnostics use bounded inventory capacity; event rows/export + use bulk. The optional diagnostics poll is one second. Queue bytes/records, + drops and out-of-band close are explicit. +- A single 500-ms absolute deadline covers lock, async Unix IPC, permit wait and + send. Expired SCTP datagrams are removed before waiting; RTP fragments share + their frame deadline. Transient IPC/refresh failure and queue pressure discard + disposable payload without retiring the peer. Malformed policy remains terminal. + The last allocation is valid only until its original TTL. This bounds admission + age, not capture-to-screen latency or the age of reliable SCTP application data. +- Protocol-only DTLS/RTCP bypasses payload backlog with a 2-KiB/s allowance and + 8-KiB burst per transport. There is no caller-controlled payload exemption. +- Explicit primary video leases are operator-selected, latest selection wins, + expire after three seconds and do not mint packet credit. Finite metadata gets + at most 32 kbit/s; selected video precedes residual cloud/export capacity. + Without an explicit primary, the prior weighted/oldest-view policy remains. +- The existing 150-ms command-pressure response permits only the explicit primary + video at <=384 kbit/s. At 250-ms command gap/age/silence all optional payload + yields. Motor deadlines and authority are unchanged. This new low-video policy + has virtual/race regression coverage, not new physical-drive acceptance. +- Capability-negotiated full budget summaries run at 1 Hz; Core retains them for + <=2 seconds with age separate from actual motor sample freshness. H.264 RTP + payloads are <=1100 bytes using per-sender NAL/FU-A packetization; actual codec + and depayload roundtrip tests cover pinned aiortc 1.14.0. No overlay MTU or + packet-loss field acceptance is implied. +- X4 retains the last rendered image and shows last-presented-frame age on an + interruption. Decode progress cannot update presentation time. Preview roles + are sent only to devices advertising their support. + +Detailed implementation and limits: `../audits/2026-10-26-network-runtime-and-dev.md`. +Package/installation evidence: `07_INSTA360_X4_INSTALLATION_LEDGER.md` and private +`outputs/network-dev-20261026/REPORT.txt`. No second transport stack is introduced. + +### Installed correction, Node75 · 2026-10-26 + +Repeated moderate command-age samples now preserve credit for the selected +low-rate video profile. Credit is discarded on the transition into pressure, +with the refill anchor advanced to prevent pre-pressure time restoring it. +Previously clearing every 50 ms could starve an 1100-byte datagram indefinitely +at 128 kbit/s optional allowance. The deterministic two-second regression changes +from zero to 25300 admitted payload bytes within the unchanged aggregate budget. +Emergency yield at 250 ms, background admission, motion leases and stop rules are +unchanged. Full Node units and isolated kernel-shaped/60-second contention tests +passed. Node75 subsequently passed all 24 Ubuntu stages including race, 431 VESC +tests and a two-minute passive hardware/browser check. Command-pressure behavior +on a physical drive remains unqualified. Detailed scope and telemetry tails: +`39_NETWORK_RUNTIME_AB.md`, private `outputs/network-contention-20261026/` and +`outputs/network-release-75-20261026/`. diff --git a/docs/node/39_NETWORK_RUNTIME_AB.md b/docs/node/39_NETWORK_RUNTIME_AB.md new file mode 100644 index 00000000..ac8ca172 --- /dev/null +++ b/docs/node/39_NETWORK_RUNTIME_AB.md @@ -0,0 +1,1127 @@ +# Network runtime A/B qualification + +Scope: remote Core ↔ Node through the admitted external path. Shared LAN, +SSID, proximity to an access point, or a local-address shortcut are not acceptance +criteria. No motion, arming, calibration, controller configuration, or firmware +commands belong to this qualification. + +## Earlier incident evidence, 2026-10-26 08:48 MSK + +The reported drive failures are not yet a closed field incident. In the bounded +journal window containing the operator's drive, 70 stream disconnects were +recorded (42 deadline, 24 cancellation, 4 network timeout). Local delivery kept +running: maximum observed inter-cycle gap 64 ms and driver exchange 9 ms. +Telemetry exchanges reached their 2 s deadline, with a maximum gap of 25.964 s. +These are different lane clocks; old `at_ms` values cannot be compared directly. +The UTC reconstruction is approximate and explicitly separated from the new +common-origin timeline. + +A separate 90 s passive capture overlapped operator control. Node CPU p95 was +7.75%, VESC 26.52%, and X4 broker 82.08% of one CPU, with no material cgroup +throttling. This does not establish CPU saturation as the cause. The agent did +not originate those control sessions. + +A later 120 s stationary capture had no control sessions and did not reproduce +the drive failures. Its verified export contains 8,996 events, zero dropped +records, and all 2,199 Core records acknowledged by Node. The SHA-256 of the +4,619,322 byte JSONL is +`a52062544f439bef13fe439ffd1635e80f7c5d6326e84b9a291e11f22bd50631`. +On the external path it observed: + +| Quantity | p95 | Maximum | +| --- | ---: | ---: | +| Core command-frame generation gap | 75.96 ms | 148.45 ms | +| Node command-frame receipt gap | 123.12 ms | 191.53 ms | +| Conservative received command age | 122.52 ms | 191.38 ms | +| Core command dispatch | 0.44 ms | 1.77 ms | +| Core telemetry dispatch | 0.87 ms | 2.34 ms | +| Node telemetry round trip | 130 ms | 249 ms | +| Node ↔ local driver exchange | 2 ms | 7 ms | + +2,078 frames were matched using the exact Core frame-clock value, not receive +order or cross-machine wall-clock subtraction. Raw evidence and hashed lossless +archives are private under `outputs/network-runtime-ab-20261026/`. + +## Implementation under qualification + +- `missioncore.rover-timeline/v1`: relay epoch and common monotonic origin for + local delivery and telemetry, explicit release `null/false/true`, terminal + state/reason, bounded post-retirement window, and indexed incremental ring + emission. Ordinary state flapping is limited to one report per second; stop, + terminal state, stage and release transitions remain prompt. +- Negotiated `rover_details_v1`: send static profile/presentation metadata at + change, reconnect and one-second refresh. Every measurement, measurement age, + attachment session, authority and current release result remains in each live + frame. Core admits a revision only for the same relay/driver identity and + matching device roster. The installed Node74/Core correction retains one immutable + revision per identity; network delay no longer expires static labels/profile. + Live sample clocks and the one-second freshness deadline remain independent. + Missing, conflicting or malformed metadata cannot renew telemetry or control. + Older peers retain the full-snapshot protocol. +- Fixed-bin, bounded encoder/admission measurements expose actual encode time, + per-packet IPC time, permit-lock waiting, denial/failure counts, producer + identity and last codec recreation. These measurements do not authorize a + second budget or imply measured network capacity. +- RTP retransmissions using RTX share the primary SSRC's frame deadline and + timestamp ordering. Retransmission cannot give an expired frame a new 500 ms + lifetime. Timestamp wrap remains admitted. The existing absolute deadline + includes permit wait, IPC and actual datagram send. +- VESC retains a bounded immediate release-readback record in `last_stop`: + per-controller send result, neutral/non-neutral/invalid reading or read + failure, error class, and finite current/duty evidence. This changes no motor + command, threshold, wait, watchdog, lease, latch or re-arm rule. +- Existing video element exposes only the current bounded server diagnostic + projection in `data-preview-runtime`, beside interval receiver metrics. + It uses the existing peer/data channel and keeps no history. Three X4 panes + continue sharing one video transport. + +## Release truth and authority + +| Observation | Current release | Meaning / authority | +| --- | --- | --- | +| New session, preflight, no output/readback yet | `null` | Unknown; never inherit a previous success/failure | +| Immediate readback satisfies existing current/duty limits | `true` | Readback confirmed; no automatic new control session | +| Read timeout, invalid or non-neutral readback | `false` | Preserve stop/fault and exact reason; never fabricate ACK | +| Three matching, fresh neutral observations spanning ≥0.5 s | `true` | Existing passive reconciliation only; latch/retired lease remain | +| Historical `last_stop.release_confirmed=false`, current `true` | independent | Preserve history plus recovery time; old fault is not current torque proof | + +The previous incident did not retain raw cleanup readback. Its precise immediate +release-failure cause therefore remains unproved. A later neutral observation is +not retrospective proof that the original read succeeded. + +## Qualification gates + +Completed before installation: 429 VESC tests; compact-metadata/sample-age/Core +channel regressions; 19 SDK deadline/codec/accounting tests including RTX; +19 focused viewer lifecycle tests; frontend typecheck/production build. +X4-23 completed 127 Ubuntu cold-runtime/package tests, including real H264, +DTLS and loopback UDP with 3 ms per-datagram delay, packet loss and a 650 ms +send stall exceeding the frame deadline. The same peers recovered, old media +expired, queues stayed bounded and encrypted RTP plus IPv4/UDP headers stayed +within 1,280 bytes. This controlled loopback impairment is not a WAN or driving +acceptance test. + +## Node73 installation and passive baseline, 2026-10-26 + +Node 0.8.49-73 / VESC 0.20.9 and X4 0.1.3-23 are installed through their +versioned owner releases. Node source `1d61b0e87f85472f23ee5f9f` passed all +24 Ubuntu jobs including Go race detection and VESC tests. Owner release +`9231e3f01fbba756513567f8` installed at 07:18:47–07:19:09 UTC; both CAN +admission barriers were safe, observation was restored, and the installer +reported `motor_commands=false`. Eleven installed payload hashes, including +the compiled Node, VESC release implementation and shared SDK, match the +qualified Debian package. X4 source `d11576ab51ba5644b107a4b6`, owner +`aaebb3008465aecb2a4bcd13`, was installed at 07:04:59–07:05:20 UTC; +its installer verified two real H264 frames at 2880×1440. Existing prepared +Ubuntu acceptance does not qualify a clean OS. + +The passive matrix ran 07:21:27–07:27:49 UTC: seven 15-second observation +windows, with recording-tail drainage between windows. No second video peer, +arm, control lease, motion or controller-setting operation was created. +All 210/210 Core samples were fresh and both controllers remained at zero ERPM. +Per-device sample age is separately reported below. + +| Phase | Device-age p95 / max, ms | Complete log events / drops | Start through file-close, s | +| --- | ---: | ---: | ---: | +| Baseline | 399 / 452 | — | — | +| Local only | 436 / 494 | 871 / 0 | 17.1 | +| Core trace 8 kbit/s | 409 / 458 | 1057 / 0 | 135.4 | +| Live 8 kbit/s | 434 / 449 | 845 / 0 | 17.1 | +| Core + live, 8 kbit/s each | 385 / 404 | 1107 / 0 | 136.2 | +| Core + live, 64 kbit/s each | 465 / 490 | 1109 / 0 | 46.1 | +| Baseline repeat | 401 / 414 | — | — | + +The final combined log was exported through the normal chunked API. All +offsets, snapshot identity and block hashes were verified: 586902 bytes, +SHA-256 `2173e24b15fffbf710b9d3942d8b9fc1bc137cf0db7d0fc5602b7a9a685fc299`, +1109 events plus manifest/footer, no dropped records. Stop ends acquisition; +a small Core-trace rate intentionally takes longer to deliver its accepted tail. + +In that 15-second log, Node request size median/p95/max was 2165/3617/3624 +bytes. The earlier 120-second Node72 log was 2920/3816/3827 bytes: median +approximately 26% lower. These are different real intervals, not a controlled +network-capacity comparison. New JSON marshal p95/max was 0.124/0.290 ms; +Core processing 0.706/1.893 ms; local-driver exchange 2/6 ms; Node telemetry +RTT 131/201 ms; command receipt gap 130.322/161.710 ms and conservative +command age 124.346/150.763 ms. All 142 telemetry exchanges succeeded. + +Over 422 seconds bracketed by browser runtime snapshots, the same producer, +peer and camera generation remained. There were 4595 encoded frames and +43200 admission requests: mean encode 8.721 ms (p95 bin ≤16 ms), mean IPC +0.229 ms (99.88% ≤1 ms), mean lock wait 0.007 ms, and zero IPC failures. +These measurements do not justify replacing per-packet IPC with a new grant +protocol for this observed workload. Revisit for higher producer count/rate or +measured contention; do not create a second budget owner. + +There were also 8 additional expired frames, 363 stale RTP drops and 10 codec +recreations, with no queue/protocol drops or peer closure. The sparse browser +snapshots and short active captures do not establish the cause of each event. +Node/VESC had zero cgroup throttling in the seven windows. X4 throttling was +0–340 ms per window, largest in the repeated baseline; therefore the matrix +does not establish DEV as its cause. Do not describe this as zero media stalls +or as proof that the driving incident is resolved. Receiver jitter-buffer +figures are not capture-to-display latency. + +## Node74: recorded 10:52–10:54 MSK drive and follow-up + +The later operator recording contains 7013 events, zero dropped records and a +complete footer (3744636 bytes; SHA-256 +`8f055827a2eed306f54d6490a140d169d91405c4cf4775ca26109cef8423f82d`). +The first stop follows the last fresh stream frame at 07:53:09.839294 UTC: +VESC lease expiry at 10.166698, release sends at 10.171/10.172, stream guard +at 10.1899. Immediate readbacks at 10.484/10.485 show motor currents +1.1 A / 2.38 A, duty zero, ERPM 539 / 429, fault zero. Those readings do not +satisfy the existing ≤1 A release criterion. At 11.815 the existing passive +reconciliation confirmed neutral after four fresh samples spanning 677 ms. +This explains that warning without weakening the criterion or erasing history. + +This first command gap precedes the three HTTP400 responses. Five later stops +are `core_withdrew_command`; the Core/browser trace was disabled, so their exact +Core reason is not retained. The separate network/host source of the initial +command blackout remains unproved. Metadata and clock defects must not be +presented as proof of the initial blackout's cause. + +Node74 corrects the observation lower-clock bound: a delayed HTTP reply cannot +erase a tighter authenticated stream/response bound. It advances the previous +bound with the existing 1000 ppm conservative drift allowance, resets on epoch +change and preserves the original measurement time. Command upper bound, +clockSeen, lease, guard, stop barrier and authority are unchanged. Static +metadata now retains one immutable revision for the same relay/driver identity; +all live expiry, revision, roster and identity checks remain separate. + +For explicit export while observing a selected primary camera, bulk receives +at most 32 kbit/s and 1/11 of the same optional budget. Active/stale control and +command pressure retain primary priority. A 640-kbit/s floor regression always +requests video first, completes 108 KiB bulk and 40 KiB inventory within the +existing timeout, verifies the shared cap and active-control bulk allocation zero. + +Source `a8251db0db45a59e12c13498` completed 24 final unique Ubuntu stages, +including Go race and VESC. The first dependency attempt timed out; its shipped +retry completed. Local Python regressions: 61 passed; changed Python Ruff pass. +Owner `bdb8cd18e05ff33f29f7ce37` installed Node 0.8.49-74 at +09:14:45–09:15:06 UTC. Both CAN barriers were safe, observation restored, +`motor_commands=false`. Eleven installed payload hashes matched qualification. +VESC 0.20.9 and X4-23 remain. Core8000 was activated through its existing +LaunchAgent, after confirming control inactive and recording closed. + +With the existing primary camera open, the original recording's first 64 KiB +export block arrived in 5.94 s; disconnect/resume delivered the next in 5.09 s. +Offsets, snapshot, SHA and exact bytes matched the original. This validates +131072 bytes and resume, not another full transfer of the 3.7 MB original. +A new six-second passive local-only capture fully exported 305 events with +zero drops: 143666 bytes in three verified blocks, 13.68 s, SHA-256 +`363465e8ef4dcff27f313d3e33742f60b755b8ce7a8b715b29be07b4ed95b8ce`. + +Across 120.40 seconds, 109/109 sampled Core views were fresh; no control session +or nonzero ERPM was observed. Device age p50/p95/max: 269/390/614 ms. Sampling +paused during the blocking export, so this is not continuous millisecond coverage. +The short recording has 62/62 telemetry HTTP200, RTT p95/max126/134 ms, +Core processing0.153/0.246 ms, local driver2/3 ms, stream gap129.815/165.598 ms. +These are separate passive intervals, not a controlled before/after drive trial. + +The same video peer/producer/session survived. The final receiver interval was +11 fps, 1280×640, RTT49 ms. Sparse snapshots also show continued expired frames, +stale RTP and codec recreation; continuity is not zero-stall acceptance. No +separate UI fix for the observation-settings timeout is claimed by this release. + +Private evidence: `outputs/network-runtime-1052-20261026/REPORT.txt` and +`evidence.json`. The 116 removed extracted package duplicates were hash-matched +to retained owner archives, reclaiming 10.544 GiB; PAYLOAD_LOCATION.json records +recovery. User captures, source pins, owner/rollback archives and runtime data +remain. The owned Node74 build stage was cleaned by its versioned entry point. + +## Remaining acceptance + +| Audit item | Evidence / remaining gate | +| --- | --- | +| A1 timeline | Common-origin/session/epoch and release evidence shipped and tested; independent local Core/browser capture added and paired without WAN log transfer. Exact transport origin and moving field acceptance remain open; see the operator-host A1 section below. | +| A2–A3 deadline / allocation lifetime | Regression and real loopback UDP impairment pass; old media cannot renew its deadline and transient allocation failure retains only the original cap. WAN field gate remains. | +| A4 primary | Existing hierarchical budget and primary selection retained; simultaneous real cameras/cloud/export under control remains unaccepted. | +| A5 DEV | Seven passive windows and five lossless closed logs accepted; full audit T1–T6 with an operator-confirmed neutral control session remains open. | +| A6 continuity | Viewer regressions/build pass; existing peer survived versioned Node update and the passive matrix. | +| A7 safety | Release null/false/true, readback errors, clock and queue/Stop contracts tested; no watchdog/lease/threshold relaxation or autonomous arm. | +| B load | Freshness/detail shipped; JSON/encode/IPC measured; no measured IPC redesign trigger at this workload. MTU and pinned aiortc integration tests pass. Recovery/codec churn under controlled WAN impairment and broader producer load remain open. | + +The earlier 08:48 driving release-readback failure remains unclassified because +that drive did not retain the readback; the later 10:53 readback is classified above. CPU saturation is not established by +the passive evidence. The failed external deliveries are real, but their exact +network/host origin is not proved by these measurements. The 30-minute latency, +driving, loss/jitter/handover and multi-producer field gates remain open. +Acceptance never depends on SSID, shared LAN, proximity, or a local shortcut. + +Private reports, immutable source/package/owner identities, hashed evidence +archives and cleanup receipts: `outputs/network-runtime-ab-20261026/`. +Qualified and rollback artifacts remain; owned temporary build stages are +cleaned through their versioned entry points. Core8000 remains the operator +service, with DEV off and no diagnostic helper retained. + + +## Node74: failed 12:36 drive followed by one sustained session + +Read-only investigation on 2026-10-26 retained the operator's closed 12:36 DEV +recording: 4150 events, zero drops, 2140213 bytes, SHA-256 +`d16dd5f4e75e99bf05d82c09d86f315b67390e7d14adeadc91efa7658fcf6f6a`. +All 569 recorded telemetry exchanges returned HTTP200, with no recorded stream +disconnect. Three VESC input gaps were 339.644/324.439/325.049 ms against previous +remaining TTL315.343/314.294/316.373 ms: expiry preceded the next input by +24.301/10.145/8.675 ms. The moving session's rejected input preceded the terminal +snapshot and Core withdrawal. Immediate release readbacks were 1.23/2.18 A, +duty0, ERPM-36/58; the existing <=1 A criterion failed, then passive neutral +reconciliation succeeded at09:37:00.972709 UTC. No threshold or lease changed. + +On the same services, a single later session persisted from09:38:06.523 through +stopping at09:44:35.788 UTC, with repeated ready/driving states and confirmed +release at09:44:36.192. Bounded journal windows retained6966 local frames and3331 +telemetry exchanges, all HTTP200. Local-driver p95/max2/7 ms, local-cycle gap +p95/max50/67 ms. These event windows are not a continuous DEV recording. The +smallest estimated prior-TTL margin across contiguous observed new intents was +approximately7 ms; success does not establish a comfortable deadline margin. +The separate60-second HTTP sample began after this session ended and must not +be described as a driving qualification. + +A later45-second passive header capture on the existing overlay interface, +with DEV off, observed command-shaped stream packets arriving in bursts after +232–244 ms gaps. One157-byte TCP sequence hole held two later segments until +it filled22 ms later. This demonstrates delivery batching before the Node +application in that separate interval; it does not identify the source of every +12:36 stop. No LAN/SSID shortcut, route or Wi-Fi change was made. A simultaneous +Core-side capture was unavailable without local sudo credentials. The remaining +cause boundary includes Core's sending stack, overlay/network delivery and the +receiving stack. No speculative transport replacement or Node75 was installed. + +Private evidence: `outputs/network-runtime-1236-20261026/REPORT.txt` and +`evidence.json`. The A/B field incident remains open. Core8000 and onboard +services remain running; the agent did not arm or originate motion. + +## Operator-host A1 capture, 2026-10-26 + +Core and browser now have an explicit local engineering capture independent of +onboard DEV and its Core/live transfer options. It records socket/request/session/ +sequence identities, browser send/ack and polling failures, Core intake/dispatch, +stream frame clocks and socket-write intervals, and telemetry handling. It sends +no new diagnostic rows to Node. Existing command envelopes, original expiry, +leases, guards, release thresholds, control ownership and re-arm are unchanged. + +The per-vehicle RAM ring is bounded to 2 MiB / 6000 rows and 10–3600 seconds. +Expiry stops acquisition but retains the ring; replacement requires its exact +previous identity. The local-origin API never arms, holds or commands the rover. +`scripts/qualification/capture_rover_local.py` drains it to a bounded private +engineering JSONL, explicitly reports ring gaps, hashes the result and stops only +its own generation. Ordinary DEV options are not changed by that collector. +The default passive collector refuses an already active control session and ends +if the operator starts control. Explicit `--allow-operator-control` only observes +human control; it adds no control request. This is an engineering facility, not a +new always-on product telemetry history or a change to the DEV modal contract. + +Qualification: 38 Core/API/collector regressions; 37 production InputLease/remote +control tests including all three recorded 12:36 receipt gaps; 1351 frontend tests, +architecture checks, typecheck and production build. New Python files pass Ruff; +existing compact-style files pass F/I checks (their prior formatting debt is not +claimed clean). Browser normal/expanded/Escape and live telemetry/video were +checked after activation through the existing Core8000 LaunchAgent. Node74, +VESC 0.20.9 and X4-23 were not reinstalled by this increment. + +A 60-second runtime check with onboard DEV off retained 1090 local events, +including the real browser attachment, with zero collector gaps. All 60 sampled +states were fresh, control was inactive and ERPM was zero. A separate 45-second +paired capture retained 2624 onboard events with zero dropped records and matched +all 767 Core frames to Node by exact Core frame-clock value. For the largest +matched Node gap, Core write completion spacing was 54.772 ms and Node receipt +spacing was 206.404 ms: delivery delay increased by 151.632 ms. This is a difference +of intervals, not an absolute one-way latency estimate or wall-clock subtraction. +The remaining boundary includes Core's sending stack, the external/overlay path +and Node's receiving stack; that measurement alone does not assign blame to TCP, +Wi-Fi or a router. Local Node–VESC exchange p95/max was 2/6 ms, and all 442 +telemetry exchanges returned HTTP200. All 45 sampled Core states were fresh; +931 driver exchanges were observation-only. These captures did not reproduce a +moving lease expiry and do not close the driving incident or the full A/B audit. + +Implementation: `src/k1link/fleet/rover_local_trace.py`, `rover_diagnostics.py`, +`rover_control.py`, `rover_stream_timing.py`; `src/k1link/web/rover_socket.py`, +`rover_diagnostics_api.py`; `apps/control-station/src/core/fleet/roverDevEvents.ts`, +`roverTransport.ts`, `useRoverDiagnostics.ts`. Private source deltas, tests and +hashed captures are retained in `outputs/network-runtime-a1-20261026/`. + +A second 90-second paired capture also collected 100 seconds of TCP headers only +on Node's existing overlay interface. It retained 5097 onboard records and 1621 +Core/browser events, with zero recording/collector loss. All 1532 Core frames +matched Node. The inferred command-stream connection carried 1703 payload-bearing +packets in the wider header interval; tcpdump reported 6063 total matching packets +and zero kernel drops. No payload capture, route, SSID or network-setting change +was performed; the bounded tcpdump process exited after its own timeout. + +At 10:56:14.805 UTC, consecutive Core write completions were 52.842 ms apart, +Node app receipts were 241.210 ms apart, and corresponding packet arrivals were +241.153 ms apart. The first packet after the pause was followed by three more +consecutive TCP sequence ranges within 0.2 ms. The first app receipt followed +its preceding header timestamp by approximately 0.1 ms. Header correlation uses +Node's own clocks and the repeated TLS record sizes; it does not decrypt packets +or use cross-host UTC subtraction. This observed burst therefore preceded Node +application processing. The remaining boundary includes Core's sending stack +and the external/overlay path before Node ingress. Separately, Core frame gaps +still reached 150.187 ms and socket-write duration 76.836 ms in this interval; +those tails are not claimed eliminated. All 90 sampled states were fresh, +control inactive and ERPM zero. A later read-only tunnel status reported active +relay `waw` with empty direct address; it is contextual evidence, not proof that +the relay caused this recorded pause. Neither test closes moving WAN acceptance. + +## Isolated command-stream qualification · 2026-10-26 + +`tests/qualification/rover_transport_test.go` adds an opt-in Worker 006 suite, +selected by `scripts/qualification/package_link_budget.py --suite transport`. +It runs the production `roverCommands`, `roverReadStream`, `roverTelemetry`, +clock/state and `roverLocalDelivery` against a synthetic TLS Core. Only the private +driver HTTP transport is replaced by an in-memory neutral sink. The fixture's +50 ms/wake delivery loop mirrors the production scheduler; it does not invoke +Pairing, the installed VESC owner, CAN, UI, real media or a physical output. +All commands have zero left/right intent. The container has no external network, +GPU, credentials, device mounts or host sockets, and is bounded to 2 CPUs, 2 GiB, +256 PIDs and 240 seconds. Capabilities are dropped and inputs are read-only. + +Qualified input `6a9279af083f987bb565`: 22 top-level tests passed, including +12 injected transport cases and the existing clock/stream/local-delivery +regressions. The exact source hashes, pinned toolchain/image, UTC/monotonic +measurements and full results are retained in the private evidence below. + +| Injection | Observed Node-to-sink result | +| --- | --- | +| Continuous frames with 20–200 ms intervals | All 12 neutral intents admitted, no stop or reconnect | +| Four frames accumulated over a 241 ms pause | Latest frame delivered; intermediate frames coalesced, no stop | +| 200 ms silence | Same identity continues, no stop | +| 500 ms / 2 s / 10 s silence; telemetry still live | Stop RPC after 350.331 / 350.466 / 350.792 ms; interrupted identity rejected after reconnect | +| Invalid JSON / oversized / truncated / closed stream | Stop RPC after 1.108–1.182 ms in these local fixtures; old identity rejected | +| Core clock identity changes | Stop after 49.074 ms via the independent telemetry clock sample | +| Command held for 125 ms before delivery | Remaining TTL 242.947 ms; expiry stop 252.709 ms after intent delivery, before stream guard | + +These are bounded application-delivery injections over real loopback TLS, not +kernel packet loss/rate emulation, a DERP comparison, or WAN latency numbers. +The 241 ms batch recreates the shape of the earlier passive episode, not its +whole network path or clock uncertainty. The sink validates original expiry and +neutral values, and acknowledges stop synthetically: no claim about measured +motor-current removal follows from these results. A new synthetic session is +accepted only after the stop barrier; the stand does not test the operator's +arm/preparation workflow. Assertion scheduling tolerance is not a product +watchdog change. Node74 / VESC 0.20.9 / X4-23 and Core runtime are unchanged. + +Decision: no receiver safety defect was reproduced in this matrix; there is no +basis here to extend TTL/guard or claim a runtime fix. The existing diagnostics +and stand make a later transport change comparable under the same expiry rules. +A/B remain open: full T0–T7/E0–E5 bandwidth/loss/media combinations, causal +localization of external delivery tails, actual hardware release, long-duration +and operator driving acceptance are not covered. Changing SSID or requiring a +shared LAN is not an acceptance strategy. + +Private report, case summary, verified deduplicated text archive and cleanup +receipts: `outputs/network-transport-qualification-20261026/`. Temporary Worker +containers and owned staging are removed after result-hash verification; the +canonical Core8000 remains running. The suite does not install a board release. + +## Kernel-shaped contention and primary-video credit · 2026-10-26 + +The opt-in `contention` suite extends the previous no-output fixture with Linux +`tc/netem` on loopback inside a `--network none` Worker container. It refuses to +run without the explicit qualification flag, Docker marker and a sole `lo` +interface. Core and Node use different loopback addresses; independent egress +qdiscs shape commands/ACKs in one direction and telemetry/video/ACKs in the other. +Only this namespace receives NET_ADMIN. No host/board interface, route or radio +setting changes. The pinned tools image adds iproute2 6.1.0-3 to the earlier +Debian image; it is a retained Worker qualification dependency, not board software. + +`tests/qualification/rover_contention_test.go` drives the real TLS/NDJSON reader, +telemetry, local delivery and budget/producer/permit handlers. Two synthetic +motor telemetry rows negotiate the production metadata contract. The primary +video source offers 1100-byte UDP packets at about 4 Mbit/s; this is encrypted +packet demand emulation, not an X4 codec, WebRTC congestion controller or DERP. +Synthetic Core keeps control-reserved interest for comparison; stopped motion +identity is never renewed or automatically replaced. Local diagnostic collection +uses the dedicated-lane contract but sends no diagnostics on the shaped link. + +A deterministic regression reproduced primary-video starvation at the existing +640-kbit/s effective floor (512 reserved + 128 optional). With a 180 ms command +age sample every 50 ms, `commandPressure` cleared credit before a 1100-byte packet +could accumulate its 1356-byte permit cost. It reported a nonzero allocation yet +admitted zero payload over two seconds. The correction clears old credit once +on entry to pressure and advances the refill anchor; subsequent moderate samples +retain the low-rate credit. The regression now admits 25300 payload bytes / 31188 +charged bytes in two seconds, below the 32000-byte aggregate allowance. Unknown +or secondary video/background classes remain blocked, and the existing >=250 ms +emergency gate still yields all video. Leases, guard, native watchdog, release +criteria and driver code are unchanged. + +Qualified source inputs: matrix `7d434b12cea89ca7250b` (45 top-level tests), full +Node units plus soak `2d83284112fde3673846` (135 Node unit tests + one 60 s case). +All passed. The full suite includes the modified primary-view admission test; +its two source-only driver version fixtures are packaged without executing them. +No race-detector, Ubuntu owner-package or physical installation acceptance is +claimed by this Worker-only increment. At that point Node74 remained installed; +the subsequent Node75 qualification and installation are recorded below. + +| Direction Core→Node / Node→Core, RTT | No video | Production gate | Unregulated reference | +| --- | --- | --- | --- | +| 5 / 5 Mbit/s, 40 ms | 160 frames, no stop | 160 frames, no stop | 160 frames, no stop | +| 1 Mbit/s / 256 kbit/s, 100 ms | 160 frames, no stop | 160 frames, no stop; 188 KiB video received | 8 frames; 7 stop calls; 7.65 s final receipt silence | +| 256 / 128 kbit/s, 150 ms | 160 frames, no stop | 160 frames, no stop; video yields completely | 12 frames; 7 stop calls; 7.42 s silence | +| Same low profile + independent 1% random loss | 160 frames, no stop in this draw | 138 frames, 2 stop calls; video sent zero bytes | 7 frames; 7 stop calls | + +Each row/mode is one 8 s active window after 2 s baseline. Loss draws are +independent and unseeded: the difference between the zero-video runs is not +proof of a gate regression or benefit. A stop call count is not the number of +user drive sessions. Kernel drop/backlog counters and local receipt silence, +including terminal silence with no arriving frame, are retained. The 1% case +shows a command-path failure without optional video; it does not identify the +cause of the earlier real WAN event or prove a replacement transport. + +The 60 s gated 1 Mbit/s / 256 kbit/s, RTT100 case retained 1201 command receipts, +maximum receipt silence 53.696 ms, zero stop calls, 869000 video payload bytes +received and 325 successful telemetry responses with no response errors. +Telemetry exchange p95/max was 205/1455 ms: a long exchange tail still exists; +continuous command receipt does not imply uniformly low telemetry latency. +Synthetic payload size, server-authenticated TLS, loopback offloads, queue limit +64 packets and the absence of real codec/outer-overlay behavior limit this result. + +Usage: package with `--suite contention`; default selection excludes the soak +so its total stays inside the 180 s Go/240 s container bounds. For the complete +unit suite plus soak, use `--run-pattern . --skip-pattern +'^(TestWorkerContentionMatrix|TestWorkerTransport)'`. The wrapper preserves full +source/tool identities, shell-quotes selectors and carries the two protocol +version/preparation files in their repository layout. Evidence and reproducible +inputs: `outputs/network-contention-20261026/`. Temporary jobs/staging are closed; +only the pinned tools image remains. This is a qualified code correction and +qualification fixture. The subsequent board release and passive real-camera +check are recorded below; driving/WAN impairment and A/B completion remain open. + + +## Node75 release and passive hardware acceptance · 2026-10-26 + +The credit correction is now installed as Node 0.8.49-75, with unchanged VESC 0.20.9 +and X4-23. Full source input `0b7e772bfe5a339ec52fd1bb` passed all 24 Ubuntu stages, +Go race,431 VESC tests and package checks. The only runtime change from Node74 is +`link_command_health.go`; `link_operator_view_test.go` is its regression. The +recorded lease-gap regression was made unittest-compatible so that the official +Ubuntu suite executes all three measured delayed cases and the timely case. +No global dependency, loose binary replacement or safety deadline change occurred. + +Owner `c995ff13b2e43a8d2fd1d01f` installed at 14:09:46–14:10:08 UTC. Both versioned +CAN admission barriers were safe, observation restored, and all 1194 regular +installed package files matched the qualified payload. The previous Node74 owner +is retained; release identities and SHA-256 values are in the installation ledgers. + +The 120-second passive check had 120/120 fresh Core observations, 240 motor readings +with p95/max age 381/434 ms, ERPM 0 and no control session. One Core stream reported +2054 successful writes and no reconnect event. Frame-gap p95/max 80.24/185.03 ms, +write p95/max 13.77/133.60 ms and dispatch max 2.12 ms remain explicit: these are +Core-side observations, not Node-receipt or one-way WAN measurements. The local +trace collected 2173 events with zero dropped rows or collector gaps and closed. + +A single browser video element served the three X4 panes. Across two readings +127.17s apart the same peer remained, currentTime advanced 126.89 s and the receiver +reported 11–12 fps at 1280x640. Cumulative media expired frames/datagrams, queue drops, +stale RTP and source decode errors remained zero in those samples; receiver +loss/drop/freeze counters were zero only for the sampled two-second intervals. +Encoder reinitializations increased 1→5 and are not declared resolved. No new +browser warning/error log items were returned. + +This accepts versioned delivery and scoped passive operation. It does not close +the earlier drive interruptions, prove delivery under packet loss/DERP/handover, +measure camera-to-display latency or test actual release-current confirmation. +No arm/hold/drive was sent. Exact evidence and compact source/build archives: +`outputs/network-release-75-20261026/REPORT.txt`. + +### Node75 operator drive — 26 October, 15:09–15:11 UTC + +The operator's local-only DEV captured 10347 events with zero drops and a normal +footer. Core API export and the onboard closed original have identical SHA-256. +One input lease expired: the last accepted command had 312.361 ms remaining; +the next distinct input arrived after 349.737 ms and was rejected in stopping. +A duplicate sequence in the intervening stream did not renew that deadline. +Seven Core frames spanning 237.939 ms of generation timestamps were read by Node +in 0.888 ms. Local driver exchanges p95/max were 2/8 ms; all 876 telemetry +exchanges returned HTTP200. The coincident telemetry round trip was 337 ms, +including only 1.141 ms reported Core handler processing. No stream disconnect +was recorded. Native watchdog release followed the input-lease expiry. + +Initial release readback on one motor remained 3.28 A despite duty zero, so its +neutral criterion was not confirmed. Later observations established neutral; +they do not change the original release evidence. This remains a failed driving +continuity criterion, despite good control before the rare delivery tail. + +The drive had no contemporaneous local Core trace or packet-header capture. +Generation clocks do not prove when Core completed socket writes, so this capture +does not distinguish the Core sending stack, external transport or Node receive +boundary. It does not identify a Wi-Fi/relay fault. DEV verbose network upload +was off. A/B are still open, and no runtime was replaced during this analysis. + +Video budget snapshots sometimes yielded to 384 kbps, but otherwise allocated +1.556–5 Mbps. After the drive, two separate browser samples showed 5 Mbps +allocation / 3.25 Mbps producer target / 0.5 Mbps H264 encoder target and receiver +feedback around 0.31–0.35 Mbps. One-second Node budget samples and later encoder +snapshots cannot establish the precise quality transition at arm. The real-codec +regression confirms that recovering Node allocation alone does not override a +low receiver estimate. Raising that ceiling alone is not a qualified video fix. + +The scalar input interval extends `plugins/vesc/tests/test_recorded_lease_gaps.py`; +receiver-cap recovery is checked in `tests/test_media_budget.py`. Both selected +lease tests and both codec tests passed, with scoped Ruff checks. Production +code, TTL/guard/watchdog and release thresholds are unchanged. Private original, +recomputable analysis, bounded board journal and checks are retained under +`outputs/network-drive-node75-20261026/`. + +### Local video history and paired passive capture — 26 October, 16:06 UTC + +The operator-host-only trace accepts `browser_preview`, a bounded numeric +projection from the existing peer and two-second `getStats` tick. Node allocation, +producer target, codec target, receiver estimate, dimensions, frame rate, counters +and encoder reset markers remain separate. `source_age_ms` is time since the last +data-channel report at the browser, not camera-to-display latency. No new peer, +polling timer, board RPC, media payload or remote DEV upload is introduced. +The remote diagnostic route rejects this event; stopping local capture ends its +retention. Numeric and identity validation excludes arbitrary payload and SDP. + +Implementation: `packages/sensor-ui/src/previewEvidence.ts`, the existing preview +hook and transport contract; `roverDevEvents.ts`/`sensorTransport.ts`; server +`rover_preview_evidence.py` and `rover_diagnostics.py`. Focused Python 20 tests, +UI 1353 tests, typecheck, architecture, scoped Ruff and frontend build passed. +The existing Core was restarted and the normal/expanded/Escape observer checked. +Node75, VESC0.20.9, X4-23 and all safety thresholds remain unchanged. + +A 90-second no-control capture matched all 1527 Core frames to Node receipts, +with 5115 onboard events, 1663 local Core events, 45 video samples and zero record +loss. The bounded Node ingress trace retained 6972 packet headers with zero kernel +drops. At 16:06:30 UTC the completed Core write interval was 55.613 ms, Node receipt +interval 257.653 ms and correlated ingress packet gap 257.669 ms; Node logging +followed the first arriving packet by about 0.081 ms. Frame-sized encrypted TCP +payloads, cadence and receipt timing identify the correlated flow; no decryption +or absolute cross-host one-way calculation is claimed. + +Local driver exchange p95/max was 2/6 ms. All 838 telemetry exchanges returned +HTTP200, p95/max159/255 ms, reported Core handler p95/max0.825/2.573 ms. Core writes +also had their own p95/max4.960/143.622 ms tail. This narrows the largest receipt +gap to before Node application processing; it does not distinguish the Core +sending stack/overlay queue from external transport without Mac egress headers. + +Video allocation recovered 1.313→5 Mbps while codec target stayed500000 bps in all +45 samples; receiver estimate was117679–418996 bps. Dimensions changed +1280x640→960x480→1280x640 and encoder reinitializations1→3. Sampled receive rate +was6–12fps; queue/expiry/stale/loss/drop/freeze/decode-error counters were zero in +the captured samples. No path-capacity or arm-transition conclusion follows from +this stationary sequence. Moving acceptance and audit A/B remain open. + +Both recordings closed, all observations fresh, ERPM0, no arm/hold/drive sent. +Reproducible analysis, original hashes, run bounds and operator-drive protocol: +`outputs/network-paired-node75-20261026/REPORT.txt`. + +### Paired operator drive and collection lifecycle — 26 October, 16:55 UTC + +The 240-second operator-run capture retained 22695 onboard records,25766 Core +events and all5512 paired frame timestamps, with no record/collector gaps. +Two early session retirements are fully recorded. During preparation a command +with18.767ms remaining was followed22.299ms later by a fresh command, after the +earlier lease had expired. The later ready-state command with203.466ms remaining +was retired by Node at16:57:15.860638; the next distinct sequence arrived at +16:57:15.866853. Core's write and operator-arrival tails also remain represented; +no unique external-link or Wi-Fi cause is assigned. + +The final operator-reported stop occurred27.391s after the main recording closed. +Its bounded Node journal shows `core_withdrew_command`, while the prior command +still showed254.372ms remaining. It lacks contemporaneous Core evidence to select +between operator-lease, socket or application withdrawal causes. Initial current +readback1.05/3.26A did not confirm neutral; later recovery did. This coverage gap +must remain explicit. The recorded new video peer had82 samples over157.34s and +encoder reset counter0→89, with frequent480/1280 width changes under control. +Those facts establish adaptation churn, not causality for control interruption. + +The local qualification collector now supports a bounded operator-stop lifecycle: +`--allow-operator-control --stop-after-control-idle 20`, with a900s maximum for +the next paired run. It starts the idle tail only after seeing operator control, +resets it on rearm/stale data and never sends a motor request. The private paired +helper closes its own packet reader through a child supervisor on completion. +Seven focused tests and scoped Ruff passed; a10s passive hardware check completed +with634 onboard records, no drops and packet-reader exit0. No runtime release or +motor-protection change occurred. Evidence and limitations: +`outputs/network-paired-node75-20261026/operator-drive-1/REPORT.txt`. + + +### Node77/X4-24 and last Core withdrawal evidence — 26 October, 18:38 UTC + +Core now exposes one bounded `core_stop_v1` record in local diagnostics even with +DEV off. Existing withdrawal paths clear authority before recording the reason; +optional trace/export locks and I/O are absent from that path. UTC-day change or +24 monotonic hours clears the RAM record. No new lease/stop/renewal condition, +persistent monitoring history or board upload is introduced. The canonical Core +was activated and116 focused tests passed. The unrecorded final stop of the earlier +drive remains unattributed; this instrumentation supports the next observation. + +Video zero-quota pauses preserve spatial profile and restart its existing 2 s +upgrade observation. H264 codec bitrate upgrades above the recreation threshold +wait for a sustained 2 s floor; ordinary decreases, Node/receiver ceilings and packet +deadlines remain. Worker006 isolated comparison decoded every frame: targeted +40-pause sequence changed 80→1 codec initializations/reinitializations and 79→0 +spatial changes. The coarse 82-sample measured profile changed 41→38 recreations; +it is synthetic-frame qualification, not loss/WAN/driving replay.21 focused SDK +tests passed. In-place bitrate mutation was rejected after measured bytes failed +to decrease and was never installed. + +X4 owns a separate SDK payload; Node-only installation does not activate it. +The coordinated release is Node 0.8.49-77 + X4 0.1.3-24 (VESC 0.20.9), with the exact +camera package pinned in `apps/node-agent/packaging/insta360-profile.json`. +Node passed 24 Ubuntu stages and X4 127 package/runtime tests. Versioned installation +completed 18:34:36UTC with safe CAN barriers; all 1195 Node files and 1069 active camera +payload files match their manifests, including the actual isolated SDK import paths. +Core files: `rover_stop_evidence.py`, `rover_control.py`, `rover_diagnostics.py`; +SDK files: `codec_recovery.py`, `media_budget.py`; new regressions: +`tests/fleet/test_rover_stop_evidence.py`, `tests/test_media_reconfiguration.py`. + +Two-minute passive acceptance: 120/120 fresh observations, ERPM 0, 2203 local events +and zero collector gaps; 2024 successful Core writes (gap p95/max 81.58/185.18ms, +write p95/max 4.97/129.91ms). These are Core-side measurements. 60 video samples kept +one peer at 1280x640, 10.5–13fps, encoder reset counter 1→2, no sampled expiry/queue/ +stale-RTP/decode/loss/drop/freeze increments. Browser video time advanced 128.947s +across 129.243s between readings. Startup required a second offer; fast recovery is +not accepted. Node allocated 5Mbps while receiver/encoder remained near 0.42–0.58Mbps, +so sustained image quality and driving continuity remain open. No motion, induced +WAN impairment or clean-host acceptance is claimed; all protection limits remain. +Exact provenance, bounded measurements, Worker comparison and verified cleanup: +`outputs/network-video-stability-20261026/REPORT.txt`. Audit A/B remain open. + + +## Node77: captured operator stop, 18:59 UTC · 2026-10-26 + +The paired human-operated run failed the continuity gate. Both records closed: +5734 Core events with zero collector gaps, 9285 onboard records with zero writer +drops, and 7485 captured ingress TCP headers with zero kernel drops. The Core +ring later evicted 419 already-drained rows; the exported file has no collector +gap. No autonomous arm or motion command was sent. + +The first stop was driver lease expiry: the last accepted intent had 313.051 ms +remaining and expired 315.908 ms later. Node's local driver exchanges were +p95/max 2/6 ms, with no delivery errors. At the same board, ingress headers show +482.003 ms with no captured TCP packet from the confirmed Core port on any +connection. The first later command-flow segment starts 718 bytes beyond the +previous observed TCP sequence end. This localizes the interruption before Node +application processing; it does not identify its origin in Core's sending stack, +tunnel or underlying path. Header matching does not decrypt TLS. + +Embedded Core frame clocks match the last received frame exactly. Core recorded +11 further successful writes on that stream over 552.881 ms, then a write error. +Successful write is not delivery acknowledgment. The first newly read Node frame +arrived after 935.808 ms and the interrupted session was already retired. Core's +new bounded last-stop evidence reports `driver_terminal` with 282.005 ms left +on the operator lease, not an operator-input timeout. Absolute UTC across hosts +is not used to estimate one-way latency. + +Immediate release readback was 1.6/1.2 A, duty zero and ERPM 363/637, so the +existing <=1 A criterion correctly did not confirm release. Four subsequent +fresh neutral samples spanning 685 ms confirmed it at 18:59:48.509 UTC. The +initial failed confirmation remains historical evidence; authority was not +restored automatically. + +A later 11.758 s absence of all captured Core TCP packets coincided with an +onboard interface re-association, DHCP/address change and tunnel rebind. Nine +TCP connect attempts failed before recovery. The first stop predates those +logged link changes: they do not by themselves explain its initial 482 ms gap. +The same video peer had zero-FPS samples during the longer outage; video quality +and causality remain open. A shared LAN or particular SSID is not an acceptance +condition. No network, runtime, protection or release setting changed. + +Matched-successive-frame gap statistics exclude terminal silence. The private +incident analyzer now reports it separately, verifies the raw hashes and keeps +Core, Node and VESC clock origins distinct. The remaining causal measurement +is Core egress/tunnel versus Node ingress during passive observation; the +existing one-sided capture cannot separate those boundaries. Do not request +another drive merely to repeat the same evidence. A/B remain open. + +Private report and reproducible analysis: +`outputs/network-video-stability-20261026/node77/operator-drive-1/REPORT.txt`. + + +## Paired tunnel egress/ingress and TCP establishment regression · 2026-10-26 + +A 300 s passive run reproduced two stream-guard disconnects without arming or +motion. Tailscale's supported debug capture on Mac persisted only scoped TCP +header metadata; Node tcpdump captured the same endpoint in both directions +with absolute sequences. All 10606 payload-bearing Core packets captured on +Node matched unique Mac records by flow, sequence, length and TCP timestamp. +Core retained 5548 events with zero collector gaps; Node retained 16289 records +with zero writer drops. Node capture reported zero kernel drops; the Mac API +provides no separate capture-drop counter. All 300 observed motor states had +zero ERPM; 299/300 Core views were fresh. + +For the first disconnect, the same consecutive packets left Mac 55.309 ms apart +and reached Node 373.309 ms apart: 318.000 ms interval expansion after Mac's +TUN capture point. In the second, two exact ACKs left Node 71.867 ms apart but +reached Mac 990.027 ms apart. Mac retransmitted older data, then withheld further +TCP output for 548.720 ms while Core kept writing new frames. Transmission +resumed 0.611 ms after the delayed ACK arrived on the same Mac clock. These +measurements establish bidirectional external-path delay and TCP output backlog; +they do not assign a particular relay, VPN, radio or underlying network as cause. +No cross-host absolute UTC subtraction is used for one-way latency. + +A separate, qualified source correction changes only TCP connection establishment +from 1 s to 2 s. The prior deadline raced the first SYN retransmission. All rover +lanes and the qualification fixture now use `newRoverHTTPTransport`; TLS settings, +pool limits, response deadlines, owning contexts and motion authority are retained. +Command TTL400 ms, guard350 ms, native watchdog200 ms, release threshold and +retired-session semantics remain unchanged. An unavailable endpoint can occupy +one connect attempt for an additional second; the existing probe still has an +overall 2.5 s context. + +The isolated Worker namespace dropped exactly one SYN, then restored the path +after 200 ms. Final corrected transport completed in 1027.977 ms; the legacy +transport failed in 1000.761 ms. Request cancellation returned in 75 ms; the +test TLS cleanup completed within its existing 1 s handshake timeout. All 39 +selected clock/stream/delivery/transport/connect tests passed, as did managed +Ruff for the packager. Final input `85649e0b4923abcef120` matches current source +hashes. No board package was built or installed by this increment. + +This fixes a demonstrated connection-recovery defect, not the captured pauses +on established connections. Its contribution to earlier real connect timeouts +is unproved. Audit A/B and moving continuity remain open. A transport comparison +for fresh intent independent of TCP ACK/backlog must preserve all authority, +expiry and stop barriers; replacing transport cannot promise control through a +complete absence of fresh packets. Shared LAN/SSID is not an acceptance criterion. + +Private report, exact paired evidence, increment and qualification/cleanup proofs: +`outputs/network-dual-egress-20261026/REPORT.txt`. + + +## DEV operator measurements and fenced datagram candidate · 2026-10-26 + +The canonical Core8000/UI now offers optional operator-side collection inside +DEV settings: Core/browser events and independent numeric video statistics. +It stays in bounded RAM (2 MiB, 6000 latest events, at most 15 minutes), never +ships those measurements over the rover link by default, and exports a separate +JSONL snapshot. Starting DEV does not arm control. Stopping DEV closes its owned +local collector; independent engineering captures retain separate ownership. +Replacing an existing local capture requires its identity and an explicit save +in the UI. The local snapshot must be saved before Core restarts. + +Browser acceptance, with no arming or motion: normal/expanded settings, checkbox +interaction, Escape, passive start/stop, narrow logs-window scrolling and local +save. The actual downloaded file exactly matches the Core export: 858 events, +including 23 numeric preview records, zero dropped/rejected. Its paired onboard +record closed with 2535 events and zero writer drops; both are preserved with +hashes in private engineering evidence. Local save uses a bounded normal browser +download; it does not require a file-system picker. The two save actions are in +the logs body so a narrow title bar cannot clip them. + +An unqualified MCR1 candidate implements fresh latest-state UDP delivery with +random per-generation AES-GCM direction keys negotiated through existing paired +mTLS. Packets are bounded to 1200 bytes, replay/reordering is rejected, and Node +keeps a one-frame mailbox. Every Core send revalidates the original certificate, +binding and current authority. Original command expiry, guard350ms, native +watchdog200ms, release evidence and no-automatic-rearm behavior remain. A +negotiated generation does not silently fall back to TCP. Candidate source and +isolated ACK-loss/expiry/replay/stop tests are prepared, not accepted as a release. + +Activation is explicitly fenced with QUALIFIED=False. No UDP command listener +is running; no new board package was built or installed. Node0.8.49-77, +X4 0.1.3-24 and VESC0.20.9 remain the last installed versions. Ordinary local +unit checks passed (81 Python, 12 Go), as did 1356 frontend tests, typecheck and +production build. After the final download/scroll adjustment, 7 focused frontend +tests and the production build/typecheck passed again. The Go stand fixtures +compile; Worker impairment/load and real Python/Go runtime interoperability +acceptance have not run. No local load/stress substitute was used. + +Automatic approval review refused the new selected private-source archive for +Worker006 twice, including after ownership and contents were established. It +scoped the previous user approval to the video-codec archive. Exact permission +for this new command-transport package is pending; no transfer or remote job +occurred. This is a release blocker. Audit A/B and driving continuity remain +open; the UI increment is not evidence that the command interruptions are fixed. + +At the owner's request the board accepted systemctl poweroff at +20:44:37 UTC (23:44 MSK). Immediately before shutdown, control was inactive, +release confirmed, both ERPM/duty zero, DEV records closed and camera recording +inactive. Subsequent SSH timed out and telemetry expired. Core8000 remained +HTTP200. Do not request another drive before isolated qualification, versioned +installation and passive external-path acceptance. + +Private report, source identities, verification and shutdown receipt: +`outputs/network-datagram-20261026/REPORT.txt`. + + +## Activated MCR1 and bounded optional egress · 2026-10-27 + +This checkpoint supersedes the preceding candidate activation fence and Worker +permission blocker. The owner explicitly approved the selected command-transport +archive transfer. MCR1 is now activated in canonical Core8000; Node0.8.49-79 is +installed through the versioned owner installer. X4 remains0.1.3-24 and VESC0.20.9. +Every send retains paired identity/binding/authority checks; fresh datagrams no +longer wait for TCP ACKs. TTL400ms, guard350ms, native watchdog200ms, telemetry +staleness withdrawal, release confirmation and no-automatic-rearm are unchanged. + +Final isolated Worker qualification passed30 top-level checks and11 contention +cases, including reverse TCP ACK blackout, replay/expiry/silence and media +contention. A real Python Core/Go Node mTLS test delivered neutral commands into +a RAM sink and verified binding revocation. The synthetic contention fixture +is not proof of continued authority through missing production telemetry. +All24 Ubuntu package stages passed;1195 Node and1069 active X4 files were +hash-verified after installation. This accepts package/standalone transport scope, +not moving vehicle continuity or arbitrary WAN conditions. + +Independent command transport exposed outgoing-probe congestion hidden by the +old media regulator. Optional bytes now use a bounded feedback window. Silence +and severe delay discard accumulated credit; moderate delay must persist200ms +before window reduction. Commands/probes/critical telemetry never require those +permits. Node78's passive video regression (median1fps) was rejected. Node79's +120s pass improved video to median6fps and8fps at end, but20 encoder +reinitializations and source-age p95~504ms leave video quality/stability open. + +In that120s passive capture all120 telemetry observations were fresh, no control +was enabled and ERPM/duty stayed0. Of2034 Core counters,2027 appear in Node's +consumed-frame records. The seven missing records cannot be called network loss: +latest-only mailbox replacement and replay/order filtering are not separated by +this recording. The worst receipt gap337.034ms is already337.022ms at the Node +kernel interface; the matching consecutive Core sends were59.466ms apart. This +establishes delivery bunching before application consumption, without identifying +a particular network hop or measuring absolute one-way latency. The350ms guard +was not crossed in this capture, but its margin is small. + +Next gate is operator-enabled control at neutral for60s with both DEV records, +followed by evidence review before any drive. Audit A/B, moving continuity, +real WAN acceptance and full video quality remain open. After the owner's reboot +board reachability returned; the original offline cause remains unresolved beyond +recorded connection timeouts. Board and Core remain on for the next operator test. +Owned Worker/build scratch was removed after preserving verified text, installers +and source identities. Original board recordings and unrelated work are retained. + +Private evidence, exact hashes, scoped acceptance and next-test instructions: +`outputs/network-datagram-20261027/REPORT.txt`. + + +## Assistant-operated neutral control acceptance · 2026-10-27 + +The owner explicitly authorized the assistant to operate the no-motion UI test. +DEV and control were started normally, all movement inputs remained neutral, then +control and DEV were explicitly stopped. No product code or thresholds changed. +This supersedes the preceding request for the owner to perform the neutral gate. + +One session lasted81.380s from arm to explicit stop, including74.420s of Node +ready control. No automatic stop/recovery preceded the button stop. All818 Core +commands and792 VESC inputs were zero;745 neutral output cycles and1490 successful +native release RPCs had no watchdog trip. ERPM/duty stayed0 and release readback +confirmed both motors. Fresh telemetry145/145. Node maximum consumed-frame spacing +was210.255ms; minimum remaining command TTL112.210ms. No real WAN or moving +acceptance follows from this single stationary run. + +Video during control had median10.5fps, principally960x480, with median source +age393ms. Quality/resolution stability remains open. The local engineering reader +preserved all8399 Core/browser events with no gaps; board14136 records had no +writer drops. The UI export retains only the latest6000 events (2399 evicted), +and matches that exact tail. Do not present its bounded RAM snapshot as a complete +long-session record. Full engineering evidence and hashes were preserved and +owned raw text compacted; the original board recording remains untouched. + +Control and DEV are off, release confirmed, board and Core left running. Next +owner participation is actual movement under observation, with both records and +the read-only collector; no further human neutral-button test is needed. +Private acceptance: `outputs/network-neutral-20261027/REPORT.txt`. + + +## Failed moving gate and Core dispatch correction · 2026-10-27 + +The subsequent human drive stopped automatically. This supersedes any inference +of moving acceptance from the preceding successful neutral session. Paired evidence +contains3959 Core/browser events and8172 board records, with no reader/writer drops. +VESC accepted sequence287 with213.741ms remaining; the next input reached it +229.487ms later, approximately15.745ms after expiry. The session was retired and +later fresh input correctly did not rearm it. Core continued receiving commands +and withdrew only after the driver's terminal report. The350ms stream guard was +not the trigger. Release was initially unconfirmed by non-neutral current readings; +subsequent samples confirmed release about1.14s after the terminal report. + +Delay exists at more than one point: sequence288 waited119.468ms from Core receipt +to first Core datagram send, while the board kernel also recorded204–231ms UDP +arrival gaps near termination. Cross-host clock subtraction is not a one-way delay +measurement, and the underlying path/hop has not been established. Optional video +was already gated to zero before termination, so its continued transmission is not +established as the immediate cause. Video froze and quality acceptance stays open. + +Core now sends changed latest intent and withdrawal at the next socket-loop +opportunity, without waiting for the50ms keepalive deadline; a10ms minimum interval +bounds sends. Every frame retains identity/binding/endpoint and authority checks. +This removes avoidable periodic waiting, not all host scheduling or external-path +latency. New dispatch/periodic-lag trace fields support the next measurement. +TTL400ms, guard350ms, native watchdog200ms, stale telemetry withdrawal, release +confirmation and no-automatic-rearm remain unchanged. Node79 is unchanged. + +129 focused checks passed, including real Python/Go mTLS interoperability and +revocation. Ruff introduced no new issue (16 pre-existing issues remain). The +canonical Core8000 replacement passed health acceptance after every recorded event +was preserved and the UI export verified. It remains running with control inactive. +The board became unreachable after the failed drive; post-fix board acceptance is +pending. Next gate is an assistant-run passive/neutral paired measurement when +connectivity returns. Audit A/B, moving continuity and WAN/video acceptance remain +open; no new human drive is requested at this checkpoint. + +Private derivation, source delta, retained originals and deployment receipt: +`outputs/network-drive-20261027/REPORT.txt`. + + +## Ethernet recovery, empty Wi-Fi scans and blocked neutral gate · 2026-10-27 + +The owner connected Ethernet. SSH, Tailscale and Core recovered with the same boot +and unchanged Node/network-service processes. Broadcom BCM4331/wl was unblocked +but disconnected; five read-only samples showed scans completing/restarting with +zero cached networks. A pending-scan message alone did not prove a permanent hang. +Installed kernel/driver/NM/wpa packages predate the current Node updates. Radio, +driver and workload-trigger causes remain unresolved; no OS/network change was made. + +A240s passive paired capture retained4319 Core/browser events and14761 board +records without reader/writer drops. Control was never armed: Node freshness was +230/240 but both VESCs were available in only2/240 observations.120 local VESC +transport deadlines and repeated logical attachment retirement/SDK worker creation +block the neutral gate. Logical usb_detached does not prove physical USB removal. +Observed CAN faults include query timeout, CRC/length mismatch and missing TX echo; +the triggering mechanism is not yet isolated. Protective budgets remain unchanged. +Core dispatch p95=4.891ms,max139.734ms; kernel UDP arrival spacing max384.271ms and +Node consumption spacing max636.504ms show this is not continuity acceptance. +The new fresh-intent path was not exercised by this passive no-command capture. + +After capture/export the board became unreachable again from Mac and Worker006. +Whether Ethernet remained connected is awaiting the owner's observation; do not +attribute that second outage to a component yet. DEV was already closed and copied, +Core8000 remains healthy, no new drive is requested. A/B, WAN, motion and video +acceptance remain open. Evidence and bounded next checks: +`outputs/network-wifi-20261027/REPORT.txt` and `passive-summary.json`. + + +## Reboot forensics and camera-free failure / Node80 qualification · 2026-10-27 + +The owner clarified that Ethernet was unplugged during the NEW boot only. The +previous boot's carrier loss therefore remains unexplained. Persisted journal and +2744 bounded historical monitor samples show distinct Wi-Fi loss, camera USB +flaps, Ethernet carrier loss and a later vendor CAN SDK crash; they do not establish +one common cause. After network loss the OS monitor continued (1008 samples, +max gap2.558s), without evidence of OOM/panic or critical thermal shutdown. The +camera was subsequently found discharged. This explains its current absence, not +proven causation of earlier CAN/network faults. Original records are preserved. + +A180s passive camera-free run was fresh180/180. A subsequent assistant-operated +neutral session FAILED: the last accepted input had216.650ms remaining, the next +arrived231.943ms later and was rejected after expiry. All490 Core commands, +469 VESC inputs and342 output cycles were zero. Release was confirmed; one native +watchdog trip prevents acceptance. Camera transmission is not necessary for this +failure, but its additional influence on failure probability remains unmeasured. + +Correction to earlier wording: existing UI recovery can create a NEW neutral +session after stable fresh stopped telemetry and the existing identity/release +checks. It never revives the expired lease or restores prior motion. The previous +unqualified “no-automatic-rearm” statement was too broad. No recovery code or +protective threshold changed in this increment. + +Node0.8.49-80 adds an opt-in,180s passive Wi-Fi power-save qualification service +for Ubuntu24.04 amd64 BCM4331/wl only, with original-state journaling, inactive +standstill checks, identity/policy guards and automatic restoration. It changes +no saved network profile, association, route, motor code or protective budget. +26 local tests and24 Ubuntu qualification jobs passed; the canonical owner +installer completed79→80 without new dependencies/removals. Installed helper/unit +hashes match; the service is static and is not enabled/started by installation. + +One300s passive A/B/A verified off then restoration to on, serviceResult=success. +UDP spacing p95 was133.970/133.109/133.704ms before/off/restored; off still had +203.060ms gaps. Unequal phase lengths and one run do not establish absence of +an effect or a reliable fix. No persistent power-setting change was promoted. +All300 observations had both VESCs, fresh telemetry and zero ERPM/duty. + +A separate exact UDP packet comparison matched3010 ingress records to unique +Mac TUN hashes. The same consecutive packets left Mac101.456ms apart and reached +Node331.971ms apart:230.515ms interval expansion after Mac TUN. Kernel and Node +consumption spacing agree. This is interval comparison, not absolute cross-host +latency, and does not isolate the physical/overlay hop. Unmatched checksums are +not counted as network loss; offload/capture points can differ. Board capture +reported0kernel drops; Mac has no independent capture-drop counter. The overlapping +DEV run was fresh180/180 and had13144 board records without writer drops. + +The400ms original deadline,350ms stream guard,200ms native watchdog and release +criteria remain. Higher fresh-input cadence is a candidate for bounded comparative +qualification, not an accepted fix or permission to extend stale motion. Another +human camera-free drive is not needed to reproduce failure; the next moving gate +follows a concrete correction and successful neutral qualification. A/B audit, +WAN, motion continuity and video acceptance remain open. + +Private report, exact identities, hashes, receipts, limitations and owned cleanup: +`outputs/network-reboot-20261027/REPORT.txt`. + +## Node81, Core scheduling and bounded recovery · 2026-10-27 + +The installed command transport is now MCR1 on Node0.8.49-81, with +VESC0.20.9 and X4 0.1.3-24. Core remains the single canonical8000 service. +The original400ms command expiry,350ms stream-silence guard and200ms native +watchdog are unchanged. Node81 distinguishes bounded diagnostic reasons such +as datagram deadline, invalid clock and local delivery failure without exposing +keys or command payloads. Its qualified installer and rollback are retained. + +Paired evidence established two separate delay boundaries. Some Core dispatch +stalls coincided with Python GIL contention from full planning-report work and +repeated parsing/hashing of completed background jobs. The installed corrections +use compact planning status selected before deepcopy, bounded identity-checked +indexes/caches for terminal reports, and avoid provider hashing for empty queues. +Active jobs, dynamic authority and live timestamps remain fresh. Focused +regressions and full response-identity comparisons accompany those changes. + +Other failures persist after regular Core sends: matching packet intervals expand +after Mac TUN/physical egress and before board ingress. Physical BPF timestamps +are not over-the-air timestamps, and unsynchronized host UTC is not one-way +latency. Repeated AWDL associations are preserved as hypotheses, not a proven +single cause. The owner denied an AWDL intervention; no Apple services were changed. +Board scanning is measured separately and was not disabled. + +Browser fresh input now has50ms cadence with the same original expiry. Recovery +no longer clears its retry count on a single ready snapshot. Three automatic +NEW neutral attempts are allowed before an explicit operator request is needed; +only30s of continuously observed ready state resets that count. Observation gaps +over1s break that continuity. Automatic reacquisition requires +`release_confirmed === true`; null/absent release is not affirmative evidence. +Stop, navigation, fault and identity changes retain their existing authority +boundaries; old movement is never restored. Hook tests cover failed starts, +exhaustion and visible terminal error. The final frontend validation passed +1366 tests, architecture, typecheck and build; the same asset was installed and +checked in normal and expanded Chrome layouts. + +Current acceptance is still incomplete. A203.755s neutral interval had no +session break,4074 successful native RPCs and198.063ms minimum remaining input +margin, but its complete recording contains an earlier passive450.834ms ingress +gap and is NOT accepted by the unchanged checker. The current strict series is +0/10. A separate480s passive recording had479/479 fresh observations and zero +stream stops; ICMP reached666ms during a board scan while command-frame spacing +remained within250.099ms. Ping alone therefore does not diagnose a command stop. + +A1 now has causal boundary evidence for individual failures, but the residual +path delay is unresolved. A7 recovery/release semantics have stronger regression +coverage. A5's full T1–T6 controlled matrix, B's broader producer/codec acceptance, +ten continuous neutral qualifications, motion, handover and30-minute useful-video +acceptance remain open. A/B are not complete. Do not repeat unchanged runs until +10 happen to pass or weaken protection to obtain a green result. + +Private source index, exact identities, validation/installation receipts, +failed runs, bounded captures and further passive localization: +`outputs/network-runtime-closure-20261027/NETWORK_RUNTIME_AUDIT.md`. + + +## Node83: transport continuity after motion expiry · 2026-10-27 + +This increment supersedes Node81's three-attempt UI cancellation policy. The +operator request now survives transport failures with capped1/2/4/8s retry rate. +Explicit Stop, hardware faults, device/assignment changes, receiver takeover and +unconfirmed release retain their existing boundaries. New neutral authority +requires confirmed standstill; movement requires a new physical press. + +The350ms silence guard retires authority without immediately closing UDP. A +separate2s elapsed-silence bound may renegotiate transport; it does not grant +motor authority or cancel the operator request. Node83 also fixes the timer and +stale-mailbox ordering race. Original400ms input expiry and200ms native watchdog +remain. Known transient admission conflicts preserve recovery; ownership does not. + +Four injected UDP receiver scenarios passed ten repetitions each; Node race, +1373 UI tests and24 Ubuntu qualification jobs passed. All1197 payload files and +the running binary match the qualified installer. One actual neutral UI interval +of217.090s passed the unchanged strict checker, with260/260fresh observations, +4342 successful native RPCs, zero demand/readback and confirmed explicit Stop. +The historic0/10 series remains unchanged. This interval did not reproduce a +350ms arrival gap; synthetic faults and passive/neutral acceptance are distinct. + +The historical678ms path gap, arbitrary WAN, A5 matrix, motion/handover and useful +video acceptance remain open. No Apple-service or network configuration change. +Exact source index, before/after evidence, failed fixture attempt, installation, +limits and owned cleanup: `outputs/network-runtime-closure-20261027/transport-continuity/REPORT.md`. diff --git a/docs/node/40_WIREGUARD_FLEET_NETWORK.md b/docs/node/40_WIREGUARD_FLEET_NETWORK.md new file mode 100644 index 00000000..4f66da53 --- /dev/null +++ b/docs/node/40_WIREGUARD_FLEET_NETWORK.md @@ -0,0 +1,64 @@ +# WireGuard: Mission Core ↔ бортовой компьютер + +Поставка 28.10.2026: VPS 0.1.1, Node 0.8.49-92, канонический Core на порту 8000. Настройка находится в «Аппараты → оборудование → Бортовой компьютер → Связь Core». Используется стандартное окно настроек NDC. Worker/inference и его Tailscale/MQTT-конфигурация в этот профиль не входят. + +## Первый сервер и подключение парка + +1. Выбрать «WireGuard · VPS» и скачать пакет VPS. Поддерживается Ubuntu Server 24.04 LTS amd64 с systemd; зависимости берутся из подписанного репозитория Ubuntu. Перенести пакет на VPS и выполнить `sudo python3 mission-core-wireguard-vps.pyz`. Единственный публичный IPv4 определяется автоматически; при неоднозначности установщик спрашивает адрес. Явный вариант: `sudo python3 mission-core-wireguard-vps.pyz install --host PUBLIC_IP_OR_DNS`. +2. Забрать созданный `/var/lib/ndc-wireguard-vps/mission-core-wireguard.json` и загрузить его кнопкой «Загрузить файл подключения». Core проверяет TLS-идентичность из файла, регистрирует собственный ключ и проверяет реальный WireGuard-туннель. На Mac установка/обновление сетевой службы использует штатный административный диалог. Окончание HTTPS-запроса само по себе не считается готовым VPN. +3. В настройках каждого уже привязанного БК выбрать этот общий профиль и сохранить. Новый файл для каждого борта не нужен. На сервере допускаются один Core и парк бортов; каждый борт получает отдельный ключ и адрес. Продуктовой квоты по количеству бортов нет. Доступность новых подключений зависит от адресного пула и ресурсов сервера. + +Повторная установка сохраняет идентичность сервера и участников. Если сервер уже установлен, файл можно получить командой `sudo python3 mission-core-wireguard-vps.pyz connection`. Файл подключения содержит секрет первичного подключения: хранить приватно, не добавлять в Git, карточки или публичные отчёты. Закрытые ключи клиентов остаются в локальной root-службе и не входят в общий файл. + +## Применение и возврат + +Сохранение запускает операцию с ожидаемой ревизией конфигурации. Борт подготавливает туннель; Core принимает подтверждение через новый аутентифицированный канал и только затем фиксирует смену. При неуспехе возвращается предыдущий профиль; незавершённая стадия сетевой службы ограничена 120 секундами. Смена пути отзывает прежнюю управляющую сессию, старые команды не повторяются. Во время операции включение управления блокируется. + +Для возврата выбрать Tailscale и сохранить. Борт хранит прежний Tailscale endpoint; его локальный интерфейс также предоставляет возврат к Tailscale. Это предполагает работоспособное существующее подключение Tailscale. Переключение не заменяет первоначальную привязку Node к Core и не меняет Worker. + +Видео использует выбранный путь. При WireGuard сигнализация ограничивает адреса Core/Node адресами данного профиля. Браузерные mDNS host candidates не разрешаются в произвольные адреса: ответ содержит адрес WireGuard борта, а входящая ICE-проверка позволяет обнаружить адрес клиента. При смене транспортного поколения прежний video peer закрывается. + +## Изоляция + +VPS принимает WireGuard UDP 51830 и отдельный HTTPS API TCP 19444. Расшифрованные пакеты находятся в namespace `ndc-fleet-wg`, содержащем только loopback и WireGuard-интерфейс. В namespace нет внешнего интерфейса или default route. Правила разрешают Core ↔ зарегистрированный борт: TCP 8781/8782, UDP для текущих медиапотоков и ICMP. Борт ↔ борт не разрешён. На хостах IP forwarding не включается. + +Установка сохраняет существующие сервисы и firewall ARNavi; добавляет только собственные маркированные правила в распознанный firewall. Неизвестные ограничивающие правила не переписываются автоматически. Namespace не имеет маршрута в LAN Synology или Tailscale. Существующий Device Core edge channel и ARNavi authority не перенастраиваются. + +## Перенос VPS + +Для нового независимого сервера достаточно того же пакета и нового файла подключения. Для сохранения идентичности существующего сервера предусмотрены `migration-export --file /root/wg-transfer.zip`, `migration-import --file /root/wg-transfer.zip --host NEW_PUBLIC_IP` и защищённое возобновление источника `migration-resume --destination-fenced`. Экспорт останавливает исходный сервис и устанавливает запрет его старта; импорт требует пустой сервер и root-owned файл с правами 600. Архив содержит закрытые ключи и хранится приватно. + +Перед плановым переносом доступных бортов сохранить рабочий резервный путь Tailscale. После переноса импортировать обновлённый файл подключения в тот же Core и повторно применить общий профиль к бортам через настройки БК. Обновление адреса VPS не считается мгновенным автоматическим переключением всех недоступных бортов. Полный перенос между двумя живыми VPS в этой поставке не квалифицирован. + +## Первоначальная приёмка 0.1.0 · 28.10.2026 + +- Штатная установка VPS 0.1.0 на действующую Ubuntu 24.04, повторная установка и перезапуск сервиса; сохранены службы ARNavi/authority/Device Core edge channel. +- Node 0.8.49-92 установлен версионированным owner installer на N006. Его сетевой helper прошёл проверку сокета; после установки новых аварийных рестартов нет. Счётчик systemd сохраняет 55 рестартов от промежуточного выпуска 91; он не сбрасывался для улучшения отчёта. +- Через реальный UI: скачивание пакета, импорт, повторный импорт, отказ ошибочному JSON, общий профиль 1/50; Tailscale → WireGuard → Tailscale → WireGuard. На борту подтверждена ревизия 3 и endpoint Core в WireGuard. +- Живое X4-видео 1280×640, выборочный интервал 12 fps, около 0,65 Мбит/с, RTT 207 мс; после проверки просмотр остановлен. Это не сравнительный тест производительности сети. +- Frontend: architecture, typecheck, 1412 unit tests, production build; проверены узкое окно и Escape. Ubuntu-квалификация базового Node — 24 этапа; упаковочная коррекция 92 — отдельный этап с точной проверкой изменённого payload. Финальные 18 тестов профилей, установщиков и helper прошли; серверные 5 тестов включают выдачу 50 индивидуальных адресов и отказ 51-му борту. +- На VPS нет маршрутов из namespace к LAN/Tailscale; forwarding хоста 0. На борту только маршруты /32 к Core и шлюзу. + +Физически проверен один ровер. 50 реальных бортов одновременно, проезд/управление моторами, длительная WAN/LTE-нагрузка и перенос между двумя VPS не проверялись. Прежняя полевая приёмка сетевых задержек остаётся открытой. + +## Идентичность и код + +VPS 0.1.0 installer SHA-256: `374624ed88448ecc8483b10f49fc2459a0f5c19de7a39ba2b2f0c39f1b668225`. + +Node92 .deb SHA-256: `c84d7019be956e2420cdd21d690069d7e16db9486d8834f2e056993f97c12e9c`. + +Owner release: `9cccd46c8af74dac8df5765f`; локальный возвращённый .pyz SHA-256: `9846af7a4c8e74555d816a0fb805c25c3f04bccee068bb79d465d590379825f5`. Полная Ubuntu-квалификация и квалифицированный compiled base сохранены рядом с Node92. + +Core: `src/k1link/fleet/network_profiles.py`, `network_client.py`, `network_media.py`, `src/k1link/web/fleet_network_api.py`. Привилегированная служба: `apps/wireguard-client/`. Node: `apps/node-agent/internal/node/network_profile.go`, `packaging/mission-core-node-wireguard.service`, `repack_wireguard_helper.py`. UI: `BoardNetworkSettings`, `useBoardNetwork`, `BoardComputerFeatureSettingsWindow`, `NodeCoreConnectionView`; медиапереход — `packages/sensor-ui/src/useSensorPreview.ts`. Самостоятельный сервер: репозиторий `NODEDC_MISSION_CORE_ARNAVI-VPS`, каталог `wireguard_vps/`, сборщик `scripts/build_wireguard_vps.py`. + + +## Уточнение владельца 28.10.2026: пример 50 не является квотой + +В VPS 0.1.1 удалены LIMIT=50, поле capacity из нового файла подключения и статуса; Core продолжает принимать ранее выданные файлы, игнорируя старое информационное поле. UI показывает только число подключённых бортов. Core/helper и migration больше не отвергают список участников после 50. Регрессия проверяет 80 отдельных бортов и сохранение изоляции. + +Это не обещание неограниченной физической ёмкости: существующая IPv4-адресация /24 сохранена без изменения адресов и ключей; текущий allocator имеет 251 доступный адрес борта. При исчерпании адресов выдаётся отдельная ошибка без частичной регистрации. Масштаб больше одного адресного пула требует расширения адресного контракта, а не замены числа в интерфейсе. + + +Квалификация 0.1.1: 20 адресных Core/installer/helper-тестов, 6 серверных, 1412 UI-тестов, architecture/typecheck/build пройдены. Пакет установлен штатно, новый файл импортирован через UI, helper Mac обновлён, Node92 остаётся на WireGuard. SHA-256 пакета 0.1.1: `79e3604efd56005de788b37610404a31e12c61f15b0edd45c822bbda9b870acd`. + +Сравнение 22:36–22:39 МСК: по три одиночных TCP-передачи каждого направления; порядок WG/TS/TS/WG/WG/TS. Медианы борт→Mac: 11,96/6,04 Мбит/с (+98,1%); Mac→борт: 18,30/6,03 (+203,5%). Request/echo RTT: 57,08/60,68 мс, p95 138,75/142,35 мс. Tailscale через DERP(waw); фон Core/Node сохранялся. Один начальный WG-запрос завершился таймаутом, все 12 передач данных завершены. Сохранены исходный измеритель, его SHA и компактные результаты в `.runtime/wireguard-ab-20261028`. Это измерение сети, не вычислительной производительности или управления в движении. diff --git a/scripts/qualification/capture_rover_local.py b/scripts/qualification/capture_rover_local.py new file mode 100644 index 00000000..1b664794 --- /dev/null +++ b/scripts/qualification/capture_rover_local.py @@ -0,0 +1,222 @@ +"""Bounded operator-host A1 collection. Never sends arm, hold or drive requests.""" + +import argparse +import hashlib +import json +import time +from datetime import UTC, datetime +from pathlib import Path +from urllib.parse import quote +from urllib.request import Request, urlopen + + +def exchange(url, body=None): + raw = None if body is None else json.dumps(body).encode() + request = Request(url, data=raw, headers={"Content-Type": "application/json"}) + with urlopen(request, timeout=4) as response: + return json.load(response) + + +def collect(vehicle, output, seconds, *, previous_id=None, allow_operator=False, + stop_after_control_idle_s=None): + if not 1 <= seconds <= 1800: + raise ValueError("Duration must be 1..1800 seconds") + if stop_after_control_idle_s is not None and ( + not allow_operator or type(stop_after_control_idle_s) is not int + or not 1 <= stop_after_control_idle_s <= 120 + ): + raise ValueError("Operator-stop collection requires allowed control and 1..120 s tail") + url = "http://127.0.0.1:8000/api/v1/fleet/" + quote(vehicle, safe="") + "/rover" + state = exchange(url) + if state.get("controlling") and not allow_operator: + raise ValueError("Operator control is active; no passive qualification started") + path = Path(output) + path.parent.mkdir(parents=True, exist_ok=True) + identifier, after, count, gaps, written = None, 0, 0, 0, 0 + started = time.monotonic() + outcome, error, final = "complete", None, None + control_seen, idle_since, termination = False, None, "duration_limit" + digest = hashlib.sha256() + with path.open("xb") as handle: + + def write(value): + nonlocal written + raw = ( + json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n" + ).encode() + if written + len(raw) > 64 * 1024 * 1024: + raise ValueError("Capture byte limit reached") + handle.write(raw) + digest.update(raw) + written += len(raw) + + def drain(): + nonlocal after, count, gaps + # At most two pages each cycle; browser and control never await this collector. + for _ in range(2): + page = exchange( + url + + "/diagnostics/local?capture_id=" + + identifier + + "&limit=500&after=" + + str(after) + ) + if page["first_sequence"] > after + 1: + gaps += page["first_sequence"] - after - 1 + write( + { + "source": "collector", + "event": "ring_gap", + "after": after, + "before": page["first_sequence"], + } + ) + after = page["first_sequence"] - 1 + for row in page["frames"]: + write(row) + after = row["record_sequence"] + count += 1 + if after >= page["sequence"]: + return page + return page + + try: + capture = exchange( + url + "/diagnostics/local", + { + "enabled": True, + "duration_s": max(10, int(seconds) + 30), + "capture_id": previous_id, + }, + ) + identifier = capture["id"] + write( + { + "type": "session_start", + "schema": "missioncore.local-capture/v1", + "id": identifier, + "at_utc": datetime.now(UTC).isoformat(), + "duration_s": seconds, + "motor_commands": False, + "allow_operator_control": allow_operator, + "stop_after_control_idle_s": stop_after_control_idle_s, + "capture": capture, + } + ) + print(json.dumps({"started": identifier, "output": str(path)}), flush=True) + while time.monotonic() - started < seconds: + tick = time.monotonic() + page = drain() + state = exchange(url) + write( + { + "source": "collector", + "event": "observation", + "at_utc": datetime.now(UTC).isoformat(), + "monotonic_ms": time.monotonic() * 1000, + "value": state, + } + ) + if state.get("controlling") and not allow_operator: + raise ValueError("Operator began control; passive qualification ended") + if not page["active"]: + raise ValueError("Local capture expired or stopped externally") + if state.get("controlling"): + control_seen, idle_since = True, None + elif state.get("fresh") and control_seen: + if idle_since is None: + idle_since = time.monotonic() + if (stop_after_control_idle_s is not None + and time.monotonic() - idle_since >= stop_after_control_idle_s): + termination = "operator_stopped" + break + else: + # A stale/missing snapshot is not a confirmed completed session. + idle_since = None + time.sleep( + max( + 0, + min(1 - (time.monotonic() - tick), seconds - (time.monotonic() - started)), + ) + ) + except BaseException as exc: + outcome, error = "incomplete", type(exc).__name__ + finally: + if identifier: + try: + final = exchange( + url + "/diagnostics/local", {"enabled": False, "capture_id": identifier} + ) + # A stopped generation is immutable; drain its remaining bounded ring. + for _ in range(7): + final = drain() + if after >= final["sequence"]: + break + if after < final["sequence"]: + outcome, error = "incomplete", "UndrainedTail" + except Exception as exc: + outcome, error = "incomplete", type(exc).__name__ + try: + write( + { + "type": "session_end", + "id": identifier, + "outcome": outcome, + "error_type": error, + "termination": termination, + "control_seen": control_seen, + "events": count, + "collector_gaps": gaps, + "local_status": {k: v for k, v in final.items() if k != "frames"} + if final + else None, + } + ) + except Exception as exc: + outcome, error = "incomplete", type(exc).__name__ + manifest = { + "id": identifier, + "outcome": outcome, + "error_type": error, + "termination": termination, + "control_seen": control_seen, + "events": count, + "collector_gaps": gaps, + "bytes": written, + "sha256": digest.hexdigest(), + "motor_commands": False, + } + path.with_suffix(path.suffix + ".manifest.json").write_text(json.dumps(manifest, indent=2)) + return manifest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--vehicle", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--seconds", type=int, default=60) + parser.add_argument("--previous-id") + parser.add_argument( + "--allow-operator-control", + action="store_true", + help="Observe user-operated control; never originate a command", + ) + parser.add_argument( + "--stop-after-control-idle", type=int, + help="Close after this fresh idle tail following operator control (1..120 s)", + ) + args = parser.parse_args() + result = collect( + args.vehicle, + args.output, + args.seconds, + previous_id=args.previous_id, + allow_operator=args.allow_operator_control, + stop_after_control_idle_s=args.stop_after_control_idle, + ) + print(json.dumps(result), flush=True) + return 0 if result["outcome"] == "complete" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/qualification/package_link_budget.py b/scripts/qualification/package_link_budget.py new file mode 100644 index 00000000..6652c843 --- /dev/null +++ b/scripts/qualification/package_link_budget.py @@ -0,0 +1,163 @@ +"""Package exact Node sources for isolated, opt-in Worker 006 qualification.""" + +import argparse +import hashlib +import json +import shlex +import tarfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +NODE = ROOT / "apps/node-agent" +NETEM_IMAGE = "sha256:264a1dac982cafa1594654a728ba487fdddf04fc05476daba377f2b04bd2f917" +IMAGE = "sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=ROOT / "outputs/link-budget-qualification") + parser.add_argument("--suite", choices=["budget", "transport", "contention"], default="budget") + parser.add_argument("--run-pattern") + parser.add_argument("--skip-pattern", default="") + args = parser.parse_args() + output = args.output + output.mkdir(parents=True, exist_ok=True) + toolchain = json.loads((NODE / "packaging/linux-toolchains.json").read_text())["files"][0] + compiler = NODE / "build/linux-toolchains" / toolchain["name"] + assert hashlib.sha256(compiler.read_bytes()).hexdigest() == toolchain["sha256"] + sources = { + str(p.relative_to(NODE)): p + for p in (NODE / "internal").rglob("*") + if p.is_file() and p.suffix in {".go", ".json"} + } + sources["go.mod"] = NODE / "go.mod" + qualification = { + "budget": "link_budget_load_test.go", + "contention": "rover_contention_test.go", + "transport": "rover_transport_test.go", + }[args.suite] + sources["internal/node/worker_" + qualification] = ROOT / "tests/qualification" / qualification + if args.suite in ("transport", "contention"): + sources["internal/node/worker_rover_datagram_test.go"] = ( + ROOT / "tests/qualification/rover_datagram_test.go" + ) + if args.suite == "contention": + sources["internal/node/worker_rover_transport_test.go"] = ( + ROOT / "tests/qualification/rover_transport_test.go" + ) + sources["internal/node/worker_rover_connect_test.go"] = ( + ROOT / "tests/qualification/rover_connect_test.go" + ) + fixtures = { + f"plugins/{plugin}/{name}": ROOT / "plugins" / plugin / name + for plugin in ("vesc", "usb-can") + for name in ("runtime/__init__.py", "packaging/prepare.py") + } + image = NETEM_IMAGE if args.suite == "contention" else IMAGE + go_timeout = "180s" if args.suite == "contention" else "90s" + capability = ( + "--cap-add NET_ADMIN --env MISSION_CORE_ISOLATED_NETEM=1 " + if args.suite == "contention" else "" + ) + selection = { + "budget": ("^(TestWorker|TestMedia|TestLink|TestBudgetReader|TestDev|TestRoverStream" + "|TestHeartbeat|TestOldHeartbeat)"), + "contention": ( + "^(TestWorkerContentionMatrix|TestWorkerTransport|TestRover|TestLink|TestCommand)" + ), + "transport": ("^(TestWorkerTransport|TestRoverStream|TestRoverLocalDelivery" + "|TestDelayedHTTPClock|TestObservationClock)"), + }[args.suite] + selection = args.run_pattern or selection + manifest = { + "schema": "missioncore.worker-link-qualification/v1", + "image": image, + "network_scope": "isolated-loopback-only" if args.suite == "contention" else "none", + "capability": "NET_ADMIN" if args.suite == "contention" else None, + "suite": args.suite, + "selection": selection, + "skip": args.skip_pattern, + "builder_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "toolchain": toolchain, + "sources": {k: hashlib.sha256(p.read_bytes()).hexdigest() for k, p in sources.items()}, + "source_root": "apps/node-agent", + "fixtures": {k: hashlib.sha256(p.read_bytes()).hexdigest() for k, p in fixtures.items()}, + "limits": {"cpus": 2, "memory": "2g", "pids": 256, "seconds": 240, "network": "none"}, + } + identity = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()[:20] + folder = output / ("worker-" + identity) + folder.mkdir(exist_ok=False) + with tarfile.open(folder / "source.tar", "w") as tar: + for name, p in sorted(sources.items()): + tar.add(p, arcname="apps/node-agent/" + name, recursive=False) + for name, p in sorted(fixtures.items()): + tar.add(p, arcname=name, recursive=False) + (folder / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + (folder / "run.sh").write_text("""#!/bin/sh +set -eu +mkdir -p /work/source /work/toolchain /work/cache /work/tmp +tar --no-same-owner -xzf /input/go.tar.gz -C /work/toolchain +tar --no-same-owner -xf /input/source.tar -C /work/source +export GOROOT=/work/toolchain/go GOCACHE=/work/cache GOTMPDIR=/work/tmp +export GOPROXY=off GOTOOLCHAIN=local CGO_ENABLED=0 GOMAXPROCS=2 +cd /work/source/apps/node-agent +selection=@SELECTION@ +skip=@SKIP@ +timeout 240 /work/toolchain/go/bin/go test -p 1 -count=1 -timeout=@GO_TIMEOUT@ -v \\ + ./internal/node -run "$selection" -skip "$skip" +""".replace("@SELECTION@", shlex.quote(selection)).replace("@GO_TIMEOUT@", go_timeout) + .replace("@SKIP@", shlex.quote(args.skip_pattern))) + files = { + name: hashlib.sha256((folder / name).read_bytes()).hexdigest() + for name in ["source.tar", "manifest.json", "run.sh"] + } + files["go.tar.gz"] = toolchain["sha256"] + (folder / "files.json").write_text(json.dumps(files, indent=2) + "\n") + # The script owns this one container. It mounts only immutable test inputs, + # has no GPU/host sockets/credentials or network and always removes itself. + runner_script = ( + """$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $MyInvocation.MyCommand.Path +$files = Get-Content (Join-Path $root 'files.json') -Raw | ConvertFrom-Json +foreach ($entry in $files.PSObject.Properties) { + $hash = (Get-FileHash (Join-Path $root $entry.Name) -Algorithm SHA256).Hash.ToLower() + if ($hash -ne $entry.Value) { throw 'Qualification input changed' } +} +$name = 'ndc-mission-core-link-budget-""" + + identity + + "'\n" + + """$started = [DateTime]::UtcNow.ToString('o') +try { + $ErrorActionPreference = 'Continue' + & docker run --rm --pull never --name $name ` + --label com.nodedc.product=mission-core --label com.nodedc.role=qualification ` + --network none --cap-drop ALL @CAPABILITY@--security-opt no-new-privileges ` + --cpus 2 --memory 2g --pids-limit 256 --read-only ` + --tmpfs /work:rw,exec,size=1536m --tmpfs /tmp:rw,size=16m ` + --mount "type=bind,source=$root,target=/input,readonly" --entrypoint /bin/sh """ + + image + + """ /input/run.sh 2>&1 | Out-File (Join-Path $root 'result.log') -Encoding utf8 + $exit = $LASTEXITCODE + $ErrorActionPreference = 'Stop' + @{ + started_at=$started;finished_at=[DateTime]::UtcNow.ToString('o') + exit_code=$exit;container=$name + result_sha256=(Get-FileHash (Join-Path $root 'result.log') -Algorithm SHA256).Hash.ToLower() + } | ConvertTo-Json | Set-Content (Join-Path $root 'result.json') -Encoding utf8 + if ($exit -ne 0) { throw 'Worker qualification failed; preserve result.log' } +} finally { + $ErrorActionPreference = 'Continue' + & docker rm -f $name 2>$null | Out-Null +} +""" + ) + (folder / "run.ps1").write_text(runner_script.replace("@CAPABILITY@", capability)) + print( + json.dumps( + {"id": identity, "folder": str(folder), "toolchain": str(compiler), "files": files} + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/qualification/passive_runtime.py b/scripts/qualification/passive_runtime.py new file mode 100644 index 00000000..d6d7f8f7 --- /dev/null +++ b/scripts/qualification/passive_runtime.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Bounded live runtime evidence; no motor-authority or camera-capture commands. + +Optional disposable viewing peer, owned DEV sessions, and read-only /proc sampling. +Never retain images, SDP, endpoints, credentials or packet payloads in evidence. +""" + +import argparse +import asyncio +import datetime +import hashlib +import ipaddress +import json +import subprocess +import time +import urllib.request +import uuid +from pathlib import Path + +BOARD_SAMPLE = r"""import json,time +from pathlib import Path +for i in range(900): + out={"utc":time.time(),"mono":time.monotonic(),"kind":"board"} + out["cpu"]=Path("/proc/stat").read_text().splitlines()[0] + out["load"]=Path("/proc/loadavg").read_text().strip() + out["pressure"]={k:Path("/proc/pressure/"+k).read_text().strip() for k in ("cpu","memory","io")} + out["net"]={} + for row in Path("/proc/net/dev").read_text().splitlines()[2:]: + interface, data = row.split(":") + if interface.strip() in ("wlp2s0", "tailscale0"): + out["net"][interface.strip()] = [int(x) for x in data.split()] + out["services"]={} + for service in ("mission-core-node","mission-core-vesc","mission-core-insta360"): + root=Path("/sys/fs/cgroup/system.slice/"+service+".service") + try:out["services"][service]={"cpu":root.joinpath("cpu.stat").read_text().strip(),"memory":int(root.joinpath("memory.current").read_text())} + except OSError:out["services"][service]={"unavailable":True} + print(json.dumps(out,separators=(",",":")),flush=True) + time.sleep(1) +""" + + +def request(base, path, body=None): + raw = None if body is None else json.dumps(body).encode() + req = urllib.request.Request( + base + path, data=raw, headers={"Content-Type": "application/json"} + ) + with urllib.request.urlopen(req, timeout=15) as reply: + return json.load(reply) + + +def stamp(): + return {"utc": time.time(), "mono": time.monotonic()} + + +async def run(args): + import aioice.ice + from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription + + host_addresses = aioice.ice.get_host_addresses + networks = tuple( + ipaddress.ip_network(v) + for v in ("127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10") + ) + # Match the product's IPv4/private-only admission; a Mac VPN IPv6 + # candidate is not a valid X4 offer. This affects only this probe process. + aioice.ice.get_host_addresses = lambda use_ipv4, use_ipv6: [ + v + for v in host_addresses(use_ipv4=True, use_ipv6=False) + if any(ipaddress.ip_address(v) in n for n in networks) + ] + root = args.output.resolve() + root.mkdir(parents=True, exist_ok=False) + started = stamp() + manifest = { + "schema": "missioncore.passive-runtime/v1", + "id": uuid.uuid4().hex, + "started": started, + "motor_commands": False, + "viewing_peer": not (args.telemetry_only or args.no_viewer), + "phase_seconds": args.seconds, + "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "limitations": [ + "Existing operator viewer is measured separately; no additional peer." + if args.no_viewer + else "Additional viewing peer; existing operator viewer is preserved.", + "Frame arrival gaps are not capture-to-screen latency.", + "SSH sampler is low-volume but shares the network.", + ], + } + pc = RTCPeerConnection(RTCConfiguration(iceServers=[])) + tasks, peer, device, owned, ssh = [], None, None, None, None + phase = "setup" + frames, last_frame = 0, None + events = root.joinpath("samples.jsonl").open("x") + board_file = root.joinpath("board.jsonl").open("xb") + board_error = root.joinpath("board.stderr").open("xb") + + def emit(kind, **fields): + events.write( + json.dumps({**stamp(), "kind": kind, "phase": phase, **fields}, separators=(",", ":")) + + "\n" + ) + events.flush() + + async def api(path="", body=None): + return await asyncio.to_thread(request, args.core, path, body) + + rover = "/" + args.vehicle + "/rover" + operations = "/" + args.vehicle + "/devices/operations" + + async def operation(action, parameters): + if action not in {"offer", "close-peer"}: + raise ValueError("Passive probe cannot execute device commands") + now = datetime.datetime.now(datetime.UTC) + identifier = "op_" + uuid.uuid4().hex + command = { + "api_version": "missioncore.nodedc/plugin-sdk/v0alpha2", + "kind": "OperationRequest", + "operation_id": identifier, + "idempotency_key": identifier, + "session": { + "session_id": device["snapshot"]["context"]["session_id"], + "device_id": device["id"], + }, + "action_id": action, + "requested_at": now.isoformat(), + "deadline_at": (now + datetime.timedelta(seconds=20)).isoformat(), + "parameters": parameters, + } + emit("view_operation", action=action, operation_id=identifier) + result = await api(operations, command) + deadline = time.monotonic() + 30 + while result["state"] in {"running", "queued"} and time.monotonic() < deadline: + await asyncio.sleep(0.5) + result = await api(operations + "/" + identifier) + if result["state"] != "complete": + raise RuntimeError( + "Viewing operation failed: " + str(result.get("error", result["state"])) + ) + return result.get("result") + + async def stop_owned(): + nonlocal owned + if owned is None: + return + current = await api(rover + "/diagnostics") + if current["id"] == owned and current["active"]: + await api(rover + "/diagnostics", {"enabled": False}) + deadline = time.monotonic() + 600 + while time.monotonic() < deadline: + current = await api(rover + "/diagnostics") + if current["id"] != owned: + raise RuntimeError("DEV ownership changed") + if not current["active"] and not current["closing"]: + emit( + "capture_closed", + capture_id=owned, + storage=current.get("node", {}).get("storage"), + ) + owned = None + return + await asyncio.sleep(1) + raise RuntimeError("Owned DEV tail has not closed") + + @pc.on("track") + def track(value): + async def consume(): + nonlocal frames, last_frame + try: + while True: + frame = await value.recv() + now = time.monotonic() + frames += 1 + emit( + "video_frame", + width=frame.width, + height=frame.height, + gap_ms=None if last_frame is None else (now - last_frame) * 1000, + ) + last_frame = now + except asyncio.CancelledError: + raise + except Exception as error: + emit("video_ended", error=type(error).__name__) + + tasks.append(asyncio.create_task(consume())) + + channel = pc.createDataChannel("sensor", ordered=False, maxRetransmits=0) + + @channel.on("message") + def message(value): + try: + emit("media", value=json.loads(value)) + except (TypeError, ValueError): + emit("invalid_media") + + async def keepalive(): + while True: + if channel.readyState == "open": + channel.send("keepalive") + channel.send("view:secondary") + await asyncio.sleep(2) + + try: + initial = await api(rover) + if not args.telemetry_only and ( + not initial.get("fresh") + or initial.get("controlling") + or initial.get("snapshot", {}).get("control_active") + ): + raise RuntimeError("Fresh inactive rover required") + dev = await api(rover + "/diagnostics") + if not args.telemetry_only and (dev["active"] or dev["closing"]): + raise RuntimeError("Preserve another DEV capture") + if not args.telemetry_only: + fleet = await api() + vehicle = next(v for v in fleet["items"] if v["id"] == args.vehicle) + device = next( + v for v in vehicle["sensor_state"]["items"] if v.get("kind") == "insta360.x4" + ) + if not device["online"] or device["snapshot"]["acquisition"] != "streaming": + raise RuntimeError("Existing camera preview required; probe never starts capture") + ssh = subprocess.Popen( + ["ssh", "-F", str(args.ssh_config.resolve()), args.ssh_host, "python3 -u -"], + stdin=subprocess.PIPE, + stdout=board_file, + stderr=board_error, + ) + ssh.stdin.write(BOARD_SAMPLE.encode()) + ssh.stdin.close() + if not (args.telemetry_only or args.no_viewer): + pc.addTransceiver("video", direction="recvonly") + await pc.setLocalDescription(await pc.createOffer()) + answer = await operation( + "offer", {"sdp": pc.localDescription.sdp, "layer": "preview", "primary": False} + ) + peer = answer["peer_id"] + await pc.setRemoteDescription(RTCSessionDescription(sdp=answer["sdp"], type="answer")) + tasks.append(asyncio.create_task(keepalive())) + phases = ( + [("baseline", None)] + if args.baseline_only + else [ + ("baseline", None), + ( + "local", + dict( + live=False, + core_trace=False, + motor_samples=True, + network=True, + live_kbps=16, + core_kbps=16, + ), + ), + ( + "core_trace", + dict( + live=False, + core_trace=True, + motor_samples=True, + network=True, + live_kbps=8, + core_kbps=8, + ), + ), + ( + "live", + dict( + live=True, + core_trace=False, + motor_samples=True, + network=True, + live_kbps=8, + core_kbps=8, + ), + ), + ] + ) + if args.dev_matrix: + + def options(*, core=False, live=False, rate=8): + return dict( + live=live, + core_trace=core, + motor_samples=True, + network=True, + live_kbps=rate, + core_kbps=rate, + ) + + phases = [ + ("baseline", None), + ("local", options()), + ("core_trace_8", options(core=True)), + ("live_8", options(live=True)), + ("core_live_8", options(core=True, live=True)), + ("core_live_64", options(core=True, live=True, rate=64)), + ("baseline_repeat", None), + ] + manifest["limitations"].append( + "Stationary passive comparison: not audit T1-T6 with a neutral control session." + ) + for phase_name, options in phases: + phase = phase_name + if options: + current = await api(rover + "/diagnostics") + if current["active"] or current["closing"]: + raise RuntimeError("Preserve another DEV capture") + capture = await api(rover + "/diagnostics", {"enabled": True, "options": options}) + owned = capture["id"] + emit("capture_started", capture_id=owned, options=options) + deadline = time.monotonic() + args.seconds + while time.monotonic() < deadline: + at = time.monotonic() + value = await api(rover) + emit( + "rover", + elapsed_ms=(time.monotonic() - at) * 1000, + value=value, + peer_state=pc.connectionState, + frames=frames, + ) + if not args.telemetry_only and ( + value.get("controlling") or value.get("snapshot", {}).get("control_active") + ): + raise RuntimeError("Operator control became active; passive comparison stopped") + if owned: + dev = await api(rover + "/diagnostics") + if dev["id"] != owned: + raise RuntimeError("DEV ownership changed") + emit( + "dev", + capture_id=owned, + active=dev["active"], + closing=dev["closing"], + rows=len(dev.get("frames", [])), + dropped=dev.get("dropped"), + node=dev.get("node"), + ) + await asyncio.sleep(max(0, 0.5 - (time.monotonic() - at))) + await stop_owned() + manifest["outcome"] = "complete" + except Exception as error: + manifest["outcome"] = "interrupted" + manifest["error"] = str(error) + finally: + phase = "cleanup" + try: + await stop_owned() + except Exception as error: + manifest["capture_cleanup_error"] = str(error) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await pc.close() + aioice.ice.get_host_addresses = host_addresses + if peer: + try: + await operation("close-peer", {"peer_id": peer}) + except Exception as error: + manifest["peer_cleanup_error"] = str(error) + if ssh: + ssh.terminate() + try: + ssh.wait(timeout=5) + except subprocess.TimeoutExpired: + ssh.kill() + ssh.wait(timeout=5) + manifest["collector_exit"] = ssh.returncode + board_file.close() + board_error.close() + events.close() + manifest["finished"] = stamp() + manifest["frames"] = frames + manifest["files"] = { + p.name: { + "bytes": p.stat().st_size, + "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), + } + for p in root.iterdir() + if p.is_file() + } + root.joinpath("manifest.json").write_text(json.dumps(manifest, indent=2)) + print(json.dumps(manifest, ensure_ascii=False), flush=True) + return 0 if manifest["outcome"] == "complete" else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--core", default="http://127.0.0.1:8000/api/v1/fleet") + parser.add_argument("--vehicle", required=True) + parser.add_argument("--ssh-config", type=Path, required=True) + parser.add_argument("--ssh-host", default="rover-006") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seconds", type=int, default=45) + parser.add_argument("--baseline-only", action="store_true") + parser.add_argument( + "--no-viewer", + action="store_true", + help="No offer or secondary viewer; observe the existing browser separately", + ) + parser.add_argument( + "--dev-matrix", + action="store_true", + help="Passive DEV direction/rate comparison; never arms a neutral session", + ) + parser.add_argument( + "--telemetry-only", + action="store_true", + help="Read-only baseline: no viewer or DEV operations; operator control may continue", + ) + args = parser.parse_args() + if args.dev_matrix and (args.baseline_only or args.telemetry_only): + parser.error("DEV matrix cannot be combined with baseline-only or telemetry-only") + if args.telemetry_only and not args.baseline_only: + parser.error("Telemetry-only requires baseline-only") + if not 10 <= args.seconds <= 90: + parser.error("Phase must last 10..90 seconds") + return asyncio.run(run(args)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/k1link/fleet/channel_binding.py b/src/k1link/fleet/channel_binding.py new file mode 100644 index 00000000..b0688e8b --- /dev/null +++ b/src/k1link/fleet/channel_binding.py @@ -0,0 +1,40 @@ +"""Shared authorization checks for durable and real-time Node channels.""" +import time + +from cryptography import x509 + +from .trust import SCHEMA + + +def authenticate(row, node_id, serial, value): + if (row is None or row["enrollment"] not in ("pending", "paired") + or value.get("node_id") != node_id + or value.get("binding_id") != row["binding"]["binding_id"]): + return 410, {"error": "Binding revoked"} + allowed = [row["binding"]["client_pem"]] + previous = row.get("certificate_previous") + if previous and previous["until"] > time.time(): + allowed.append(previous["pem"]) + if serial not in [x509.load_pem_x509_certificate(item.encode()).serial_number + for item in allowed]: + return 403, {"error": "Certificate superseded"} + if value.get("schema") != SCHEMA: + return 400, {"error": "Incompatible protocol"} + return None + + +def endpoint_error(row, value, address): + from .recovery import tailnet_address + + revision = value.get("endpoint_revision", 0) + if type(revision) is not int or not 0 <= revision <= 1000000000: + return 400, {"error": "Invalid endpoint revision"} + previous = row["binding"].get("endpoint_revision", 0) + if revision < previous: + return 409, {"error": "Endpoint superseded"} + if revision > previous and ( + not (tailnet_address(address) or any(path.get("core") == address for path in row.get("network_paths", {}).values())) + or value.get("core_endpoint") != f"https://{address}:8782" + ): + return 400, {"error": "Endpoint does not match authenticated channel"} + return None diff --git a/src/k1link/fleet/heartbeat_encoding.py b/src/k1link/fleet/heartbeat_encoding.py new file mode 100644 index 00000000..a78b04ad --- /dev/null +++ b/src/k1link/fleet/heartbeat_encoding.py @@ -0,0 +1,21 @@ +"""Bounded, negotiated compression for the existing full Node heartbeat.""" + +import zlib + +MAX_HEARTBEAT_BYTES = 8 * 1024 * 1024 + + +def decode_heartbeat(body: bytes, encoding: str, path: str) -> bytes: + if not encoding: + return body + if encoding != "gzip" or path != "/v1/node/heartbeat": + raise ValueError("Unsupported encoding") + try: + stream = zlib.decompressobj(16 + zlib.MAX_WBITS) + decoded = stream.decompress(body, MAX_HEARTBEAT_BYTES + 1) + if (len(decoded) > MAX_HEARTBEAT_BYTES or not stream.eof + or stream.unused_data or stream.unconsumed_tail): + raise ValueError("Invalid compressed heartbeat") + return decoded + except zlib.error as error: + raise ValueError("Invalid compressed heartbeat") from error diff --git a/src/k1link/fleet/network_client.py b/src/k1link/fleet/network_client.py new file mode 100644 index 00000000..29268527 --- /dev/null +++ b/src/k1link/fleet/network_client.py @@ -0,0 +1,77 @@ +"""Bounded access to the installed WireGuard system helper.""" +import json +import hashlib +import os +import platform +import shlex +import socket +import subprocess +import shutil +import tempfile +import time +from pathlib import Path + +SOCKET = "/var/run/ndc-mission-wireguard.sock" + + +def request(action, server_id, **values): + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(25) + connection.connect(SOCKET) + connection.sendall(json.dumps({"action": action, "server_id": server_id, **values}).encode() + b"\n") + with connection.makefile("rb") as stream: + data = stream.readline(16385) + if len(data) > 16384 or not data.endswith(b"\n"): + raise ValueError("Некорректный ответ сетевой службы.") + result = json.loads(data) + if not result.get("ok"): + raise ValueError("Не удалось применить сетевой профиль: " + result.get("error", "ошибка службы")) + return result["result"] + + +def ensure(): + source = Path(__file__).resolve().parents[3] / "apps/wireguard-client" + if Path(SOCKET).is_socket(): + try: + status = request("health", "") + if status.get("sha256") == hashlib.sha256((source / "helper.py").read_bytes()).hexdigest(): + return + except (ValueError, OSError): + pass + if platform.system() != "Darwin" or platform.machine() != "arm64": + raise ValueError("Подготовка компьютера поддерживает macOS Apple Silicon.") + source = Path(__file__).resolve().parents[3] / "apps/wireguard-client" + # Administrator processes cannot read macOS protected Downloads. The app + # stages only its reviewed installer payload before asking for OS authorization. + with tempfile.TemporaryDirectory(prefix="ndc-wireguard-install-", dir="/private/tmp") as folder: + staging = Path(folder) + for name in ("install_macos.py", "helper.py"): + shutil.copyfile(source / name, staging / name) + shutil.copytree(source / "build/macos-arm64", staging / "build/macos-arm64") + command = shlex.join(["/usr/bin/python3", str(staging / "install_macos.py"), "--uid", str(os.getuid())]) + script = "do shell script " + json.dumps(command) + " with administrator privileges" + result = subprocess.run(["/usr/bin/osascript", "-e", script], capture_output=True, timeout=180) + if result.returncode: + raise ValueError("Системная установка WireGuard не завершена. Подтвердите запрос администратора macOS и повторите импорт.") + for _ in range(40): + if Path(SOCKET).is_socket(): + try: + if request("health", "").get("sha256") == hashlib.sha256((source / "helper.py").read_bytes()).hexdigest(): + return + except (ValueError, OSError): + pass + time.sleep(0.25) + raise ValueError("Системная служба WireGuard пока не запущена.") + + +def verify_tunnel(config): + """Probe only the isolated gateway, explicitly using the fleet source address.""" + import ipaddress + gateway = str(ipaddress.ip_network(config["subnet"])[1]) + for _ in range(3): + result = subprocess.run(["/sbin/ping", "-n", "-c", "1", "-W", "1500", "-S", config["address"], gateway], + capture_output=True, timeout=4) + status = request("status", config["server_id"]) + if result.returncode == 0 and time.time() - status.get("last_handshake", 0) < 180: + return + raise ValueError("Сервер отвечает, но туннель WireGuard не установлен. Проверьте доступность UDP 51830 на VPS. Прежнее подключение сохранено.") diff --git a/src/k1link/fleet/network_media.py b/src/k1link/fleet/network_media.py new file mode 100644 index 00000000..f746185c --- /dev/null +++ b/src/k1link/fleet/network_media.py @@ -0,0 +1,55 @@ +"""Constrain board media signalling to its acknowledged private network path.""" +import copy +import re +from urllib.parse import urlsplit +from .trust import PairingError + + +def filter_sdp(sdp, address, *, browser_offer=False): + if not isinstance(sdp, str) or not 1 <= len(sdp) <= 32768: + raise PairingError("Некорректное подключение просмотра.") + lines, admitted, hidden_hosts = [], 0, False + for line in sdp.splitlines(): + if line.startswith("a=candidate:"): + fields = line.split() + if (len(fields) >= 8 and fields[7] == "host" and fields[2].lower() == "udp" + and re.fullmatch(r"[A-Za-z0-9-]{1,63}\.local", fields[4])): + hidden_hosts = True + if len(fields) < 8 or fields[4] != address or fields[7] != "host" or fields[2].lower() != "udp": + continue + admitted += 1 + if line.startswith("a=remote-candidates:"): + continue + if line.startswith("c=IN IP4 "): + line = "c=IN IP4 " + address + lines.append(line) + if not admitted and browser_offer and hidden_hosts: + # Browsers mask local addresses with mDNS. Never resolve or relabel an + # unrelated interface. Only the Node's exact WG candidate is returned; + # its authenticated ICE checks learn the Core's WG peer-reflexive address. + # Keep gathering open so the receiver can wait for that incoming check. + lines = [line for line in lines if line != "a=end-of-candidates"] + elif not admitted: + raise PairingError("Просмотр не получил адрес выбранной сети. Проверьте WireGuard и откройте просмотр заново.") + return "\r\n".join(lines) + "\r\n" + + +def selected_path(row): + address = urlsplit(row.get("binding", {}).get("endpoint", "")).hostname + return next((p for p in row.get("network_paths", {}).values() if p.get("core") == address), None) + + +def offer(row, value): + path = selected_path(row) + if path and value.get("action_id") == "offer": + value = copy.deepcopy(value) + value["parameters"]["sdp"] = filter_sdp(value["parameters"].get("sdp"), path["core"], browser_offer=True) + return value + + +def answer(row, value): + path = selected_path(row) + if path and value.get("command", {}).get("action_id") == "offer" and value.get("state") == "complete": + value = copy.deepcopy(value) + value["result"]["sdp"] = filter_sdp(value["result"].get("sdp"), path["node"]) + return value diff --git a/src/k1link/fleet/network_profiles.py b/src/k1link/fleet/network_profiles.py new file mode 100644 index 00000000..e24a8be8 --- /dev/null +++ b/src/k1link/fleet/network_profiles.py @@ -0,0 +1,358 @@ +"""Shared VPS profiles and bounded board network transactions. Worker is not a consumer.""" +import base64 +import copy +import ipaddress +import json +import re +import secrets +import threading +import time +from urllib.parse import urlsplit + +from . import network_client +from .trust import atomic_private +from .vps_transport import request, interfaces + +SCHEMA = "missioncore.wireguard-connect/v1" + + +def parse_file(raw): + if not isinstance(raw, str) or len(raw.encode()) > 16384: + raise ValueError("Файл подключения слишком большой.") + value = json.loads(raw) + required = {"schema", "server_id", "endpoint", "vpn_endpoint", "fingerprint", "server_public_key", "subnet", "bootstrap", "expires_at"} + if not isinstance(value, dict) or not required <= set(value) or set(value) - required - {"capacity"} or value["schema"] != SCHEMA: + raise ValueError("Выберите файл подключения WireGuard, созданный установщиком VPS.") + if any(not isinstance(value[k], str) for k in required - {"expires_at"}): + raise ValueError("Некорректный формат файла подключения.") + if not re.fullmatch(r"wg_[a-f0-9]{32}", value["server_id"]) or not re.fullmatch(r"[a-f0-9]{64}", value["fingerprint"]): + raise ValueError("Некорректная идентичность сервера.") + if not re.fullmatch(r"[A-Za-z0-9_-]{43}", value["bootstrap"]): + raise ValueError("Некорректный ключ подключения.") + if type(value["expires_at"]) is not int or ("capacity" in value and (type(value["capacity"]) is not int or value["capacity"] < 1)): + raise ValueError("Несовместимый файл подключения.") + if len(base64.b64decode(value["server_public_key"], validate=True)) != 32: + raise ValueError("Некорректный ключ WireGuard.") + network = ipaddress.ip_network(value["subnet"]) + if network.version != 4 or network.prefixlen != 24 or not network.subnet_of(ipaddress.ip_network("10.203.0.0/16")): + raise ValueError("Неподдерживаемая адресация парка.") + endpoint = urlsplit(value["endpoint"]) + if endpoint.scheme != "https" or endpoint.port != 19444 or not endpoint.hostname or endpoint.username or endpoint.password or endpoint.path or endpoint.query or endpoint.fragment: + raise ValueError("Некорректный адрес сервера.") + if value["vpn_endpoint"] != endpoint.hostname + ":51830": + raise ValueError("Адреса сервера не согласованы.") + # Old connection files carried an illustrative quota; it is not a fleet policy. + value.pop("capacity", None) + return value + + +class NetworkProfiles: + def __init__(self, fleet): + self.fleet = fleet + self.root = fleet.root / "networks" + self.root.mkdir(mode=0o700, exist_ok=True) + self.path = self.root / "profiles.json" + self.lock = threading.RLock() + self.changed = threading.Condition(self.lock) + self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {} + self.latest = {} + self.commands = {} + self.operations = {} + self.workers = {} + self.import_lock = threading.Lock() + self.sync_lock = threading.RLock() + self.revoke_retry = {} + + def save(self): + atomic_private(self.path, json.dumps(self.profiles).encode()) + + def revoke_node(self, node_id): + with self.lock: + changed = False + for row in self.profiles.values(): + if any(p["id"] == node_id for p in row.get("status", {}).get("peers", [])): + pending = row.setdefault("revocations", []) + if node_id not in pending: + pending.append(node_id) + changed = True + if changed: + self.save() + + def reconcile(self): + # Durable revocation retries run outside registry/control locks. + now = time.monotonic() + with self.lock: + candidates = [copy.deepcopy(row) for row in self.profiles.values() + if row.get("revocations") and now >= self.revoke_retry.get(row["server_id"], 0)] + for row in candidates: + if self.fleet.stop.is_set(): + return + node_id = row["revocations"][0] + with self.lock: + self.revoke_retry[row["server_id"]] = now + 30 + try: + status = self.call(row, "DELETE", "/v1/peers/" + node_id) + self.sync_operator(row, status) + with self.lock: + current = self.profiles[row["server_id"]] + if node_id in current.get("revocations", []): + current["revocations"].remove(node_id) + self.save() + except (ValueError, OSError): + continue + + def public(self, row): + status = row.get("status") or {} + return {"id": row["server_id"], "name": row["name"], "endpoint": row["endpoint"], + "state": row["state"], + "boards": len([p for p in status.get("peers", []) if p["kind"] == "node"]), + "network_interface": row.get("network_interface"), "last_verified": row.get("last_verified")} + + def listing(self): + with self.lock: + return [self.public(row) for row in self.profiles.values()] + + def verify_status(self, row, value): + if not isinstance(value, dict) or value.get("schema") != "missioncore.wireguard-status/v1" or value.get("server_id") != row["server_id"] or value.get("server_public_key") != row["server_public_key"] or value.get("subnet") != row["subnet"]: + raise ValueError("Сервер вернул другую идентичность профиля.") + peers = value.get("peers") + if not isinstance(peers, list) or len(peers) > ipaddress.ip_network(row["subnet"]).num_addresses - 4: + raise ValueError("Некорректный список участников.") + network = ipaddress.ip_network(row["subnet"]) + seen_ids, seen_keys, seen_addresses = set(), set(), set() + if value.get("server_address") != str(network[1]): + raise ValueError("Некорректный адрес шлюза.") + for peer in peers: + address = ipaddress.ip_address(peer["address"]) + if (address not in network or peer["kind"] not in ("core", "node") + or (peer["kind"] == "core" and (peer["id"] != self.fleet.trust.core_id or address != network[2])) + or (peer["kind"] == "node" and not network[3] <= address <= network[253]) + or peer["id"] in seen_ids or peer["public_key"] in seen_keys or str(address) in seen_addresses + or len(base64.b64decode(peer["public_key"], validate=True)) != 32): + raise ValueError("Некорректная адресация участника.") + seen_ids.add(peer["id"]); seen_keys.add(peer["public_key"]); seen_addresses.add(str(address)) + return value + + def call(self, row, method, path, body=None): + return self.verify_status(row, request(row, method, path, body)) + + def operator_config(self, row, status): + core = next((p for p in status["peers"] if p["id"] == self.fleet.trust.core_id and p["kind"] == "core"), None) + if core is None: + raise ValueError("Сервер не подтвердил этот Mission Core.") + local = network_client.request("status", row["server_id"]) + if core["public_key"] != local["public_key"]: + raise ValueError("Сервер не подтвердил ключ этого Core.") + addresses = [status["server_address"] + "/32"] + [p["address"] + "/32" for p in status["peers"] if p["kind"] == "node"] + return {"server_id": row["server_id"], "address": core["address"], "subnet": row["subnet"], + "server_public_key": row["server_public_key"], "endpoint": row["vpn_endpoint"], + "allowed_ips": addresses, "role": "core", "interface": row.get("network_interface")} + + def sync_operator(self, row, status): + with self.sync_lock: + config = self.operator_config(row, status) + operation = secrets.token_hex(16) + network_client.request("stage", row["server_id"], config=config, operation_id=operation) + try: + network_client.verify_tunnel(config) + with self.fleet.lock: + self.fleet.listen(config["address"]) + with self.lock: + current = self.profiles[row["server_id"]] + previous = copy.deepcopy(current) + current.update(status=status, state="ready", last_verified=time.time()) + try: + self.save() + network_client.request("confirm", row["server_id"], operation_id=operation) + except Exception: + self.profiles[row["server_id"]] = previous + self.save() + raise + except Exception: + network_client.request("rollback", row["server_id"], operation_id=operation) + raise + return config + + def import_file(self, raw, name="", interface=None): + if not self.import_lock.acquire(blocking=False): + raise ValueError("Дождитесь завершения импорта профиля.") + previous = copy.deepcopy(self.profiles) + try: + return self._import_file(raw, name, interface) + except Exception: + # A failed new claim keeps its retry token; an existing active profile + # retains its last verified endpoint and peer set. + with self.lock: + for identity, row in previous.items(): + if row.get("state") == "ready": + self.profiles[identity] = row + self.save() + raise + finally: + self.import_lock.release() + + def _import_file(self, raw, name="", interface=None): + value = parse_file(raw) + with self.lock: + old = self.profiles.get(value["server_id"]) + if old and (old["fingerprint"] != value["fingerprint"] or old["server_public_key"] != value["server_public_key"]): + raise ValueError("Ключи существующего сервера изменились. Профиль сохранён без изменений.") + if not old and value["expires_at"] <= time.time(): + raise ValueError("Файл подключения просрочен. Получите новый файл на VPS.") + if any(p["server_id"] != value["server_id"] and p["subnet"] == value["subnet"] for p in self.profiles.values()): + raise ValueError("Адресация совпадает с другим подключённым VPS.") + row = {**value, "name": name.strip()[:80] or (old or {}).get("name") or "WireGuard · " + urlsplit(value["endpoint"]).hostname, + "token": (old or {}).get("token") or secrets.token_urlsafe(32), + "state": (old or {}).get("state", "pending"), "network_interface": interface or (old or {}).get("network_interface")} + # Persist the retry credential before either administrator interaction or claim. + self.profiles[value["server_id"]] = row + self.save() + network_client.ensure() + local = network_client.request("prepare", row["server_id"]) + claim = {"core_id": self.fleet.trust.core_id, "public_key": local["public_key"], + "credential": row["token"], "bootstrap": row["bootstrap"]} + candidates = [row.get("network_interface")] + if not candidates[0]: + candidates += [item["id"] for item in interfaces() if re.fullmatch(r"en[0-9]+", item["id"])] + failure = None + for selected in candidates: + try: + row["network_interface"] = selected + status = self.call(row, "POST", "/v1/claim", claim) + break + except (OSError, ValueError) as error: + failure = error + else: + raise ValueError("Не удалось подключиться к VPS. Проверьте доступность сервера.") from failure + self.sync_operator(row, status) + with self.lock: + self.profiles[row["server_id"]].pop("bootstrap", None) + self.save() + return self.public(self.profiles[row["server_id"]]) + + def heartbeat(self, row, value): + snapshot = value.get("network_profile") + if isinstance(snapshot, dict) and snapshot.get("phase") in ("applied", "rolled_back"): + selected = snapshot.get("server_id") if snapshot.get("provider") == "wireguard" else "tailscale" + if selected == "tailscale" or selected in row.get("network_paths", {}): + row["network_active"] = selected + with self.changed: + if isinstance(snapshot, dict) and len(json.dumps(snapshot)) < 16384: + self.latest[row["node_id"]] = {"value": copy.deepcopy(snapshot), "received": time.monotonic(), "endpoint": value.get("core_endpoint")} + self.changed.notify_all() + command = self.commands.get(row["node_id"]) + if command and command["expires_at"] > time.time(): + return {"network_profile_change": copy.deepcopy(command)} + return {} + + def view(self, node_id): + with self.lock: + latest = self.latest.get(node_id) + return {"profiles": self.listing(), "available": bool(latest and time.monotonic() - latest["received"] < 20), + "node": copy.deepcopy(latest["value"]) if latest else None, + "operation": copy.deepcopy(self.operations.get(node_id))} + + def wait(self, node_id, operation, phase, timeout=45): + end = time.monotonic() + timeout + with self.changed: + while time.monotonic() < end and not self.fleet.stop.is_set(): + latest = self.latest.get(node_id) + value = latest["value"] if latest else {} + if value.get("operation_id") == operation: + if value.get("phase") in ("failed", "rolled_back"): + raise ValueError(value.get("error") or "Борт вернул прежнее подключение.") + if value.get("phase") == phase: + return copy.deepcopy(latest) + self.changed.wait(timeout=min(2, max(0, end - time.monotonic()))) + raise ValueError("Борт не подтвердил применение подключения.") + + def command(self, node_id, value): + with self.changed: + self.commands[node_id] = {**value, "expires_at": int(time.time()) + 110} + + def start(self, vehicle_id, provider, profile_id, expected_revision): + if provider not in ("tailscale", "wireguard"): + raise ValueError("Неизвестный способ подключения.") + with self.fleet.lock: + vehicle = copy.deepcopy(self.fleet.find(vehicle_id)) + if vehicle["enrollment"] != "paired": + raise ValueError("Сначала привяжите бортовой компьютер.") + node_id = vehicle["node_id"] + with self.lock: + if self.workers.get(node_id) and self.workers[node_id].is_alive(): + raise ValueError("Дождитесь завершения текущего переключения.") + current = self.view(node_id) + if not current["available"]: + raise ValueError("Борт недоступен или требует обновления Node.") + if current["node"].get("revision", 0) != expected_revision: + raise ValueError("Настройки борта изменились. Обновите окно.") + if provider == "wireguard" and profile_id in self.profiles and node_id in self.profiles[profile_id].get("revocations", []): + raise ValueError("Дождитесь подтверждения предыдущего отзыва доступа к VPS.") + if provider == "wireguard" and (profile_id not in self.profiles or self.profiles[profile_id]["state"] != "ready"): + raise ValueError("Сначала подключите профиль VPS.") + self.fleet.rover_control.network_change(node_id, True) + op = secrets.token_hex(16) + self.operations[node_id] = {"id": op, "state": "applying", "provider": provider, "profile_id": profile_id} + worker = threading.Thread(target=self.apply, args=(vehicle, provider, profile_id, expected_revision, op), daemon=True) + self.workers[node_id] = worker + worker.start() + return self.operations[node_id].copy() + + def apply(self, vehicle, provider, profile_id, revision, op): + node_id = vehicle["node_id"] + command = {"id": op, "provider": provider, "server_id": profile_id or "", "expected_revision": revision, "expires_at": int(time.time()) + 110} + try: + if provider == "wireguard": + with self.lock: + row = copy.deepcopy(self.profiles[profile_id]) + self.command(node_id, {**command, "action": "prepare"}) + prepared = self.wait(node_id, op, "prepared") + status = self.call(row, "POST", "/v1/peers", {"node_id": node_id, "public_key": prepared["value"]["public_key"]}) + operator = self.sync_operator(row, status) + peer = next(p for p in status["peers"] if p["id"] == node_id) + config = {"server_id": profile_id, "address": peer["address"], "subnet": row["subnet"], + "server_public_key": row["server_public_key"], "endpoint": row["vpn_endpoint"], + "allowed_ips": [status["server_address"] + "/32", operator["address"] + "/32"], "role": "node"} + endpoint = "https://" + operator["address"] + ":8782" + with self.fleet.lock: + latest = self.fleet.find(vehicle["id"]) + if latest["enrollment"] != "paired" or latest["binding"]["binding_id"] != vehicle["binding"]["binding_id"]: + self.revoke_node(node_id) + raise ValueError("Привязка БК изменилась во время подключения.") + paths = latest.setdefault("network_paths", {}) + paths[profile_id] = {"core": operator["address"], "node": peer["address"]} + self.fleet.save(latest) + self.command(node_id, {**command, "action": "apply", "config": config, "core_endpoint": endpoint}) + else: + with self.lock: + snapshot = copy.deepcopy(self.latest[node_id]["value"]) + endpoint = snapshot.get("tailscale_endpoint") + from .recovery import tailnet_address + if not isinstance(endpoint, str) or not tailnet_address(urlsplit(endpoint).hostname): + raise ValueError("Нет сохранённого подключения Tailscale к этому Core.") + with self.fleet.lock: + self.fleet.listen(urlsplit(endpoint).hostname) + self.command(node_id, {**command, "action": "apply", "core_endpoint": endpoint}) + applied = self.wait(node_id, op, "verifying", timeout=55) + if applied["endpoint"] != endpoint: + raise ValueError("Борт ответил через другое подключение.") + self.command(node_id, {**command, "action": "commit"}) + self.wait(node_id, op, "applied", timeout=30) + with self.lock: + self.operations[node_id]["state"] = "applied" + except Exception as error: + self.command(node_id, {**command, "action": "abort"}) + with self.lock: + self.operations[node_id].update(state="rolling_back", error=str(error) if isinstance(error, ValueError) else "Не удалось применить подключение.") + end = time.monotonic() + 105 + with self.changed: + while time.monotonic() < end and not self.fleet.stop.is_set(): + latest = self.latest.get(node_id, {}).get("value", {}) + if latest.get("operation_id") != op or latest.get("phase") in ("rolled_back", "failed", "prepared"): + break + self.changed.wait(timeout=1) + self.operations[node_id]["state"] = "failed" + finally: + self.fleet.rover_control.network_change(node_id, False) + with self.lock: + self.commands.pop(node_id, None) diff --git a/src/k1link/fleet/recovery.py b/src/k1link/fleet/recovery.py index 265ab91c..42169d22 100644 --- a/src/k1link/fleet/recovery.py +++ b/src/k1link/fleet/recovery.py @@ -29,6 +29,10 @@ def tailnet_address(value): def node_addresses(row): + selected = row.get("network_active") + if selected and selected != "tailscale": + path = row.get("network_paths", {}).get(selected) + return [path["node"]] if path else [] addresses = set() for network in (row.get("inventory") or {}).get("networks", [])[:64]: if not isinstance(network, dict) or not network.get("up"): @@ -83,14 +87,14 @@ def request(connection, path, body): def recover(registry, row, address, context): - if not tailnet_address(address) or address not in node_addresses(row): + if address not in node_addresses(row): raise PairingError("Нет подтверждённого адреса БК.") connection = http.client.HTTPSConnection(address, 8781, timeout=4, context=context) try: connection.connect() verify_node_certificate(connection.sock.getpeercert(binary_form=True), row["node_id"]) local = connection.sock.getsockname()[0] - if not tailnet_address(local): + if not (tailnet_address(local) or any(path.get("core") == local and path.get("node") == address for path in row.get("network_paths", {}).values())): raise PairingError("Обратный адрес Core не относится к частному каналу.") body = {"schema": SCHEMA, "binding_id": row["binding"]["binding_id"]} value = request(connection, "/v1/channel/inspect", body) @@ -145,7 +149,7 @@ def reconcile(registry): if now < attempts.get(row["id"], 0): continue attempts[row["id"]] = now + 30 - if tailnet_address(row["core_address"]) and (row.get("last_seen") or 0) >= max( + if (row.get("last_seen") or 0) >= max( registry.started_at, time.time() - 20 ): continue diff --git a/src/k1link/fleet/registry.py b/src/k1link/fleet/registry.py index e1958cc3..d852b92b 100644 --- a/src/k1link/fleet/registry.py +++ b/src/k1link/fleet/registry.py @@ -20,9 +20,10 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey from missioncore_plugin_sdk.v0alpha2.identity import ExecutionBinding from . import sensors +from .channel_binding import authenticate, endpoint_error +from .sensor_transient import cache as sensor_transient from .trust import SCHEMA, CoreTrust, PairingError, node_request, parse_invitation, pem, public_id - class FleetRegistry: """One writer lock and durable transactions; transport never owns vehicles.""" @@ -35,20 +36,27 @@ class FleetRegistry: self.independent_equipment: EquipmentStore | None = None self.vps_hosts: VPSHosts | None = None self.lock = threading.RLock() + self.presence: dict[str, dict] = {} from .events import FleetEvents self.events = FleetEvents() from .device_enrollment import DeviceEnrollment self.device_enrollment = DeviceEnrollment() + from .routers import Routers + self.routers = Routers() from .monitor import MonitorReceiver self.monitor = MonitorReceiver(root) from .rover_control import RoverControl self.rover_control = RoverControl() + from .rover_channel import RoverChannel + self.rover_channel = RoverChannel(self.rover_control) from .rover_configuration import RoverConfigurations self.rover_configurations = RoverConfigurations(root) self.trust = CoreTrust(root) + from .network_profiles import NetworkProfiles + self.network_profiles = NetworkProfiles(self) path = root / "fleet.sqlite3" if path.is_symlink(): raise PairingError("Конфликт файла реестра.") @@ -72,6 +80,7 @@ class FleetRegistry: # Preserve pre-archive releases' completed backups before the ordinary # short-lived operation receipts are pruned. for row in self.rows(): + self.rover_channel.publish(row) for receipt in row.get("sensor_commands", {}).values(): if receipt.get("state") == "complete" and receipt.get("command", {}).get("action_id") == "vesc.config.backup": with suppress(ValueError, KeyError, TypeError): @@ -84,26 +93,31 @@ class FleetRegistry: def rows(self): return [ - json.loads(row[0]) for row in self.db.execute("SELECT body FROM vehicles ORDER BY id") + sensor_transient(self).hydrate(json.loads(row[0])) for row in self.db.execute("SELECT body FROM vehicles ORDER BY id") ] def save(self, row, *, previous=None): with self.db: if previous is not None: self.db.execute("INSERT INTO board_history VALUES(?,?,?)", - (previous["id"], previous["revision"], json.dumps(previous))) + (previous["id"], previous["revision"], json.dumps(sensor_transient(self).persist(previous)))) self.db.execute( "INSERT INTO vehicles VALUES(?,?,?) " "ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, body=excluded.body", - (row["id"], row["node_id"], json.dumps(row)), + (row["id"], row["node_id"], json.dumps(sensor_transient(self).persist(row))), ) + # Publish only after commit. Inventory fsync never holds the control + # channel lock; a failed transaction cannot change its authority. + self.rover_channel.publish(row) + if row["enrollment"] == "revoked": + self.network_profiles.revoke_node(row["node_id"]) self.events.notify() def find(self, identifier): result = self.db.execute("SELECT body FROM vehicles WHERE id=?", (identifier,)).fetchone() if not result: raise PairingError("Аппарат не найден.") - return json.loads(result[0]) + return sensor_transient(self).hydrate(json.loads(result[0])) def start(self): with self.lock: @@ -112,6 +126,11 @@ class FleetRegistry: # Address absent: keep the binding and show offline. with suppress(OSError): self.listen(row["core_address"]) + for profile in self.network_profiles.profiles.values(): + if profile.get("state") == "ready": + import ipaddress + with suppress(OSError): + self.listen(str(ipaddress.ip_network(profile["subnet"])[2])) self.worker = threading.Thread( target=self.reconcile, name="mission-core-fleet", daemon=True ) @@ -134,6 +153,8 @@ class FleetRegistry: self.worker.join(timeout=20) if self.recovery_worker: self.recovery_worker.join(timeout=30) + for worker in self.network_profiles.workers.values(): + worker.join(timeout=30) for server in self.listeners.values(): server.shutdown() server.server_close() @@ -184,7 +205,9 @@ class FleetRegistry: def add(self, preview_id: str, name: str, platform: str, *, vehicle_id: str | None = None, expected_revision: int | None = None) -> dict: - with self.lock: + # Replacement admission and publication exclude a concurrent arm. + # This exceptional identity operation is not the heartbeat writer path. + with self.lock, self.rover_channel.lock: preview = self.previews.get(preview_id) if preview is None or preview["expires"] <= time.time(): raise PairingError("Проверка приглашения истекла. Вставьте код снова.") @@ -259,11 +282,15 @@ class FleetRegistry: return self.public(row) def public(self, row): + presence = self.presence.get(row["id"], {}) + if presence.get("binding_id") != row["binding"]["binding_id"]: + presence = {} + last_seen = max(row["last_seen"] or 0, presence.get("at", 0)) or None online = ( row["enrollment"] == "paired" - and row["last_seen"] is not None - and row["last_seen"] >= self.started_at - and time.time() - row["last_seen"] < 20 + and last_seen is not None + and last_seen >= self.started_at + and time.time() - last_seen < 20 ) return { "id": row["id"], @@ -274,6 +301,13 @@ class FleetRegistry: "revision": row["revision"], "connectivity": "online" if online else "offline", "last_seen": row["last_seen"], + "link_last_seen": last_seen, + "inventory_fresh": bool( + row["last_seen"] and row["last_seen"] >= self.started_at + and time.time() - row["last_seen"] < 20 + and (not presence or presence.get("agent_instance_id") + == (row.get("runtime") or {}).get("agent_instance_id")) + ), "host": row["inventory"], "execution_binding": row["runtime"], "devices": row.get("sensor_state", {}).get("items", []), @@ -308,7 +342,7 @@ class FleetRegistry: } def revoke(self, identifier: str): - with self.lock: + with self.lock, self.rover_channel.lock: row = self.find(identifier) if row["enrollment"] == "revoked": return self.public(row) @@ -385,7 +419,9 @@ class FleetRegistry: def reconcile(self): while not self.stop.is_set(): + self.network_profiles.reconcile() with self.lock: + self.routers.prune() active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")] for address in {row["core_address"] for row in active}: try: @@ -421,31 +457,24 @@ class FleetRegistry: if not isinstance(key, Ed25519PublicKey): return 403, {"error": "Unauthorized Node"} node_id = public_id("node_", key) + if path in ("/v1/node/rover", "/v1/node/rover-stream", "/v1/node/rover-link", "/v1/node/rover-diagnostics"): + started = time.monotonic() + result = self.rover_channel.receive(node_id, cert.serial_number, path, value, address) + if path == "/v1/node/rover" and result[0] == 200: + self.rover_control.record_telemetry_timing( + node_id, (time.monotonic() - started) * 1000, + result[1]["control_clock"]["monotonic_ms"], + ) + return result entered = time.monotonic() with self.lock: waited = time.monotonic() - entered if waited > .025: logging.getLogger(__name__).warning("fleet timing path=%s lock_ms=%.1f", path, waited*1000) row = next((item for item in self.rows() if item["node_id"] == node_id), None) - if ( - row is None - or row["enrollment"] not in ("pending", "paired") - or value.get("node_id") != node_id - or value.get("binding_id") != row["binding"]["binding_id"] - ): - return 410, {"error": "Binding revoked"} - allowed = [row["binding"]["client_pem"]] - if ( - row.get("certificate_previous") - and row["certificate_previous"]["until"] > time.time() - ): - allowed.append(row["certificate_previous"]["pem"]) - if cert.serial_number not in [ - x509.load_pem_x509_certificate(item.encode()).serial_number for item in allowed - ]: - return 403, {"error": "Certificate superseded"} - if value.get("schema") != SCHEMA: - return 400, {"error": "Incompatible protocol"} + error = authenticate(row, node_id, cert.serial_number, value) + if error: + return error if path == "/v1/node/unpair": row.update( enrollment="revoked", @@ -456,42 +485,28 @@ class FleetRegistry: ) self.save(row) return 200, {"ok": True} - if path not in ("/v1/node/heartbeat", "/v1/node/rover", "/v1/node/rover-stream"): + if path == "/v1/node/liveness": + return self.receive_liveness(row, value, address) + if path != "/v1/node/heartbeat": return 404, {"error": "Unknown operation"} # Endpoint revisions prevent an old in-flight heartbeat or lost ack # from reversing a migration. Use the actual listener, not a claimed IP. - from .recovery import tailnet_address - + error = endpoint_error(row, value, address) + if error: + return error revision = value.get("endpoint_revision", 0) - if type(revision) is not int or not 0 <= revision <= 1000000000: - return 400, {"error": "Invalid endpoint revision"} previous_revision = row["binding"].get("endpoint_revision", 0) - if revision < previous_revision: - return 409, {"error": "Endpoint superseded"} if revision > previous_revision: - if ( - not tailnet_address(address) - or value.get("core_endpoint") != f"https://{address}:8782" - ): - return 400, {"error": "Endpoint does not match authenticated channel"} row["core_address"] = address row["binding"]["endpoint"] = value["core_endpoint"] row["binding"]["endpoint_revision"] = revision - if path in ("/v1/node/rover", "/v1/node/rover-stream"): - if row["enrollment"] != "paired": - return 410, {"error": "Pairing incomplete"} - if path.endswith("-stream"): - relay = value.get("relay_id") - if not isinstance(relay, str) or len(relay) != 32: - return 400, {"error": "Invalid relay"} - return 200, self.rover_control.stream(node_id, relay) - return 200, self.rover_control.exchange(node_id, value) binding = ExecutionBinding.model_validate(value["execution_binding"]) if binding.node_id != node_id or binding.platform.value != "linux": return 400, {"error": "Invalid Node inventory"} sensor_state = sensors.validate_inventory(value, node_id) sensor_response = sensors.heartbeat(row, value) configuration_response = self.rover_configurations.heartbeat(node_id, value) + network_response = self.network_profiles.heartbeat(row, value) archive_ack = None archive_started = time.monotonic() try: @@ -506,6 +521,7 @@ class FleetRegistry: archive_ack = None archive_elapsed = time.monotonic() - archive_started enrollment_response = self.device_enrollment.heartbeat(row, value) + router_response = self.routers.heartbeat(row, value) host = value.get("host") if ( not isinstance(host, dict) @@ -548,6 +564,32 @@ class FleetRegistry: "ok": True, "client_pem": row["binding"]["client_pem"], **configuration_response, + **network_response, **sensor_response, **enrollment_response, + **router_response, } + + def receive_liveness(self, row, value, address): + # Called after the same certificate/binding authentication, under lock. + # RAM-only presence does not refresh equipment, monitor, configuration, + # command acknowledgements, persisted inventory or motor authority. + allowed = {"schema", "node_id", "binding_id", "execution_binding", + "core_endpoint", "endpoint_revision"} + if set(value) - allowed or len(json.dumps(value).encode()) > 2048: + return 400, {"error": "Invalid liveness envelope"} + error = endpoint_error(row, value, address) + if error: + return error + binding = ExecutionBinding.model_validate(value["execution_binding"]) + if binding.node_id != row["node_id"] or binding.platform.value != "linux": + return 400, {"error": "Invalid Node identity"} + now = time.time() + self.presence = {key: item for key, item in self.presence.items() if now-item["at"] < 20} + if row["id"] not in self.presence and len(self.presence) >= 256: + return 503, {"error": "Presence capacity"} + self.presence[row["id"]] = { + "at": now, "binding_id": row["binding"]["binding_id"], + "agent_instance_id": binding.agent_instance_id, + } + return 200, {"ok": True, "heartbeat_encoding": "gzip"} diff --git a/src/k1link/fleet/rover_channel.py b/src/k1link/fleet/rover_channel.py new file mode 100644 index 00000000..b39782b9 --- /dev/null +++ b/src/k1link/fleet/rover_channel.py @@ -0,0 +1,132 @@ +"""Committed binding projection for control, independent of inventory disk I/O. + +Lock order: registry writer -> channel -> RoverControl. Channel operations never +take the writer lock or access SQLite. Each frame still checks current authority. +""" +import copy +import threading +import time + +from .channel_binding import authenticate, endpoint_error +from .trust import PairingError + + +class RoverChannel: + def __init__(self, control): + self.control = control + self.lock = threading.RLock() + self.vehicles = {} + self.nodes = {} + + def publish(self, row): + # Only committed identity metadata is projected, never inventory, action + # 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"], + "binding": {key: binding[key] for key in + ("binding_id", "client_pem", "endpoint_revision") if key in binding}, + "certificate_previous": row.get("certificate_previous"), + }) + 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["enrollment"] == "paired" and row["enrollment"] != "paired")): + self.nodes.pop(old["node_id"], None) + self.control.forget(old["node_id"]) + self.vehicles[row["id"]] = projection + self.nodes[row["node_id"]] = projection + + def same_generation(self, value): + """Cheap retirement check only; a send still performs full authentication.""" + with self.lock: + row = self.nodes.get(value.get("node_id")) + 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)) + + def operator(self, vehicle, operation, body=None, *, expires_at=None): + with self.lock: + row = self.vehicles.get(vehicle) + if row is None: + raise PairingError("Аппарат не найден.") + if row["enrollment"] != "paired": + raise ValueError("Борт не привязан.") + node = row["node_id"] + if operation == "diagnostics": + return self.control.diagnostics(node,row.get("name",vehicle)) + if operation == "view": + return self.control.view(node) + if operation == "observation_evidence": + return self.control.observation(node, body) + if operation == "arm": + return self.control.arm(node, body, expires_at=expires_at) + if operation == "command": + return self.control.command(node, body, expires_at=expires_at) + if operation == "hold": + return self.control.hold(node, body, expires_at=expires_at) + if operation == "maintain_neutral": + return self.control.maintain_neutral(node, body["session_id"]) + if operation == "disconnect": + return self.control.disconnect(node, body["session_id"]) + raise ValueError("Unknown control operation") + + def receive(self, node, serial, path, value, address): + started = time.monotonic() + with self.lock: + row = self.nodes.get(node) + error = self._receive_error(row, node, serial, value, address) + if error: + return error + if path == "/v1/node/rover-link": + # Authenticate/establish the connection only. This must never + # publish a snapshot, renew a lease or make stale data fresh. + relay = value.get("relay_id") + if (set(value) - {"schema", "node_id", "binding_id", "core_endpoint", + "endpoint_revision", "relay_id"} + 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, + "control_clock": self.control._clock()} + if path == "/v1/node/rover-diagnostics": + # Capture this binding's diagnostics object while authority is + # locked, but never serialize control behind optional ingest or + # export. A forgotten binding's object cannot recreate a board. + diagnostics = self.control.diagnostics(node, row.get("name", row["id"])) + elif path == "/v1/node/rover-stream": + relay = value.get("relay_id") + if not isinstance(relay, str) or len(relay) != 32: + return 400, {"error": "Invalid relay"} + return 200, self.control.stream(node, relay) + else: + result = self.control.exchange(node, value) + result["core_processing_ms"] = (time.monotonic() - started) * 1000 + return 200, result + + reply = diagnostics.exchange(value) + with self.lock: + # Revocation/rotation/rebinding may finish during optional work. + # Recheck current authority before releasing any diagnostic reply. + error = self._receive_error(self.nodes.get(node), node, serial, value, address) + if error: + return error + with self.control.lock: + board = self.control.boards.get(node) + if board is None or board["diagnostics"] is not diagnostics: + return 409, {"error": "Diagnostic binding superseded"} + return 200, reply + + @staticmethod + def _receive_error(row, node, serial, value, address): + error = authenticate(row, node, serial, value) + if error: + return error + error = endpoint_error(row, value, address) + if error: + return error + if row["enrollment"] != "paired": + return 410, {"error": "Pairing incomplete"} + return None diff --git a/src/k1link/fleet/rover_control.py b/src/k1link/fleet/rover_control.py index fd3f5f9d..d8bfa533 100644 --- a/src/k1link/fleet/rover_control.py +++ b/src/k1link/fleet/rover_control.py @@ -7,6 +7,9 @@ import secrets import threading import time +from .rover_diagnostics import RoverDiagnostics +from .rover_observation_evidence import ObservationEvidence + class RoverControl: def __init__(self, clock=time.monotonic): @@ -14,50 +17,126 @@ class RoverControl: self.lock = threading.RLock() self.changed = threading.Condition(self.lock) self.boards = {} + self.network_changes = set() self.clock_id = secrets.token_hex(16) def _board(self, node): - return self.boards.setdefault(node, {"seen": -1e9, "watch": 0, "snapshot": {}, - "session": None, "relay": None}) + if node not in self.boards: + self.boards[node]={"seen":-1e9,"watch":0,"snapshot":{},"session":None,"relay":None,"diagnostics":RoverDiagnostics(self.clock),"observation":ObservationEvidence(self.clock)} + return self.boards[node] + + def diagnostics(self,node,vehicle): + with self.lock: + board=self._board(node);value=board["diagnostics"];value.vehicle=vehicle + session=board["session"] or {} + value.context={"vehicle":vehicle,"core_clock_instance":self.clock_id,"driver_state":board["snapshot"].get("state"), + "session_id":session.get("id"),"settings":copy.deepcopy(session.get("settings"))} + return value + + def forget(self, node): + """A revoked/replaced binding cannot retain a lease or a fresh snapshot.""" + with self.changed: + self.boards.pop(node, None) + self.changed.notify_all() + + def observation(self, node, event=None): + with self.lock: + evidence = self._board(node)["observation"] + if event in ("operator_socket_opened", "operator_socket_closed"): + evidence.event(event) + return evidence.snapshot() def view(self, node): with self.lock: b = self._board(node) b["watch"] = self.clock() + 2 - fresh = self.clock() - b["seen"] < 1 + elapsed = max(0., self.clock() - b["seen"]) + fresh = elapsed < 1 + b["observation"].view(fresh) self._expire(b) - return {"fresh": fresh, "snapshot": copy.deepcopy(b["snapshot"]) if fresh else {}, - "controlling": b["session"] is not None} + snapshot = copy.deepcopy(b["snapshot"]) if fresh else {} + for reading in snapshot.get("devices", []): + age = reading.get("age_ms") + if type(age) in (int, float) and math.isfinite(age): + reading["age_ms"] = max(0, age) + int(elapsed * 1000) + result = {"fresh": fresh, "snapshot": snapshot, + "controlling": b["session"] is not None} + if fresh and self.clock()-b.get("budget_seen", -1e9) < 2 and isinstance(b.get("link_budget"), dict): + result["link_budget"] = copy.deepcopy(b["link_budget"]) + result["link_budget"]["snapshot_age_ms"] = max(0, int((self.clock()-b["budget_seen"])*1000)) + return result + + def _withdraw(self, b, reason, *, snapshot=None): + session = b["session"] + if session is None: + return + b["session"] = None + observed = b["snapshot"] if snapshot is None else snapshot + b["diagnostics"].control_stop.record( + reason, session, core_instance=self.clock_id, + telemetry_age_ms=(self.clock() - b["seen"]) * 1000, + driver_state=observed.get("state"), + ) def _expire(self, b): if b["session"] and self.clock() >= b["session"]["until"]: - b["session"] = None + b["diagnostics"].trace.add("lease_expired", session_id=b["session"]["id"], sequence=b["session"]["sequence"]) + self._withdraw(b, "input_deadline_expired") - def arm(self, node, body): - if (set(body) != {"standstill_confirmed", "current_a", "max_erpm"} + def disconnect(self, node, session): + """A closed operator socket can retire only the lease it created.""" + with self.changed: + b = self._board(node) + if b["session"] and b["session"]["id"] == session: + b["diagnostics"].trace.add("operator_disconnect", session_id=session) + self._withdraw(b, "operator_socket_closed") + self.changed.notify_all() + + def network_change(self, node, active): + with self.lock: + if active: + board = self._board(node) + self._expire(board) + if board["session"] is not None: + raise ValueError("Отключите управление перед изменением сети борта.") + self.network_changes.add(node) + else: + self.network_changes.discard(node) + + def arm(self, node, body, *, expires_at=None): + duty = "max_duty_percent" in body + speed_key, low, high = ("max_duty_percent", 1, 100) if duty else ("max_erpm", 300, 3000) + if (set(body) != {"standstill_confirmed", "current_a", speed_key} or body["standstill_confirmed"] is not True or type(body["current_a"]) not in (int, float) - or not .5 <= body["current_a"] <= 30 - or type(body["max_erpm"]) not in (int, float) - or not 300 <= body["max_erpm"] <= 3000): + or not math.isfinite(body["current_a"]) or body["current_a"] < .5 + or type(body[speed_key]) not in (int, float) + or not low <= body[speed_key] <= high): raise ValueError("Подтвердите остановку и выберите допустимые пределы.") with self.lock: + if node in self.network_changes: + raise ValueError("Дождитесь завершения переключения сети борта.") b = self._board(node) + if expires_at is not None and self.clock() >= expires_at: + raise ValueError("Команда устарела до передачи на борт.") self._expire(b) if b["session"]: raise ValueError("Аппаратом уже управляют. Сначала остановите управление.") snapshot = b["snapshot"] if self.clock() - b["seen"] >= 1 or snapshot.get("supported") is not True: raise ValueError("Канал управления бортом недоступен.") + if duty and "duty" not in (snapshot.get("control_modes") or []): + raise ValueError("Обновите драйвер борта для управления газом.") if snapshot.get("state") in ("preparing", "ready", "driving", "stopping"): raise ValueError("Дождитесь завершения предыдущего управления.") identifier = secrets.token_hex(16) - b["session"] = {"id": identifier, "sequence": 0, "until": self.clock()+.4, + b["session"] = {"id": identifier, "sequence": 0, "operator_sequence": 0, "neutral_hold": False, "until": min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4, "left": 0, "right": 0, "settings": copy.deepcopy(body)} self.changed.notify_all() + b["diagnostics"].trace.add("armed", session_id=identifier, settings=body) return {"session_id": identifier} - def command(self, node, body): + def command(self, node, body, *, expires_at=None): if set(body) != {"session_id", "sequence", "left", "right", "stop"}: raise ValueError("Некорректная команда управления.") if (type(body["sequence"]) is not int or not 1 <= body["sequence"] < 2**53 @@ -67,20 +146,66 @@ class RoverControl: raise ValueError("Некорректные значения команды.") with self.lock: b = self._board(node) + if expires_at is not None and self.clock() >= expires_at: + raise ValueError("Команда устарела до передачи на борт.") self._expire(b) s = b["session"] if not s or not secrets.compare_digest(str(body["session_id"]), s["id"]): raise ValueError("Управление завершено. Включите его заново.") - if body["sequence"] <= s["sequence"]: + if body["sequence"] <= s["operator_sequence"]: raise ValueError("Устаревшая команда отклонена.") if body["stop"]: - b["session"] = None + self._withdraw(b, "operator_stop") else: - s.update(sequence=body["sequence"], left=body["left"], right=body["right"], - until=self.clock()+.4) + s.update(sequence=max(s["sequence"]+1, body["sequence"]), operator_sequence=body["sequence"], + neutral_hold=False, left=body["left"], right=body["right"], + until=min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4) self.changed.notify_all() + b["diagnostics"].trace.add("operator_command", **body) return {"accepted_sequence": body["sequence"]} + def hold(self, node, body, *, expires_at=None): + """Explicit socket-owner handoff to neutral; no remembered motion.""" + if not isinstance(body, dict) or set(body) != {"session_id", "sequence"}: + raise ValueError("Некорректная команда удержания готовности.") + with self.lock: + result = self.command(node, {**body, "left": 0, "right": 0, "stop": False}, + expires_at=expires_at) + self._board(node)["session"]["neutral_hold"] = True + return result + + def maintain_neutral(self, node, session): + """Called only by the live owner socket, never by observation/Node pull. + + This creates fresh ZERO frames, not fresh timestamps on remembered + operator input. Missing a deadline is terminal even in neutral hold. + """ + with self.changed: + b = self._board(node) + self._expire(b) + s = b["session"] + if not s or s["id"] != session or not s["neutral_hold"]: + return False + snapshot = b["snapshot"] + if (self.clock()-b["seen"] >= 1 or snapshot.get("supported") is not True + or (snapshot.get("session_id") == session and snapshot.get("state") + in ("stopping", "stopped", "fault", "receiver"))): + reason = ("telemetry_stale" if self.clock()-b["seen"] >= 1 else + "driver_unavailable" if snapshot.get("supported") is not True else + "driver_terminal") + self._withdraw(b, reason) + self.changed.notify_all() + return False + s.update(left=0, right=0, sequence=s["sequence"]+1, until=self.clock()+.4) + self.changed.notify_all() + return True + + @staticmethod + def _intent(session): + # Browser sequence and neutral ownership never cross the Node boundary. + return {key: copy.deepcopy(session[key]) for key in + ("id", "sequence", "left", "right", "settings")} + def exchange(self, node, body): """Called only after normal paired-certificate/binding authentication.""" snapshot = body.get("rover") @@ -88,27 +213,112 @@ class RoverControl: if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32: raise ValueError("Invalid rover exchange") with self.lock: + observed = self.clock() + timing = body.get("sample_clock") + if timing is not None: + if (not isinstance(timing, dict) or set(timing) != {"instance", "monotonic_ms"} + or timing["instance"] != self.clock_id + or type(timing["monotonic_ms"]) not in (int, float) + or not math.isfinite(timing["monotonic_ms"]) + or not 0 <= timing["monotonic_ms"] <= observed * 1000): + raise ValueError("Invalid rover sample clock") + observed = timing["monotonic_ms"] / 1000 b = self._board(node) - if b["relay"] != relay: - b["session"] = None # No resume after relay restart/rebind. - if b["snapshot"].get("instance") != snapshot.get("instance"): - b["session"] = None # Driver restarts also revoke the browser lease. - b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=self.clock()) + # A delayed/cancelled request may arrive after its replacement. + # It cannot replace a newer sample or change its relay/session. + publish = observed >= b["seen"] + metadata = None + if publish and "rover_details_v1" in body: + from .rover_metadata import expand + snapshot, metadata = expand(snapshot, body["rover_details_v1"], b.get("rover_metadata"), + relay=relay, observed=observed, now=self.clock()) + readings = snapshot.get("devices") + b["observation"].receive(observed, publish, len(readings) if isinstance(readings, list) else 0) + if publish and b["relay"] != relay: + self._withdraw(b, "relay_changed", snapshot=snapshot) + if publish and b["snapshot"].get("instance") != snapshot.get("instance"): + self._withdraw(b, "driver_restarted", snapshot=snapshot) + b["diagnostics"].ingest(body.get("diagnostics")) + if publish: + b["diagnostics"].supports_options=body.get("diagnostic_options_v1") is True + b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=observed, rover_metadata=metadata) + if "link_budget" in body: + b["link_budget"] = copy.deepcopy(body["link_budget"]) + b["budget_seen"] = observed + snapshot = b["snapshot"] self._expire(b) s = b["session"] if s and snapshot.get("session_id") == s["id"] and snapshot.get("state") in ( - "stopped", "fault", "receiver"): - b["session"] = s = None + "stopping", "stopped", "fault", "receiver"): + self._withdraw(b, "driver_terminal") + s = None command = None if s: - command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"} + command = self._intent(s) command["ttl_ms"] = max(0, min(400, int((s["until"]-self.clock())*1000))) - return {"watch": self.clock() < b["watch"] or s is not None, "command": command, - "control_clock": self._clock()} + return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].enabled or b["diagnostics"].closing, "command": command, + "control_active": s is not None, + # Atomic hints only: never take the optional recorder/export + # locks in the command/telemetry path. + "diagnostics_pending": bool(b["diagnostics"].enabled or b["diagnostics"].closing or b["diagnostics"].export.busy), + "control_clock": self._clock(), "diagnostics": None if body.get("diagnostic_lane_v1") is True else b["diagnostics"].desired(relay_ack=body.get("diagnostic_relay_ack_v1") is True)} + + def exchange_diagnostics(self, node, body): + with self.lock: + diagnostics = self._board(node)["diagnostics"] + # No control lock while ingesting optional records or waiting for files. + return diagnostics.exchange(body) + + def record_telemetry_timing(self, node, dispatch_ms, reply_mono_ms): + """DEV-only Core dispatch timing; no publication or lease renewal. + + Excludes body transfer and reply transmission. Compare with Node's + HTTP trace to distinguish channel processing from end-to-end delay. + Aggregate at most once/second to avoid amplifying optional traffic. + Never retain the control lock while writing the diagnostic ring. + """ + with self.lock: + board = self.boards.get(node) + if board is None: + return + diagnostics = board["diagnostics"] + if not diagnostics.trace.recording(): + board.pop("telemetry_timing", None) + return + trace = diagnostics.trace + now = self.clock() + timing = board.get("telemetry_timing") + if timing is None or timing["capture_id"] != trace.capture_identity(): + timing = {"capture_id": trace.capture_identity(), "next": now, "count": 0, "max_ms": 0.} + board["telemetry_timing"] = timing + timing["count"] += 1 + timing["max_ms"] = max(timing["max_ms"], dispatch_ms) + if now < timing["next"]: + return + details = {"exchanges": timing["count"], + "dispatch_max_ms": round(timing["max_ms"], 3), + "reply_mono_ms": reply_mono_ms} + timing.update(next=now + 1, count=0, max_ms=0.) + trace.add("node_telemetry_handled", **details) def _clock(self): return {"instance": self.clock_id, "monotonic_ms": self.clock()*1000} + def stream_trace(self, node): + """Capture a recorder reference; never hold the authority lock on I/O.""" + with self.lock: + board = self.boards.get(node) + return board["diagnostics"].trace if board else None + + def intent_changed(self, node, relay, previous): + """Read-only wake hint; never create a board or grant send authority.""" + with self.lock: + board = self.boards.get(node) + current = (board["session"] if board and board["relay"] == relay else None) or {} + previous = previous or {} + return (current.get("id"), current.get("sequence")) != ( + previous.get("id"), previous.get("sequence")) + def wait_for_intent(self, node, relay, previous, timeout=.05): """Wake on a new intent, including updates between write and wait.""" previous = previous or {} @@ -125,11 +335,11 @@ class RoverControl: b = self._board(node) self._expire(b) if self.clock() - b["seen"] >= 1: - b["session"] = None + self._withdraw(b, "telemetry_stale") s = b["session"] if b["relay"] == relay else None command = None if s: - command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"} + command = self._intent(s) command["expires_mono_ms"] = s["until"]*1000 - return {"watch": self.clock() < b["watch"] or s is not None, + return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].enabled or b["diagnostics"].closing, "command": command, "control_clock": self._clock()} diff --git a/src/k1link/fleet/rover_datagram.py b/src/k1link/fleet/rover_datagram.py new file mode 100644 index 00000000..729d53e6 --- /dev/null +++ b/src/k1link/fleet/rover_datagram.py @@ -0,0 +1,182 @@ +"""Latest-state datagrams, with keys delivered only through the paired mTLS lane. + +No command queue, retransmission, authority or lease lives here. Every send asks +RoverChannel for the currently authorized intent. Unknown/forged/replayed input +gets no response. Keys and packet contents are never logged or persisted. +""" +from __future__ import annotations + +import json +import secrets +import socket +import struct +import threading +import time + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +# Qualified on 2026-10-27: isolated impairment tests and paired Python/Go mTLS. +# Deployment/field acceptance is recorded separately in the network runtime audit. +QUALIFIED = True + +MAGIC = b"MCR1" +MAX_PACKET = 1200 +MAX_COUNTER = 2**32 - 1 +MAX_CHANNELS = 16 +HEADER = 28 # magic + random channel id + uint64 counter +KEEPALIVE_INTERVAL = .05 +MIN_SEND_INTERVAL = .01 + + +class DatagramCipher: + """One direction, one random key; a counter is never reused under that key.""" + + def __init__(self, channel: bytes, key: bytes): + if len(channel) != 16 or len(key) != 32: + raise ValueError("Invalid datagram key") + self.channel, self.aead = channel, AESGCM(key) + self.sent = self.received = 0 + + def seal(self, value: dict) -> bytes: + raw = json.dumps(value, separators=(",", ":"), allow_nan=False).encode() + if len(raw) + HEADER + 16 > MAX_PACKET or self.sent >= MAX_COUNTER: + raise ValueError("Datagram bound exceeded") + self.sent += 1 + counter = struct.pack("!Q", self.sent) + header = MAGIC + self.channel + counter + return header + self.aead.encrypt(b"\0" * 4 + counter, raw, header) + + def open(self, packet: bytes): + if (not HEADER + 16 < len(packet) <= MAX_PACKET + or packet[:20] != MAGIC + self.channel): + return None + counter = struct.unpack("!Q", packet[20:28])[0] + if not self.received < counter <= MAX_COUNTER: + return None + try: + raw = self.aead.decrypt(b"\0" * 4 + packet[20:28], packet[28:], packet[:28]) + value = json.loads(raw) + if not isinstance(value, dict): + return None + except (InvalidTag, ValueError, UnicodeError): + return None + self.received = counter + return counter, value + + +class RoverDatagramServer: + """Bounded socket/thread owned by one existing NodeChannelServer listener.""" + + def __init__(self, address, registry, *, port=8782): + self.address, self.registry = address, registry + self.lock = threading.Lock() + self.channels = {} + self.stop = threading.Event() + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + self.socket.bind((address, port)) + self.socket.settimeout(.01) + except BaseException: + self.socket.close() + raise + self.thread = threading.Thread( + target=self.run, name="mission-core-rover-datagram", daemon=True) + self.thread.start() + + def open(self, certificate, value): + # Caller already authenticated /rover-link, and every frame rechecks + # the original certificate/binding. A replacement destroys old keys. + channel = secrets.token_bytes(16) + send, receive = secrets.token_bytes(32), secrets.token_bytes(32) + now = time.monotonic() + with self.lock: + self.channels = {k: c for k, c in self.channels.items() + if c["value"]["node_id"] != value["node_id"] and now < c["expires"]} + if len(self.channels) >= MAX_CHANNELS: + return 503, {"error": "Datagram capacity reached"} + self.channels[channel] = { + "value": dict(value), "certificate": certificate, + "send": DatagramCipher(channel, send), "receive": DatagramCipher(channel, receive), + "peer": None, "probe": 0, "probe_clock": None, "last_probe": now, + "next": now, "last_sent": -1e9, "last_command": None, "expires": now + 86400, + } + return 200, {"channel": channel.hex(), "send_key": receive.hex(), + "receive_key": send.hex(), "port": self.socket.getsockname()[1], + "max_packet": MAX_PACKET, "lifetime_s": 86400} + + def close(self): + self.stop.set() + self.socket.close() + self.thread.join(timeout=2) + with self.lock: + self.channels.clear() + + def run(self): + while not self.stop.is_set(): + try: + packet, peer = self.socket.recvfrom(MAX_PACKET + 1) + except (TimeoutError, BlockingIOError): + packet = None + except OSError: + break + now = time.monotonic() + with self.lock: + if packet is not None and len(packet) <= MAX_PACKET: + c = self.channels.get(packet[4:20]) + if c is not None: + opened = c["receive"].open(packet) + if opened is not None and opened[1] == {}: + # This clock is sampled AFTER the exact echoed probe, + # never at a later periodic send for that same probe. + c.update(peer=peer, probe=opened[0], + probe_clock=self.registry.rover_control._clock(), + last_probe=now) + for key, c in list(self.channels.items()): + if (now >= c["expires"] or now - c["last_probe"] >= 2 + or not self.registry.rover_channel.same_generation(c["value"])): + self.channels.pop(key, None) + continue + if c["peer"] is None or now - c["last_sent"] < MIN_SEND_INTERVAL: + continue + # Fresh input and withdrawal must not wait for a keepalive + # tick. This hint does not authorize a send: the original + # certificate/binding/endpoint is checked again below. + if now < c["next"] and not self.registry.rover_control.intent_changed( + c["value"]["node_id"], c["value"]["relay_id"], c["last_command"]): + continue + periodic_lag_ms = max(0., (now - c["next"]) * 1000) + dispatched = time.monotonic() + try: + status, reply = self.registry.receive( + c["certificate"], "/v1/node/rover-stream", + c["value"], address=self.address) + if status != 200: + self.channels.pop(key, None) + continue + received = time.monotonic() + packet = c["send"].seal({"probe": c["probe"], + "probe_clock": c["probe_clock"], "reply": reply}) + sealed = time.monotonic() + self.socket.sendto(packet, c["peer"]) + sent = time.monotonic() + c.update(last_sent=sent, next=sent + KEEPALIVE_INTERVAL, + last_command=reply.get("command")) + trace = self.registry.rover_control.stream_trace(c["value"]["node_id"]) + if trace is not None: + command = reply.get("command") or {} + trace.add("datagram_sent", packet_sequence=c["send"].sent, + channel=key.hex(), bytes=len(packet), + session_id=command.get("id"), + sequence=command.get("sequence"), + expires_mono_ms=command.get("expires_mono_ms"), + dispatch_ms=(sent - dispatched) * 1000, + registry_ms=(received - dispatched) * 1000, + encrypt_ms=(sealed - received) * 1000, + socket_ms=(sent - sealed) * 1000, + periodic_lag_ms=periodic_lag_ms) + if not reply.get("watch"): + self.channels.pop(key, None) + except (OSError, ValueError, TypeError, KeyError): + # Drop this generation; receiver's unchanged guard stops. + self.channels.pop(key, None) diff --git a/src/k1link/fleet/rover_diagnostics.py b/src/k1link/fleet/rover_diagnostics.py new file mode 100644 index 00000000..e46ad1ac --- /dev/null +++ b/src/k1link/fleet/rover_diagnostics.py @@ -0,0 +1,189 @@ +"""DEV evidence transport; independent from every motion lease and output.""" +import json +import re +import secrets +import threading + +from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics +from missioncore_plugin_sdk.diagnostic_options import LEGACY_OPTIONS, diagnostic_options + +from .rover_diagnostics_export import DiagnosticExport +from .rover_local_trace import LocalRoverTrace +from .rover_preview_evidence import preview_sample +from .rover_stop_evidence import CoreStopEvidence + +KEYS={'KeyW','KeyA','KeyS','KeyD','KeyQ','KeyE','Space','Escape'} +INPUT_EVENTS={'key_down','key_up','pause','stop','pointer_down','pointer_up','pointer_cancel', + 'settings','demand','heartbeat','request','transport','lifecycle'} +INPUT_FIELDS={'code','repeat','reason','held','mode','current_a','speed','control_mode','left','right', + 'sequence','session_id','foreground','input_valid','pending','action','outcome','elapsed_ms', + 'browser_ms','ready_state','buffered_bytes','close_code','visibility','dropped', + 'request_id','socket_id','expires_ms','clock_ms','state_age_ms','gap_ms'} + +class CoreTrace(BoundedDiagnostics): + def __init__(self,clock,live): + super().__init__('core',clock);self.live=live;self.local=LocalRoverTrace(clock) + def recording(self):return self.active() or self.local.active() + def capture_identity(self):return (self.id if self.active() else None, self.local.id if self.local.active() else None) + def add(self,event,**data): + self.local.add(event,**data) + self.add_remote(event,**data) + def add_remote(self,event,**data): + row=super().add(event,**data) + if row:self.live.add('record',record=row) + +class RoverDiagnostics: + def __init__(self,clock): + self.lock=threading.RLock();self.live=BoundedDiagnostics('core',clock) + self.trace=CoreTrace(clock,self.live);self.node_ack=0;self.relay_ack=0;self.node_status={} + self.clock=clock;self.options=dict(LEGACY_OPTIONS);self.supports_options=False + self.control_stop=CoreStopEvidence(clock) + self.trace_tokens=4096.0;self.trace_at=clock() + self.enabled=False;self.closing=False;self.vehicle='Rover';self.context={};self.export=DiagnosticExport() + self.local_owner = None + + def exchange(self, body): + self.ingest(body.get('diagnostics')) + return {'diagnostics': self.desired(relay_ack=True, export_v2=body.get('diagnostic_export_v2') is True)} + + def set_enabled(self, enabled, options=None, local_options=None): + if type(enabled) is not bool:raise ValueError('Invalid DEV mode') + selected=diagnostic_options(options) + if local_options is not None and (not isinstance(local_options, dict) + or set(local_options) - {"enabled", "preview", "previous_id"} + or type(local_options.get("enabled")) is not bool + or type(local_options.get("preview")) is not bool): + raise ValueError("Invalid operator capture options") + if enabled and options is not None and not self.supports_options: + raise ValueError('Борт ещё не подтвердил поддержку настроек записи.') + with self.lock: + if enabled and not self.enabled: + if self.closing or self.export.busy:raise ValueError('Дождитесь завершения записи или сохранения файла.') + if local_options and local_options["enabled"]: + local = self.trace.local.start( + previous_id=local_options.get("previous_id"), preview=local_options["preview"]) + self.local_owner = local["id"] + identifier=secrets.token_hex(16) + self.options=selected;self.trace_tokens=4096.0;self.trace_at=self.clock() + self.live.configure(identifier,True);self.trace.configure(identifier,selected['core_trace']) + self.node_ack=self.relay_ack=0;self.node_status={};self.enabled=True + self.trace.add('capture_started',context=self.context) + if self.local_owner == self.trace.local.id and self.local_owner is not None: + self.trace.local.add('local_capture_context', context=self.context, + board_capture_id=identifier) + elif not enabled and self.enabled: + self.trace.add('capture_stop_requested');self.trace.configure(self.trace.id,False) + self.enabled=False;self.closing=True + if self.local_owner is not None and self.trace.local.id == self.local_owner: + self.trace.local.stop(self.local_owner) + self.local_owner = None + return self.view() + + def desired(self, *, relay_ack=False, export_v2=False): + with self.lock: + if not self.trace.id:return None + stored=self.node_status.get('storage') or {} + ack=(stored.get('external_ack') or {}).get('core',0) + # Acquisition and tail delivery are distinct on capable boards. + # Keep legacy draining semantics only until the board advertises it. + stop_tail=self.node_status.get('stop_tail_v1') is True + recording=self.enabled or (self.closing and not stop_tail and ack4096: + row={'source':'core','event':'core_record_omitted','record_sequence':row['record_sequence'], + 'reason':'trace_rate_bound','original_bytes':row_size} + row_size=len(json.dumps(row).encode())+2 + if size+row_size>allowance:break + events.append(row);size+=row_size + self.trace_tokens=max(0,self.trace_tokens-size) + result = {'id':self.trace.id,'enabled':recording,'after':self.node_ack,'vehicle':self.vehicle, + 'core_events':events,'export':self.export.desired(export_v2)} + if self.supports_options:result['options']=dict(self.options) + if self.closing and stop_tail:result['stop_after']=self.trace.sequence + if relay_ack:result['relay_after']=self.relay_ack + return result + + def ingest(self,packet): + if not isinstance(packet,dict):return + with self.lock: + identifier=packet.get('id') + stored=packet.get('storage') or {} + stop_after=packet.get('stop_after') + draining=packet.get('stop_tail_v1') is True and type(stop_after) is int and 0<=stop_after<=2**53-1 and stored.get('closed') is False + recoverable=draining or packet.get('active') is True or (stored.get('closed') is True and isinstance(stored.get('file'),str)) + if self.trace.id is None and isinstance(identifier,str) and re.fullmatch(r'[a-f0-9]{32}',identifier) and recoverable: + # Recover the last paired-board file after Core restart, including + # a completed capture. Recovery never reopens its writer. + active=packet.get('active') is True and stored.get('closed') is not True + try:self.options=diagnostic_options(packet.get('options')) + except ValueError:return + self.live.configure(identifier,active);self.trace.configure(identifier,active and self.options['core_trace']);self.enabled=active + self.trace.sequence=((packet.get('storage') or {}).get('external_ack') or {}).get('core',0) + self.vehicle=packet.get('vehicle','Rover') + self.trace.add('core_reconnected') + if draining: + self.enabled=False;self.closing=True + ack=self.trace.sequence + if ack32 or not isinstance(relay,list) or len(relay)>64:return + self.node_status={k:packet.get(k) for k in ('id','active','dropped','rejected','sequence','first_sequence','storage','transport_error','stop_tail_v1','options')} + for row in relay: + if isinstance(row,dict) and type(row.get('record_sequence')) is int and row['record_sequence']>self.relay_ack: + self.live.add('record',record=row);self.relay_ack=row['record_sequence'] + for row in rows: + if not isinstance(row,dict) or type(row.get('record_sequence')) is not int:continue + if row['record_sequence']<=self.node_ack:continue + if row['record_sequence']>self.node_ack+1:self.live.add('live_view_gap',after=self.node_ack,before=row['record_sequence']) + self.live.add('record',record=row);self.node_ack=row['record_sequence'] + stored=packet.get('storage') or {} + if stored.get('closed'): + if self.local_owner is not None and self.trace.local.id == self.local_owner: + self.trace.local.stop(self.local_owner) + self.local_owner = None + self.closing=False;self.enabled=False + self.trace.configure(identifier,False) + self.export.ingest(packet.get('export')) + + def browser(self,body,*,local=False): + with self.lock: + target=self.trace.local if local else self.trace + admitted=target.active() if local else self.enabled and self.options['core_trace'] + if not isinstance(body,dict) or body.get('id')!=target.id or not admitted:return False + rows=body.get('events') + if not isinstance(rows,list) or len(rows)>32:raise ValueError('Invalid diagnostic events') + for row in rows: + if not isinstance(row,dict):raise ValueError('Invalid diagnostic event') + if row.get('event')=='preview' and local: + if not self.trace.local.preview: + continue + fields={'sample':preview_sample(row.get('sample'))} + stamp=row.get('browser_ms') + if type(stamp) in (int,float):fields['browser_ms']=stamp + else: + if row.get('event') not in INPUT_EVENTS:raise ValueError('Invalid diagnostic event') + fields={k:v for k,v in row.items() if k in INPUT_FIELDS} + if len(json.dumps(fields,allow_nan=False))>2048:raise ValueError('Diagnostic event too large') + if 'code' in fields and fields['code'] not in KEYS:fields.pop('code') + if 'held' in fields:fields['held']=[k for k in fields['held'] if k in KEYS][:8] if isinstance(fields['held'],list) else [] + # Local-only ingress must never be fanned out to the Node recorder. + (target.add if local else self.trace.add_remote)('browser_'+row['event'],**fields) + return True + + def view(self,after=0,limit=200): + with self.lock: + after=max(after,self.live.sequence-limit,0) + return {**self.live.snapshot(after,limit),'active':self.enabled,'closing':self.closing, + 'local_capture':self.trace.local.snapshot(limit=0), + 'core_stop_v1':self.control_stop.snapshot(), + 'node':self.node_status,'options':dict(self.options),'options_supported':self.supports_options,'schema':'missioncore.rover-dev/v1'} diff --git a/src/k1link/fleet/rover_diagnostics_export.py b/src/k1link/fleet/rover_diagnostics_export.py new file mode 100644 index 00000000..f66c199b --- /dev/null +++ b/src/k1link/fleet/rover_diagnostics_export.py @@ -0,0 +1,158 @@ +"""Bounded prefetch from the paired board; no whole-file cache on Core.""" + +import asyncio +import base64 +import hashlib +import json +import secrets +import threading + + +class DiagnosticExport: + WAIT_SECONDS = 120 # Includes pacing at the minimum optional bandwidth. + + def __init__(self): + self.changed = threading.Condition() + self.request = self.chunk = self.capture = None + self.busy = False + + def start(self, capture, *, offset=0, total=None, snapshot=None): + with self.changed: + if self.busy: + raise ValueError("Сохранение этого лога уже выполняется.") + if not capture: + raise ValueError("Сначала включите DEV.") + if type(offset) is not int or offset < 0 or (offset and total is None): + raise ValueError("Invalid export offset") + if total is not None and (type(total) is not int or total < offset or not snapshot): + raise ValueError("Invalid export snapshot") + self.busy = True + self.capture, self.chunk = capture, None + token = secrets.token_hex(16) + self.request = {"offset": offset, "token": token} + if total is not None: + self.request.update(total_bytes=total, snapshot=snapshot) + return token + + def begin(self, capture, **kwargs): + token = self.start(capture, **kwargs) + try: + return self.take(token) + except Exception: + self.finish(token) + raise + + def desired(self, large=False): + with self.changed: + if self.request is None: + return None + result = dict(self.request) + if large: + result["chunk_bytes"] = 65536 + return result + + def ingest(self, value): + with self.changed: + request = self.request + if not isinstance(value, dict) or not request or self.chunk is not None: + return + if ( + value.get("capture_id") != self.capture + or value.get("offset") != request["offset"] + or value.get("token") != request["token"] + ): + return + if any(type(value.get(k)) is not int for k in ("offset", "next", "total_bytes")): + return + if not value["offset"] <= value["next"] <= value["total_bytes"]: + return + encoded = value.get("data") + if not isinstance(encoded, str) or len(encoded) > 87384: + return + try: + data = base64.b64decode(encoded, validate=True) + except ValueError: + return + if len(data) > 65536 or len(data) != value["next"] - value["offset"]: + return + if not data and value["next"] != value["total_bytes"]: + return + if "total_bytes" in request and value["total_bytes"] != request["total_bytes"]: + return + if "snapshot" in request and value.get("snapshot") != request["snapshot"]: + return + # Legacy boards remain readable. Once a snapshot is advertised every + # block must carry its board checksum, including resumed transfers. + digest = value.get("sha256") + if ( + digest is not None or value.get("snapshot") is not None + ) and digest != hashlib.sha256(data).hexdigest(): + return + self.chunk = {**value, "data": data} + self.changed.notify_all() + + def take(self, token=None): + with self.changed: + token = token or (self.request or {}).get("token") + + def ready(): + return ( + self.chunk is not None + or not self.busy + or (self.request or {}).get("token") != token + ) + + if not self.changed.wait_for(ready, self.WAIT_SECONDS): + raise TimeoutError("Борт не передал файл. Проверьте связь и повторите сохранение.") + if not self.busy or (self.request or {}).get("token") != token: + raise TimeoutError("Сохранение завершено или отменено.") + chunk, self.chunk = self.chunk, None + # Admit at most one further block while the caller writes this one. + # Repeated delivery of the old offset is ignored, never queued. + if chunk["next"] < chunk["total_bytes"]: + self.request = { + "offset": chunk["next"], + "total_bytes": chunk["total_bytes"], + "token": token, + } + if chunk.get("snapshot"): + self.request["snapshot"] = chunk["snapshot"] + return chunk + + def stream(self, first): + token = first["token"] + try: + chunk = first + while True: + yield chunk["data"] + if chunk["next"] == chunk["total_bytes"]: + return + chunk = self.take(token) + finally: + self.finish(token) + + async def stream_async(self, first, *, framed=False): + token = first["token"] + try: + chunk = first + while True: + if framed: + row = {k: v for k, v in chunk.items() if k != "token"} + row["data"] = base64.b64encode(chunk["data"]).decode() + yield (json.dumps(row, separators=(",", ":")) + "\n").encode() + else: + yield chunk["data"] + if chunk["next"] == chunk["total_bytes"]: + return + chunk = await asyncio.to_thread(self.take, token) + finally: + # Cancels a blocked worker immediately on HTTP client disconnect. + self.finish(token) + + def finish(self, token=None): + with self.changed: + if token is not None and (self.request or {}).get("token") != token: + return + self.request = self.chunk = None + self.busy = False + self.changed.notify_all() diff --git a/src/k1link/fleet/rover_local_trace.py b/src/k1link/fleet/rover_local_trace.py new file mode 100644 index 00000000..8633e07a --- /dev/null +++ b/src/k1link/fleet/rover_local_trace.py @@ -0,0 +1,54 @@ +"""Explicit operator-host evidence; no Node traffic, disk I/O or motor authority.""" + +import secrets + +from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics + + +class LocalRoverTrace(BoundedDiagnostics): + MAX_BYTES = 2 * 1024 * 1024 + MAX_ROWS = 6000 + + def __init__(self, clock): + super().__init__("core", clock) + self.until = 0.0 + self.preview = True + + def active(self): + return super().active() and self.clock() < self.until + + def snapshot(self, after=0, limit=200): + return { + **super().snapshot(after, limit), + "expires_mono_ms": self.until * 1000, + "max_rows": self.MAX_ROWS, + "scope": "operator_host_only", + "preview": self.preview, + } + + def start(self, *, duration=900, previous_id=None, preview=True): + if type(preview) is not bool: + raise ValueError("Invalid preview capture option") + if type(duration) is not int or not 10 <= duration <= 3600: + raise ValueError("Invalid local capture duration") + if self.active(): + raise ValueError("Local capture is already active") + if self.id is not None and previous_id != self.id: + raise ValueError("Export the previous local capture and supply its identity") + self.preview = preview + self.until = self.clock() + duration + self.configure(secrets.token_hex(16), True) + self.add("local_capture_started", duration_s=duration) + return self.snapshot(limit=0) + + def stop(self, identifier): + if self.id is None or identifier != self.id: + raise ValueError("Local capture identity changed") + self.add("local_capture_stopped") + self.configure(identifier, False) + return self.snapshot(limit=0) + + def page(self, identifier, after=0, limit=200): + if self.id is None or identifier != self.id: + raise ValueError("Local capture identity changed") + return self.snapshot(after, limit) diff --git a/src/k1link/fleet/rover_metadata.py b/src/k1link/fleet/rover_metadata.py new file mode 100644 index 00000000..7f8377ae --- /dev/null +++ b/src/k1link/fleet/rover_metadata.py @@ -0,0 +1,81 @@ +"""One immutable metadata revision per relay/driver; no live values or authority.""" + +import copy + +TOP = {"supported", "control_modes", "profile"} +DEVICE = {"uuid", "slot", "label"} + + +def expand(snapshot, envelope, previous, *, relay, observed, now): + if ( + not isinstance(envelope, dict) + or set(envelope) - {"revision", "details"} + or type(envelope.get("revision")) is not int + or not 0 < envelope["revision"] < 2**53 + or not isinstance(snapshot.get("instance"), str) + or not snapshot["instance"] + or any(k in snapshot for k in TOP) + ): + raise ValueError("Invalid rover metadata envelope") + identity = (relay, snapshot["instance"]) + same = previous is not None and previous["identity"] == identity + revision = envelope["revision"] + if "details" in envelope: + details = envelope["details"] + if ( + not isinstance(details, dict) + or set(details) - TOP - {"devices"} + or not isinstance(details.get("devices"), dict) + or len(details["devices"]) > 500 + ): + raise ValueError("Invalid rover metadata") + for key, value in details["devices"].items(): + if ( + not isinstance(key, str) + or not key + or not isinstance(value, dict) + or set(value) - DEVICE + ): + raise ValueError("Invalid rover device metadata") + if same and ( + revision < previous["revision"] + or (revision == previous["revision"] and details != previous["details"]) + ): + raise ValueError("Rover metadata revision changed") + cache = { + "identity": identity, + "revision": revision, + "details": copy.deepcopy(details), + "observed": observed, + } + else: + if not same or revision != previous["revision"]: + raise ValueError("Rover metadata refresh required") + cache = previous + # A reference explicitly asserts the same immutable revision. Expiring + # these labels/profile by a network-age TTL rejects otherwise fresh samples + # and forces another handshake precisely when the transport is recovering. + # The caller still publishes the ORIGINAL sample clock, expires live values + # after one second, and never renews a control lease from this cache. + # Relay/driver/revision changes and roster conflicts remain fail-closed. + readings = snapshot.get("devices") + details = cache["details"] + if not isinstance(readings, list) or len(readings) != len(details["devices"]): + raise ValueError("Rover metadata roster changed") + seen = set() + result = copy.deepcopy(snapshot) + for row in result["devices"]: + if ( + not isinstance(row, dict) + or not isinstance(row.get("id"), str) + or row["id"] in seen + or row["id"] not in details["devices"] + or not isinstance(row.get("session_id"), str) + or not row["session_id"] + or any(k in row for k in DEVICE) + ): + raise ValueError("Invalid compact rover sample") + seen.add(row["id"]) + row.update(copy.deepcopy(details["devices"][row["id"]])) + result.update({k: copy.deepcopy(v) for k, v in details.items() if k != "devices"}) + return result, cache diff --git a/src/k1link/fleet/rover_observation_evidence.py b/src/k1link/fleet/rover_observation_evidence.py new file mode 100644 index 00000000..6c441acc --- /dev/null +++ b/src/k1link/fleet/rover_observation_evidence.py @@ -0,0 +1,59 @@ +"""Bounded lifecycle evidence, independent of DEV, values and motor authority. + +Only the latest receipt summary and 64 transitions live in RAM. Daily reset; +no raw samples, inventory, disk writes or network traffic. +""" +from collections import deque +from datetime import UTC, datetime + + +class ObservationEvidence: + def __init__(self, clock, utc_now=lambda: datetime.now(UTC)): + self.clock, self.utc_now = clock, utc_now + self.day = None + self._reset() + + def _reset(self): + self.day = self.utc_now().date() + self.events = deque(maxlen=64) + self.latest = None + self.receipts = self.ignored = 0 + self.max_gap_ms = 0. + self.phase = None + + def _daily(self): + if self.day != self.utc_now().date(): + self._reset() + + def event(self, kind): + self._daily() + self.events.append({"event": kind, "at_utc": self.utc_now().isoformat(), + "monotonic_ms": self.clock()*1000}) + + def receive(self, sampled, published, devices): + self._daily() + now = self.clock() + gap = 0. if self.latest is None else max(0., now-self.latest["received_mono_ms"]/1000)*1000 + self.max_gap_ms = max(self.max_gap_ms, gap) + self.receipts += 1 + self.ignored += int(not published) + self.latest = {"received_mono_ms": now*1000, "received_utc": self.utc_now().isoformat(), + "sample_age_at_receipt_ms": max(0., now-sampled)*1000, + "published": published, "sampled_devices": min(128, devices)} + if self.receipts == 1 or gap >= 1000: + self.event("first_receipt" if self.receipts == 1 else "receipt_after_gap") + + def view(self, fresh): + self._daily() + phase = "fresh" if fresh else "stale" if self.receipts else "awaiting_first_receipt" + if phase != self.phase: + self.phase = phase + self.event(phase) + + def snapshot(self): + self._daily() + return {"schema": "missioncore.observation-evidence/v1", "scope": "core_memory_daily", + "receipts": self.receipts, "ignored_older_receipts": self.ignored, + "max_receipt_gap_ms": self.max_gap_ms, "phase": self.phase, + "latest": dict(self.latest) if self.latest else None, + "events": list(self.events)} diff --git a/src/k1link/fleet/rover_preview_evidence.py b/src/k1link/fleet/rover_preview_evidence.py new file mode 100644 index 00000000..3d64d4c1 --- /dev/null +++ b/src/k1link/fleet/rover_preview_evidence.py @@ -0,0 +1,67 @@ +"""Local-only numeric video evidence; never a signaling or control payload.""" + +import math +import re + +NUMBERS = frozenset( + [ + 'width', + 'height', + 'source_age_ms', + 'sender_mono_ms', + 'allocation_bps', + 'target_bps', + 'encoder_bps', + 'receiver_bps', + 'max_width', + 'max_fps', + 'encoder_frames', + 'encoder_reinitializations', + 'encode_ms', + 'sent_bytes', + 'queue_dropped', + 'expired_frames', + 'expired_datagrams', + 'stale_rtp_packets', + 'max_permit_wait_ms', + 'decoder_errors', + 'decoder_frames', + 'decoder_gaps', + 'receiver_sampled_at_ms', + 'interval_ms', + 'fps', + 'mbps', + 'round_trip_ms', + 'jitter_buffer_ms', + 'requested_jitter_ms', + 'jitter_target_ms', + 'jitter_minimum_ms', + 'decode_ms', + 'processing_ms', + 'assembly_ms', + 'frames_dropped', + 'packets_lost', + 'freezes', + 'reset_frame', + 'reset_mono_ms', + ] +) + + +def preview_sample(value): + if not isinstance(value, dict): + raise ValueError("Invalid preview evidence") + result = {} + for key in ("peer_id", "device_session"): + item = value.get(key) + if not isinstance(item, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", item): + raise ValueError("Invalid preview identity") + result[key] = item + for key in NUMBERS & value.keys(): + item = value[key] + if type(item) not in (int, float) or not 0 <= item <= 2**53 - 1 or not math.isfinite(item): + raise ValueError("Invalid preview metric") + result[key] = item + if value.get("mode") in ("observing", "control_reserved"): + result["mode"] = value["mode"] + return result diff --git a/src/k1link/fleet/rover_stop_evidence.py b/src/k1link/fleet/rover_stop_evidence.py new file mode 100644 index 00000000..63d9e1e4 --- /dev/null +++ b/src/k1link/fleet/rover_stop_evidence.py @@ -0,0 +1,48 @@ +"""One latest Core withdrawal in RAM; independent of DEV and motion authority.""" + +from datetime import UTC, datetime +from threading import Lock + + +class CoreStopEvidence: + def __init__(self, clock, utc_now=lambda: datetime.now(UTC)): + self.clock, self.utc_now = clock, utc_now + self._latest = None + self._lock = Lock() + + def record(self, reason, session, *, core_instance, telemetry_age_ms, driver_state): + now, wall = self.clock(), self.utc_now() + # Board state is untrusted; never retain an arbitrary object or string. + state = driver_state if driver_state in ( + "observing", "preparing", "ready", "driving", "stopping", + "stopped", "fault", "receiver", + ) else None + value = (wall.date(), now, { + "schema": "missioncore.core-control-stop/v1", + "reason": reason, + "at_utc": wall.isoformat(), + "monotonic_ms": now * 1000, + "core_clock_instance": core_instance, + "session_id": session["id"], + "sequence": session["sequence"], + "operator_sequence": session["operator_sequence"], + "neutral_hold": session["neutral_hold"], + "remaining_ms": (session["until"] - now) * 1000, + "telemetry_age_ms": max(0, telemetry_age_ms), + "driver_state": state, + }) + + # No optional-recorder/export lock, file I/O or transport in this path. + with self._lock: + self._latest = value + + def snapshot(self): + now, day = self.clock(), self.utc_now().date() + with self._lock: + if self._latest is None: + return None + recorded_day, at, value = self._latest + if recorded_day != day or now - at >= 86400: + self._latest = None + return None + return dict(value) diff --git a/src/k1link/fleet/rover_stream_timing.py b/src/k1link/fleet/rover_stream_timing.py new file mode 100644 index 00000000..3bd2c842 --- /dev/null +++ b/src/k1link/fleet/rover_stream_timing.py @@ -0,0 +1,50 @@ +"""Opt-in per-frame evidence for the existing command stream.""" +import secrets +import time + + +class RoverStreamTiming: + def __init__(self, trace, clock=time.monotonic): + self.trace, self.clock = trace, clock + self.stream_id = secrets.token_hex(8) + self.capture_id = None + self.previous = None + self.index = 0 + + def write(self, writer, raw, data, *, dispatch_ms, wait_ms): + # No additional socket write, authority, queue, or retry. Without either capture, + # no frame evidence is serialized/stored and no previous sample is retained. + trace = self.trace + if trace is None or not getattr(trace, "recording", trace.active)(): + self.capture_id = self.previous = None + writer.write(raw) + return + started = self.clock() + outcome = "ok" + try: + writer.write(raw) + except OSError: + outcome = "write_error" + raise + finally: + finished = self.clock() + try: + identity = getattr(trace, "capture_identity", lambda: trace.id)() + if self.capture_id != identity: + self.capture_id, self.previous, self.index = identity, None, 0 + self.index += 1 + command = data.get("command") or {} + trace.add("command_stream_frame", stream_id=self.stream_id, + frame_index=self.index, session_id=command.get("id"), + sequence=command.get("sequence"), + frame_clock_ms=(data.get("control_clock") or {}).get("monotonic_ms"), + write_started_ms=started * 1000, + write_finished_ms=finished * 1000, + gap_ms=None if self.previous is None else (started-self.previous)*1000, + dispatch_ms=dispatch_ms, wait_ms=wait_ms, + write_ms=(finished-started)*1000, bytes=len(raw), outcome=outcome) + self.previous = started + except Exception: + # Evidence must not alter stream cleanup, including when the + # original socket write raised. Never log private socket errors. + pass diff --git a/src/k1link/fleet/sensor_transient.py b/src/k1link/fleet/sensor_transient.py new file mode 100644 index 00000000..4d702aaf --- /dev/null +++ b/src/k1link/fleet/sensor_transient.py @@ -0,0 +1,91 @@ +"""Bounded RAM receipts for Sample Data and QML; durable records are tombstones. + +After a Core restart an ephemeral request is never re-enqueued. A missing frame +or capture must be requested explicitly again with a new operation identity. +""" + +import hashlib +import json +import threading +import time +from collections import OrderedDict +from datetime import UTC, datetime +from functools import wraps + + +def ephemeral(action): + return action.startswith(("vesc.samples.", "vesc.qml.", "can.")) + + +def synchronized(method): + @wraps(method) + def run(self, *args, **kwargs): + with self.lock: + return method(self, *args, **kwargs) + + return run + + +class SensorTransient: + def __init__(self, clock=time.monotonic, day=lambda: datetime.now(UTC).date()): + self.clock, self.day = clock, day + self.date = day() + self.entries = OrderedDict() + self.lock = threading.RLock() + + @synchronized + def prune(self): + if self.day() != self.date: + self.entries.clear() + self.date = self.day() + now = self.clock() + for key, (at, _, _) in list(self.entries.items()): + if now - at >= 300: + del self.entries[key] + + @synchronized + def persist(self, row): + self.prune() + result = dict(row) + operations = dict(row.get("sensor_commands", {})) + for key, value in operations.items(): + command = value.get("command", {}) + if not ephemeral(command.get("action_id", "")) or value.get("ephemeral_expired"): + continue + cache_key = (row["id"], key) + raw = json.dumps(value, allow_nan=False).encode() + fingerprint = hashlib.sha256( + json.dumps(command, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + at = self.entries.get(cache_key, (self.clock(), None, None))[0] + self.entries[cache_key] = (at, fingerprint, raw) + operations[key] = { + "command": {**command, "parameters": {}}, + "state": "unknown", + "error": "Временный результат истёк. Повторите просмотр.", + "updated_at": value["updated_at"], + "ephemeral_expired": True, + "command_sha256": fingerprint, + } + while len(self.entries) > 64 or sum(len(v[2]) for v in self.entries.values()) > 8 * 1024**2: + self.entries.popitem(last=False) + if "sensor_commands" in row: + result["sensor_commands"] = operations + return result + + @synchronized + def hydrate(self, row): + self.prune() + for key, value in list(row.get("sensor_commands", {}).items()): + if not value.get("ephemeral_expired"): + continue + cached = self.entries.get((row["id"], key)) + if cached and cached[1] == value["command_sha256"]: + row["sensor_commands"][key] = json.loads(cached[2]) + return row + + +def cache(fleet): + if not hasattr(fleet, "_sensor_transient"): + fleet._sensor_transient = SensorTransient() + return fleet._sensor_transient diff --git a/src/k1link/fleet/sensors.py b/src/k1link/fleet/sensors.py index 01039072..f6b3d8f9 100644 --- a/src/k1link/fleet/sensors.py +++ b/src/k1link/fleet/sensors.py @@ -10,6 +10,7 @@ from missioncore_plugin_sdk.v0alpha2.session import DeviceSessionSnapshot from .trust import PairingError ACTIONS = { + "can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop", "prepare", "details", "rename", @@ -30,8 +31,8 @@ ACTIONS = { "files.list", "recovery.configure", "power.wake", - "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", - "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release", + "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", "vesc.bms.configuration.apply", "vesc.bms.configuration.reconcile", "vesc.bms.configuration.restore", "vesc.packages.catalog", "vesc.packages.inspect", "vesc.packages.download", "vesc.packages.begin", "vesc.packages.chunk", "vesc.packages.load", "vesc.packages.forget", "vesc.packages.status", "vesc.packages.prepare", "vesc.packages.remove_prepare", "vesc.packages.restore", "vesc.packages.apply", "vesc.packages.reconcile", "vesc.packages.refresh", "vesc.samples.start", "vesc.samples.status", "vesc.samples.fetch", "vesc.samples.stop", "vesc.samples.read", "vesc.qml.begin", "vesc.qml.chunk", "vesc.qml.render", "vesc.qml.open", "vesc.qml.frame", "vesc.qml.close", "vesc.code.read", "vesc.code.begin", "vesc.code.chunk", "vesc.code.prepare", "vesc.code.erase_prepare", "vesc.code.apply", "vesc.code.reconcile", "vesc.code.control_prepare", "vesc.code.control_apply", "vesc.code.stats", "vesc.code.restore", "vesc.bms.read", "vesc.bms.prepare", "vesc.bms.apply", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.reconcile", "vesc.firmware.backup", "vesc.firmware.target", "vesc.firmware.catalog", "vesc.firmware.catalog_prepare", "vesc.firmware.begin", "vesc.firmware.chunk", "vesc.firmware.seal", "vesc.firmware.discard", "vesc.firmware.apply", "vesc.firmware.status", "vesc.firmware.cancel", "vesc.firmware.reconcile", "vesc.diagnostics.read", + "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release", } MAX_INVENTORY_ITEMS = 500 MAX_SENSOR_STATE_BYTES = 3 * 1024 * 1024 @@ -73,6 +74,8 @@ def submit(fleet, vehicle_id, value): raise PairingError("Неподдерживаемая команда устройства.") with fleet.lock: row = fleet.find(vehicle_id) + from .network_media import offer + value = offer(row, value) if fleet.public(row)["connectivity"] != "online": raise PairingError("БК недоступен. Дождитесь связи перед настройкой устройства.") existing = row.setdefault("sensor_commands", {}).get(command.operation_id) @@ -140,7 +143,8 @@ def operation(fleet, vehicle_id, identifier): "state": "unknown", "error": "Подтверждение не получено. Обновите фактическое состояние устройства.", } - return value + from .network_media import answer + return answer(fleet.find(vehicle_id), value) def heartbeat(row, value): diff --git a/src/k1link/fleet/transport.py b/src/k1link/fleet/transport.py index dd2b00de..2e4fda67 100644 --- a/src/k1link/fleet/transport.py +++ b/src/k1link/fleet/transport.py @@ -6,6 +6,9 @@ import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from .heartbeat_encoding import decode_heartbeat +from .rover_datagram import QUALIFIED, RoverDatagramServer +from .rover_stream_timing import RoverStreamTiming from .trust import private_address @@ -18,7 +21,18 @@ class NodeChannelServer(ThreadingHTTPServer): self.address = address self.refresh_context() self.capacity = threading.BoundedSemaphore(16) + self.datagrams = None super().__init__((address, 8782), NodeChannelHandler) + try: + self.datagrams = RoverDatagramServer(address, registry) if QUALIFIED else None + except OSError: + super().server_close() + raise + + def server_close(self): + if self.datagrams is not None: + self.datagrams.close() + super().server_close() def refresh_context(self): self.context = self.registry.trust.server_context(self.address) @@ -62,18 +76,34 @@ class NodeChannelHandler(BaseHTTPRequestHandler): or self.headers.get("Origin") # A bounded 500-camera summary is carried both in devices and # sensor_state for the existing paired heartbeat contract. - or not 0 < size <= 8 * 1024 * 1024 + or not 0 < size <= ( + 2048 if self.path in ("/v1/node/liveness", "/v1/node/rover-datagram") else + 112 * 1024 if self.path == "/v1/node/rover-diagnostics" else 8 * 1024 * 1024 + ) ): raise ValueError - value = json.loads(self.rfile.read(size)) + body = self.rfile.read(size) + if len(body) != size: + raise ValueError + value = json.loads(decode_heartbeat(body, self.headers.get("Content-Encoding", ""), self.path)) if not isinstance(value, dict): raise ValueError + dispatched = time.monotonic() + path = "/v1/node/rover-link" if self.path == "/v1/node/rover-datagram" else self.path status, data = self.server.registry.receive( self.connection.getpeercert(binary_form=True), - self.path, + path, value, address=self.server.address, ) + if status == 200 and self.path == "/v1/node/rover-link": + data["latest_datagram_v1"] = getattr(self.server, "datagrams", None) is not None + if status == 200 and self.path == "/v1/node/rover-datagram": + status, data = (self.server.datagrams.open( + self.connection.getpeercert(binary_form=True), value) + if getattr(self.server, "datagrams", None) is not None + else (404, {"error": "Datagram transport unavailable"})) + dispatch_ms = (time.monotonic() - dispatched) * 1000 except (ValueError, KeyError, TypeError): self.close_connection = True status, data = 400, {"error": "Invalid request"} @@ -84,19 +114,26 @@ class NodeChannelHandler(BaseHTTPRequestHandler): self.send_header("Cache-Control", "no-store") self.send_header("Connection", "close") self.end_headers() + timing = RoverStreamTiming(self.server.registry.rover_control.stream_trace(value["node_id"])) + wait_ms = 0. try: while not self.server.registry.stop.is_set(): - self.wfile.write(json.dumps(data, allow_nan=False).encode()+b"\n") + timing.write(self.wfile, json.dumps(data, allow_nan=False).encode()+b"\n", + data, dispatch_ms=dispatch_ms, wait_ms=wait_ms) if not data.get("watch"): break # Every frame rechecks the same certificate and binding. # No queued intent and no lease renewal from a keepalive. + waited = time.monotonic() self.server.registry.rover_control.wait_for_intent( value["node_id"], value["relay_id"], data.get("command")) + wait_ms = (time.monotonic() - waited) * 1000 + dispatched = time.monotonic() status, data = self.server.registry.receive( self.connection.getpeercert(binary_form=True), self.path, value, address=self.server.address, ) + dispatch_ms = (time.monotonic() - dispatched) * 1000 if status != 200: break except (OSError, ValueError): diff --git a/src/k1link/web/app.py b/src/k1link/web/app.py index 4ae544dd..ec3f856f 100644 --- a/src/k1link/web/app.py +++ b/src/k1link/web/app.py @@ -151,6 +151,7 @@ from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router from k1link.web.environment_api import build_environment_router from k1link.web.frontend_assets import ControlStationStaticFiles, frontend_build_id from k1link.web.response_compression import ResponseCompressionMiddleware +from k1link.web.runtime_http_timing import RuntimeHttpTimingMiddleware from k1link.web.l3_pointpillars_visual_api import ( build_l3_pointpillars_visual_router, ) @@ -1008,6 +1009,8 @@ app = FastAPI( ) app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compresslevel=5) +app.add_middleware(RuntimeHttpTimingMiddleware) + app.include_router(fleet_router) app.include_router(equipment_router) diff --git a/src/k1link/web/fleet_api.py b/src/k1link/web/fleet_api.py index b18ff286..9a0ea94f 100644 --- a/src/k1link/web/fleet_api.py +++ b/src/k1link/web/fleet_api.py @@ -62,6 +62,11 @@ class RenameRequest(BaseModel): router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"]) +from .fleet_router_api import register as register_router_equipment +register_router_equipment(router, local_operator) +from .fleet_network_api import register as register_network_profiles +register_network_profiles(router, local_operator) + class BoardLayoutChange(BaseModel): model_config = ConfigDict(extra="forbid") @@ -154,16 +159,19 @@ def observation_configuration_write(vehicle_id: str, body: ObservationConfigurat @router.get("/{vehicle_id}/monitor") def board_monitor(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)], - metric: str = "cpu.usage", window: int = 900, end: float | None = None): + metric: str | None = None, window: int | None = None, + end: float | None = None): response.headers["Cache-Control"] = "no-store" try: + if metric is not None or window is not None or end is not None: + raise ValueError("Historical operator queries are unavailable") with fleet.lock: node_id = fleet.find(vehicle_id)["node_id"] - return fleet.monitor.query(node_id, metric, window, end) + return fleet.monitor.query(node_id) except PairingError as error: raise HTTPException(404, str(error)) from None except ValueError: - raise HTTPException(400, "Выберите доступный период и показатель.") from None + raise HTTPException(400, "Доступны только текущие показатели БК.") from None @router.get("") diff --git a/src/k1link/web/fleet_network_api.py b/src/k1link/web/fleet_network_api.py new file mode 100644 index 00000000..fa29f89f --- /dev/null +++ b/src/k1link/web/fleet_network_api.py @@ -0,0 +1,47 @@ +"""Operator-only network profile actions, separate from compute contours.""" +from typing import Annotated, Literal +from fastapi import Depends, HTTPException, Response +from pydantic import BaseModel, ConfigDict, Field +from k1link.fleet.registry import FleetRegistry + +class ImportProfile(BaseModel): + model_config = ConfigDict(extra="forbid") + document: str = Field(min_length=1, max_length=16384) + name: str = Field(default="", max_length=80) + network_interface: str | None = Field(default=None, max_length=20) + +class SelectProfile(BaseModel): + model_config = ConfigDict(extra="forbid") + provider: Literal["tailscale", "wireguard"] + profile_id: str | None = Field(default=None, max_length=80) + expected_revision: int = Field(ge=0, lt=2**53, strict=True) + + +def register(router, local_operator): + @router.get("/network-profiles") + def listing(fleet: Annotated[FleetRegistry, Depends(local_operator)]): + return {"items": fleet.network_profiles.listing()} + + @router.post("/network-profiles/import") + def import_profile(body: ImportProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]): + try: + return fleet.network_profiles.import_file(body.document, body.name, body.network_interface) + except (ValueError, OSError) as error: + raise HTTPException(409, str(error) if isinstance(error, ValueError) else "Не удалось подготовить подключение.") from None + + @router.get("/{vehicle_id}/network-profile") + def view(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]): + response.headers["Cache-Control"] = "no-store" + with fleet.lock: + try: + node_id = fleet.find(vehicle_id)["node_id"] + except ValueError as error: + raise HTTPException(404, str(error)) from None + return fleet.network_profiles.view(node_id) + + @router.put("/{vehicle_id}/network-profile") + def apply(vehicle_id: str, body: SelectProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]): + try: + return fleet.network_profiles.start(vehicle_id, body.provider, body.profile_id, body.expected_revision) + except ValueError as error: + raise HTTPException(409, str(error)) from None diff --git a/src/k1link/web/rover_api.py b/src/k1link/web/rover_api.py index 0e19eefc..e67b800c 100644 --- a/src/k1link/web/rover_api.py +++ b/src/k1link/web/rover_api.py @@ -6,20 +6,17 @@ from k1link.fleet.trust import PairingError from .fleet_api import local_operator router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"]) - -def node(fleet, vehicle): - with fleet.lock: - row = fleet.find(vehicle) - if row["enrollment"] != "paired": - raise ValueError("Борт не привязан.") - return row["node_id"] +from .rover_socket import register +register(router) +from .rover_diagnostics_api import register as register_diagnostics +register_diagnostics(router) @router.get("/{vehicle_id}/rover") def rover_state(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]): response.headers["Cache-Control"] = "no-store" try: - return fleet.rover_control.view(node(fleet, vehicle_id)) + return fleet.rover_channel.operator(vehicle_id, "view") except (ValueError, PairingError) as error: raise HTTPException(409, str(error)) from None @@ -27,9 +24,7 @@ def rover_state(vehicle_id: str, response: Response, def rover_arm(vehicle_id: str, body: dict, fleet: Annotated[FleetRegistry, Depends(local_operator)]): try: - # Admission and node resolution must not race a computer replacement. - with fleet.lock: - return fleet.rover_control.arm(node(fleet, vehicle_id), body) + return fleet.rover_channel.operator(vehicle_id, "arm", body) except (ValueError, PairingError) as error: raise HTTPException(409, str(error)) from None @@ -37,7 +32,6 @@ def rover_arm(vehicle_id: str, body: dict, def rover_command(vehicle_id: str, body: dict, fleet: Annotated[FleetRegistry, Depends(local_operator)]): try: - with fleet.lock: - return fleet.rover_control.command(node(fleet, vehicle_id), body) + return fleet.rover_channel.operator(vehicle_id, "command", body) except (ValueError, PairingError) as error: raise HTTPException(409, str(error)) from None diff --git a/src/k1link/web/rover_diagnostics_api.py b/src/k1link/web/rover_diagnostics_api.py new file mode 100644 index 00000000..56472bdd --- /dev/null +++ b/src/k1link/web/rover_diagnostics_api.py @@ -0,0 +1,149 @@ +"""Local operator DEV controls and full onboard-file streaming.""" + +import asyncio +import json +import re +from typing import Literal + +from fastapi import Depends, HTTPException, Query +from fastapi.responses import Response, StreamingResponse + +from ..fleet.trust import PairingError +from .fleet_api import local_operator + + +def register(router): + def recorder(fleet, vehicle): + try: + return fleet.rover_channel.operator(vehicle, "diagnostics") + except (ValueError, PairingError) as error: + raise HTTPException(409, str(error)) from None + + @router.get("/{vehicle_id}/rover/diagnostics") + def view(vehicle_id: str, after: int = Query(0, ge=0), fleet=Depends(local_operator)): + return recorder(fleet, vehicle_id).view(after) + + @router.get("/{vehicle_id}/rover/diagnostics/runtime") + def runtime(vehicle_id: str, fleet=Depends(local_operator)): + from .rover_runtime_diagnostics import snapshot + + recorder(fleet, vehicle_id) + result = snapshot() + result["observation"] = fleet.rover_channel.operator(vehicle_id, "observation_evidence") + return Response(json.dumps(result), media_type="application/json", + headers={"Cache-Control": "no-store"}) + + @router.post("/{vehicle_id}/rover/diagnostics") + def configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)): + if set(body)-{"enabled", "options", "local_options"} or type(body.get("enabled")) is not bool: + raise HTTPException(400, "Invalid DEV mode") + try: + return recorder(fleet, vehicle_id).set_enabled( + body["enabled"], body.get("options"), body.get("local_options")) + except ValueError as error: + raise HTTPException(409, str(error)) from None + + @router.post("/{vehicle_id}/rover/diagnostics/events") + def events(vehicle_id: str, body: dict, fleet=Depends(local_operator)): + try: + recorder(fleet, vehicle_id).browser(body) + except (ValueError, TypeError): + raise HTTPException(400, "Invalid diagnostic events") from None + return {"accepted": True} + + @router.post("/{vehicle_id}/rover/diagnostics/local") + def local_configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)): + if set(body)-{"enabled", "duration_s", "capture_id"} or type(body.get("enabled")) is not bool: + raise HTTPException(400, "Invalid local diagnostic mode") + capture = recorder(fleet, vehicle_id) + try: + with capture.lock: + if body["enabled"]: + capture.trace.local.start(duration=body.get("duration_s", 900), previous_id=body.get("capture_id")) + capture.trace.local.add("local_capture_context", context=capture.context, board_capture_id=capture.trace.id) + return capture.trace.local.snapshot(limit=0) + return capture.trace.local.stop(body.get("capture_id")) + except ValueError as error: + raise HTTPException(409, str(error)) from None + + @router.get("/{vehicle_id}/rover/diagnostics/local") + def local_view(vehicle_id: str, capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"), + after: int = Query(0, ge=0), limit: int = Query(200, ge=0, le=500), fleet=Depends(local_operator)): + capture = recorder(fleet, vehicle_id) + try: + with capture.lock: + return capture.trace.local.page(capture_id, after, limit) + except ValueError as error: + raise HTTPException(409, str(error)) from None + + @router.get("/{vehicle_id}/rover/diagnostics/local/export") + def local_export(vehicle_id: str, + capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"), + fleet=Depends(local_operator)): + capture = recorder(fleet, vehicle_id) + try: + with capture.lock: + page = capture.trace.local.page(capture_id, limit=capture.trace.local.MAX_ROWS) + except ValueError as error: + raise HTTPException(409, str(error)) from None + rows = page.pop("frames") + metadata = {"schema": "missioncore.operator-capture/v1", **page} + text = "\n".join(json.dumps(row, ensure_ascii=False, allow_nan=False) + for row in [metadata, *rows]) + "\n" + return Response(text, media_type="application/x-ndjson", headers={ + "Cache-Control": "no-store", + "Content-Disposition": f'attachment; filename="rover-operator-{capture_id}.jsonl"', + }) + + @router.post("/{vehicle_id}/rover/diagnostics/local/events") + def local_events(vehicle_id: str, body: dict, fleet=Depends(local_operator)): + try: + accepted = recorder(fleet, vehicle_id).browser(body, local=True) + except (ValueError, TypeError): + raise HTTPException(400, "Invalid local diagnostic events") from None + return {"accepted": bool(accepted)} + + @router.get("/{vehicle_id}/rover/diagnostics/export") + async def export( + vehicle_id: str, + format: Literal["raw", "chunks"] = "raw", + capture_id: str | None = Query(None, pattern=r"^[a-f0-9]{32}$"), + offset: int = Query(0, ge=0), + total_bytes: int | None = Query(None, ge=0), + snapshot: str | None = Query(None, pattern=r"^[a-f0-9]{64}$"), + fleet=Depends(local_operator), + ): + capture = recorder(fleet, vehicle_id) + if capture_id is not None and capture_id != capture.trace.id: + raise HTTPException(409, "Запись изменилась. Повторите сохранение нужной сессии.") + if offset and capture_id is None: + raise HTTPException(400, "Missing capture identity") + try: + token = capture.export.start( + capture.trace.id, offset=offset, total=total_bytes, snapshot=snapshot + ) + except ValueError as error: + raise HTTPException(409, str(error)) from None + try: + first = await asyncio.to_thread(capture.export.take, token) + if format == "chunks" and (not first.get("sha256") or not first.get("snapshot")): + raise HTTPException(409, "Для продолжения выгрузки обновите бортовой модуль VESC.") + except BaseException as error: + capture.export.finish(token) + if isinstance(error, TimeoutError): + raise HTTPException(503, str(error)) from None + raise + filename = first.get("file", "") + if not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", filename): + filename = f"rover-{capture.trace.id}.jsonl" + headers = { + "Cache-Control": "no-store", + "Content-Disposition": f'attachment; filename="{filename}"', + } + if format == "raw": + headers["Content-Length"] = str(first["total_bytes"] - offset) + return StreamingResponse( + capture.export.stream_async(first, framed=format == "chunks"), + media_type="application/x-ndjson", + headers=headers, + ) diff --git a/src/k1link/web/rover_runtime_diagnostics.py b/src/k1link/web/rover_runtime_diagnostics.py new file mode 100644 index 00000000..ac998c43 --- /dev/null +++ b/src/k1link/web/rover_runtime_diagnostics.py @@ -0,0 +1,41 @@ +"""Bounded read-only thread locations for local operator runtime diagnosis. + +No frame locals, source lines, request bodies, keys or persistent profiler are +exposed. A native sampler can correlate native_id with these Python locations. +""" +from __future__ import annotations + +import os +import sys +import threading +import time +from pathlib import PurePath + +from .runtime_http_timing import http_timings + + +def snapshot() -> dict: + started = time.monotonic() + threads = {thread.ident: thread for thread in threading.enumerate()} + frames = sys._current_frames() + rows = [] + try: + for ident, frame in sorted(frames.items())[:128]: + thread = threads.get(ident) + stack = [] + while frame is not None and len(stack) < 24: + code = frame.f_code + stack.append({"file": PurePath(code.co_filename).name[:128], + "function": code.co_name[:128], "line": frame.f_lineno}) + frame = frame.f_back + rows.append({"native_id": thread.native_id if thread else None, + "name": thread.name[:128] if thread else "unregistered", + "stack": stack, "truncated": frame is not None}) + finally: + # Do not retain application frames (and their locals) beyond this call. + frames.clear() + del frame + return {"schema": "missioncore.runtime-threads/v1", "pid": os.getpid(), + "monotonic_ms": started * 1000, "duration_ms": (time.monotonic()-started)*1000, + "thread_count": len(threads), "truncated": len(threads) > 128, + "threads": rows, "http": http_timings.snapshot()} diff --git a/src/k1link/web/rover_socket.py b/src/k1link/web/rover_socket.py new file mode 100644 index 00000000..3dc4a37a --- /dev/null +++ b/src/k1link/web/rover_socket.py @@ -0,0 +1,126 @@ +"""Independent local operator transport; the existing control authority is unchanged.""" +import asyncio +import json +import math +import secrets +import time +from contextlib import suppress + +from fastapi import HTTPException, WebSocket, WebSocketDisconnect + +from k1link.fleet.trust import PairingError + +from .fleet_api import local_operator + + +def register(router): + @router.websocket("/{vehicle_id}/rover-channel") + async def channel(socket: WebSocket, vehicle_id: str): + try: + fleet = local_operator(socket) + # WebSocket browser handshakes must have the exact local origin. + if socket.headers.get("origin") != f"http://{socket.headers.get('host', '')}": + raise HTTPException(403) + fleet.rover_channel.operator(vehicle_id, "view") + except (HTTPException, ValueError, PairingError): + await socket.close(code=1008) + return + trace=fleet.rover_channel.operator(vehicle_id,"diagnostics").trace + await socket.accept() + socket_id = secrets.token_hex(8) + trace.add("operator_socket_opened", socket_id=socket_id) + fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_opened") + owned = None + sending = asyncio.Lock() + + async def send(value): + async with sending: + await socket.send_json({**value, "socket_id": socket_id}) + + async def receive(): + nonlocal owned + window, count = time.monotonic(), 0 + while True: + raw = await socket.receive_text() + now = time.monotonic() + if now - window >= 1: + window, count = now, 0 + count += 1 + if len(raw) > 4096 or count > 64: + await socket.close(code=1008) + return + try: + message = json.loads(raw) + if (not isinstance(message, dict) + or set(message) != {"id", "action", "body", "expires_ms"} + or type(message["id"]) is not int + or not 0 < message["id"] < 2**53 + or message["action"] not in ("arm", "command", "hold") + or not isinstance(message["body"], dict) + or type(message["expires_ms"]) not in (int, float) + or not math.isfinite(message["expires_ms"])): + raise ValueError + except (ValueError, TypeError): + await socket.close(code=1008) + return + # A delayed local/browser send cannot become fresh motion on + # arrival. Clock samples are sent below; receipt never extends it. + remaining = message["expires_ms"] - time.monotonic() * 1000 + trace.add("operator_socket_received", socket_id=socket_id, request_id=message["id"], + action=message["action"], session_id=message["body"].get("session_id"), + sequence=message["body"].get("sequence"), received_ms=now*1000, + expires_ms=message["expires_ms"], remaining_ms=remaining, bytes=len(raw)) + if not 0 < remaining <= 400: + trace.add("operator_socket_rejected",reason="expired",action=message["action"],remaining_ms=remaining,session_id=owned,socket_id=socket_id) + await send({"type": "reply", "id": message["id"], "status": 408, + "error": "Команда устарела до передачи на борт."}) + continue + try: + if message["action"] in ("command", "hold") and message["body"].get("session_id") != owned: + raise ValueError("Управление не принадлежит этому окну.") + dispatch_started = time.monotonic() + result = fleet.rover_channel.operator(vehicle_id, message["action"], message["body"], expires_at=message["expires_ms"]/1000) + if message["action"] == "arm": + owned = result["session_id"] + trace.add("operator_socket_applied", socket_id=socket_id, request_id=message["id"], + session_id=owned, sequence=message["body"].get("sequence"), + action=message["action"], dispatch_ms=(time.monotonic()-dispatch_started)*1000) + # The ack carries a post-operation view. The browser must + # not apply its cached pre-arm controlling=false snapshot + # to the newly acknowledged session before the next push. + await send({"type": "reply", "id": message["id"], "value": result, + "state": fleet.rover_channel.operator(vehicle_id, "view"), + "clock_ms": time.monotonic()*1000}) + except (ValueError, PairingError) as error: + trace.add("operator_socket_rejected",reason=str(error)[:512],action=message["action"],session_id=owned,socket_id=socket_id) + await send({"type": "reply", "id": message["id"], "status": 409, "error": str(error)}) + + reader = asyncio.create_task(receive()) + next_state = 0. + try: + while not reader.done(): + if owned: + # Native process timer, independent of hidden browser JS. + # Only an explicit hold can produce fresh neutral frames. + fleet.rover_channel.operator(vehicle_id, "maintain_neutral", {"session_id": owned}) + if time.monotonic() < next_state: + await asyncio.wait({reader}, timeout=.1) + continue + next_state = time.monotonic()+.2 + value = fleet.rover_channel.operator(vehicle_id, "view") + await send({"type": "state", "value": value, "clock_ms": time.monotonic() * 1000}) + await asyncio.wait({reader}, timeout=.1) + await reader + except (WebSocketDisconnect, OSError, RuntimeError, ValueError, PairingError) as error: + trace.add("operator_socket_closed",error_type=type(error).__name__,close_code=getattr(error,"code",None),session_id=owned,socket_id=socket_id) + finally: + with suppress(ValueError, PairingError): + fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_closed") + reader.cancel() + with suppress(asyncio.CancelledError, WebSocketDisconnect, OSError, RuntimeError): + await reader + if owned: + with suppress(ValueError, PairingError): + fleet.rover_channel.operator(vehicle_id, "disconnect", {"session_id": owned}) + with suppress(WebSocketDisconnect, OSError, RuntimeError): + await socket.close() diff --git a/src/k1link/web/runtime_http_timing.py b/src/k1link/web/runtime_http_timing.py new file mode 100644 index 00000000..e2bb3c4d --- /dev/null +++ b/src/k1link/web/runtime_http_timing.py @@ -0,0 +1,68 @@ +"""Bounded, expiring HTTP timing metadata; no bodies, query strings or client IDs.""" +import threading +import time +from collections import deque + +from starlette.types import ASGIApp, Receive, Scope, Send + + +class HttpTimingWindow: + def __init__(self, clock=time.monotonic): + self.clock = clock + self.lock = threading.Lock() + self.rows = deque(maxlen=256) + + def add(self, row): + with self.lock: + self.rows.append(row) + self._expire(self.clock() * 1000) + + def _expire(self, now_ms): + while self.rows and now_ms - self.rows[0]["ended_mono_ms"] >= 30_000: + self.rows.popleft() + + def snapshot(self): + with self.lock: + self._expire(self.clock() * 1000) + return [dict(row) for row in self.rows] + + +http_timings = HttpTimingWindow() + + +class RuntimeHttpTimingMiddleware: + def __init__(self, app: ASGIApp, window=http_timings): + self.app, self.window = app, window + + async def __call__(self, scope: Scope, receive: Receive, send: Send): + if scope["type"] != "http": + return await self.app(scope, receive, send) + started = self.window.clock() * 1000 + status, size, first, complete = 500, 0, None, False + + async def measured_send(message): + nonlocal status, size, first, complete + if message["type"] == "http.response.start": + status = message["status"] + first = self.window.clock() * 1000 - started + elif message["type"] == "http.response.body": + size += len(message.get("body", b"")) + await send(message) + if message["type"] == "http.response.body" and not message.get("more_body", False): + complete = True + + try: + await self.app(scope, receive, measured_send) + finally: + ended = self.window.clock() * 1000 + # Only the registered route template is retained. The raw path can + # contain filenames, tokens or other user data even without a query. + route = getattr(scope.get("route"), "path", None) + route = (route[:240] if isinstance(route, str) and route.startswith("/api/") + else "") + method = scope.get("method") + if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}: + method = "" + self.window.add({"route": route, "method": method, "status": status, + "duration_ms": ended - started, "response_start_ms": first, + "ended_mono_ms": ended, "bytes": size, "complete": complete}) diff --git a/tests/fleet/test_heartbeat_encoding.py b/tests/fleet/test_heartbeat_encoding.py new file mode 100644 index 00000000..d6ed8573 --- /dev/null +++ b/tests/fleet/test_heartbeat_encoding.py @@ -0,0 +1,66 @@ +"""Compression changes framing, never identity, acknowledgements or body limits.""" + +import gzip +import http.client +import json +import threading +from http.server import ThreadingHTTPServer +from types import SimpleNamespace + +import pytest + +from k1link.fleet.heartbeat_encoding import MAX_HEARTBEAT_BYTES, decode_heartbeat +from k1link.fleet.transport import NodeChannelHandler + + +def test_encoding_rejects_truncation_concatenation_expansion_and_other_channels(): + body = b'{"snapshot":"fixture"}' + encoded = gzip.compress(body) + assert decode_heartbeat(body, "", "/v1/node/heartbeat") == body + assert decode_heartbeat(encoded, "gzip", "/v1/node/heartbeat") == body + for data, encoding, path in ( + (encoded[:-2], "gzip", "/v1/node/heartbeat"), + (encoded + encoded, "gzip", "/v1/node/heartbeat"), + (encoded + b"extra", "gzip", "/v1/node/heartbeat"), + (gzip.compress(b"x" * (MAX_HEARTBEAT_BYTES + 1)), "gzip", "/v1/node/heartbeat"), + (encoded, "deflate", "/v1/node/heartbeat"), + (encoded, "gzip", "/v1/node/rover"), + (encoded, "gzip", "/v1/node/liveness"), + ): + with pytest.raises(ValueError): + decode_heartbeat(data, encoding, path) + + +def test_http_decodes_before_existing_authentication_and_rejects_bad_body(): + calls = [] + + class Handler(NodeChannelHandler): + def setup(self): + super().setup() + self.connection = SimpleNamespace(getpeercert=lambda **_: b"fixture-cert") + + def receive(cert, path, value, *, address): + calls.append((cert, path, value)) + return 403, {"error": "Fixture binding rejected"} + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.address = "127.0.0.1" + server.registry = SimpleNamespace(receive=receive) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + try: + for raw, expected in ((gzip.compress(b'{"node_id":"fixture"}'), 403), (b"invalid", 400)): + client = http.client.HTTPConnection(*server.server_address, timeout=2) + try: + client.request("POST", "/v1/node/heartbeat", raw, + {"Content-Type": "application/json", "Content-Encoding": "gzip"}) + response = client.getresponse() + assert response.status == expected + assert "error" in json.loads(response.read()) + finally: + client.close() + assert calls == [(b"fixture-cert", "/v1/node/heartbeat", {"node_id": "fixture"})] + finally: + server.shutdown() + server.server_close() + worker.join(timeout=2) diff --git a/tests/fleet/test_network_profiles.py b/tests/fleet/test_network_profiles.py new file mode 100644 index 00000000..ec7acdd4 --- /dev/null +++ b/tests/fleet/test_network_profiles.py @@ -0,0 +1,148 @@ +import base64 +import importlib.util +import json +import secrets +import time +from pathlib import Path +from types import SimpleNamespace +import pytest +from k1link.fleet.network_profiles import parse_file, NetworkProfiles +from k1link.fleet.network_media import filter_sdp +from k1link.fleet.rover_control import RoverControl + + +def document(): + return dict(schema='missioncore.wireguard-connect/v1',server_id='wg_'+'1'*32,endpoint='https://vps.example.com:19444',vpn_endpoint='vps.example.com:51830',fingerprint='a'*64,server_public_key=base64.b64encode(b'1'*32).decode(),subnet='10.203.45.0/24',bootstrap=secrets.token_urlsafe(32),expires_at=int(time.time())+3600,capacity=50) + +@pytest.mark.parametrize('change',[{'subnet':'0.0.0.0/0'},{'subnet':'192.168.1.0/24'},{'endpoint':'http://vps.example.com:19444'},{'vpn_endpoint':'other.example.com:51830'},{'capacity':-1},{'private_key':'secret'},{'endpoint':'https://vps.example.com:19444/path'}]) +def test_import_rejects_unbounded_or_inconsistent_profile(change): + with pytest.raises(ValueError): parse_file(json.dumps({**document(),**change})) + + +def test_profile_is_shared_and_public_projection_has_no_credentials(tmp_path): + fleet=SimpleNamespace(root=tmp_path,trust=SimpleNamespace(core_id='core_test')) + profiles=NetworkProfiles(fleet); row={**document(), 'name':'Fleet', 'state':'ready','token':secrets.token_urlsafe(32)} + profiles.profiles[row['server_id']]=row;profiles.save() + reopened=NetworkProfiles(fleet) + assert 'capacity' not in reopened.listing()[0] + assert not {'token','bootstrap','private_key'} & reopened.listing()[0].keys() + assert reopened.profiles[row['server_id']]['token']==row['token'] + + +def test_media_admits_only_selected_peer_and_never_falls_back_to_tailnet(): + sdp='v=0\r\nc=IN IP4 100.64.1.2\r\na=candidate:1 1 udp 100 100.64.1.2 4567 typ host\r\na=candidate:2 1 udp 90 10.203.45.2 4568 typ host\r\n' + result=filter_sdp(sdp,'10.203.45.2') + assert '100.64.' not in result and '10.203.45.2' in result + with pytest.raises(ValueError):filter_sdp(sdp,'10.203.45.3') + + +def test_network_change_never_arms_or_replays_motion(): + control=RoverControl();control.network_change('node',True) + with pytest.raises(ValueError,match='переключения'): control.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':1000}) + assert not control.view('node')['controlling'] + control.network_change('node',False) + assert not control.view('node')['controlling'] + + +def helper_module(): + path=Path(__file__).parents[2]/'apps/wireguard-client/helper.py' + spec=importlib.util.spec_from_file_location('test_wireguard_helper',path); module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);return module + + +def test_helper_can_rollback_after_confirmation_and_process_restart(tmp_path,monkeypatch): + module=helper_module();manager=module.Manager(tmp_path);identity='wg_'+'1'*32 + manager.profiles[identity]={'private_key':'private','public_key':'public','config':{'old':True},'pending':None,'interface':None} + monkeypatch.setattr(module,'validate',lambda c:None) + monkeypatch.setattr(manager,'apply',lambda row,c:row.update(config=c)) + manager.dispatch({'action':'stage','server_id':identity,'operation_id':'2'*32,'config':{'server_id':identity}}) + manager.dispatch({'action':'confirm','server_id':identity,'operation_id':'2'*32}) + restored=module.Manager(tmp_path);monkeypatch.setattr(restored,'apply',lambda row,c:row.update(config=c)) + restored.dispatch({'action':'rollback','server_id':identity,'operation_id':'2'*32}) + assert restored.profiles[identity]['config']=={'old':True} + + +def test_revocation_is_durable_per_peer_and_does_not_touch_other_boards(tmp_path, monkeypatch): + import threading + fleet=SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'), stop=threading.Event()) + profiles=NetworkProfiles(fleet); row={**document(),'name':'Fleet','state':'ready','status':{'peers':[{'id':'node_1','kind':'node'},{'id':'node_2','kind':'node'}]}} + profiles.profiles[row['server_id']]=row;profiles.save();profiles.revoke_node('node_1') + profiles=NetworkProfiles(fleet);calls=[] + monkeypatch.setattr(profiles,'call',lambda row,method,path: calls.append((method,path)) or {'peers':[{'id':'node_2','kind':'node'}]}) + monkeypatch.setattr(profiles,'sync_operator',lambda row,status:None) + profiles.reconcile() + assert calls==[('DELETE','/v1/peers/node_1')] + assert profiles.profiles[row['server_id']]['revocations']==[] + + +def test_migration_adds_new_endpoint_and_only_retires_owned_previous_route(tmp_path, monkeypatch): + module=helper_module(); monkeypatch.setattr(module,'DARWIN',True) + manager=module.Manager(tmp_path);calls=[] + old={'endpoint':'8.8.8.8','gateway':'192.168.68.1','source':'192.168.68.54','interface':'en0'} + row={'host_route':old,'config':{'old':True}} + manager.profiles['fleet']=row + def run(*args,**kwargs): + calls.append(args) + if args[1:]==('getoption','en0','router'): data='192.168.68.1' + elif args[1:]==('getifaddr','en0'): data='192.168.68.54' + elif args[1:4]==('-n','get','8.8.8.8'): data='flags: \ngateway: 192.168.68.1\ninterface: en0\n' + else: data='flags: \ngateway: 192.168.68.1\ninterface: en0\n' + return SimpleNamespace(stdout=data.encode(),returncode=0) + monkeypatch.setattr(module,'run',run) + manager.physical_route({'interface':'en0'},'1.1.1.1',row) + assert ('/sbin/route','-n','add','-host','1.1.1.1','192.168.68.1','-ifa','192.168.68.54') in calls + assert not any(x[2:4]==('change','-host') for x in calls) + manager.retire_physical_routes(row) + assert ('/sbin/route','-n','delete','-host','8.8.8.8','192.168.68.1') in calls + assert list(row['host_routes'])==['1.1.1.1'] + + +def test_migration_never_replaces_foreign_static_destination(tmp_path,monkeypatch): + module=helper_module();monkeypatch.setattr(module,'DARWIN',True) + manager=module.Manager(tmp_path) + def run(*args,**kwargs): + if args[1]=='getoption': data='192.168.68.1' + elif args[1]=='getifaddr': data='192.168.68.54' + else: data='flags: \ngateway: 100.64.0.1\ninterface: utun9' + return SimpleNamespace(stdout=data.encode(),returncode=0) + monkeypatch.setattr(module,'run',run) + with pytest.raises(ValueError,match='conflicts'): + manager.physical_route({'interface':'en0'},'1.1.1.1',{'host_route':{'endpoint':'8.8.8.8'}}) + + +def test_failed_udp_probe_rolls_back_and_never_publishes_ready_profile(tmp_path,monkeypatch): + import threading + from k1link.fleet import network_client + fleet=SimpleNamespace(root=tmp_path,lock=threading.RLock(),trust=SimpleNamespace(core_id='core_test')) + profiles=NetworkProfiles(fleet);row={**document(),'name':'Fleet','state':'pending'} + profiles.profiles[row['server_id']]=row;calls=[] + monkeypatch.setattr(profiles,'operator_config',lambda row,status: {'server_id':row['server_id'],'address':'10.203.45.2'}) + monkeypatch.setattr(network_client,'request',lambda action,*args,**kwargs: calls.append(action)) + def fail(config):raise ValueError('UDP unavailable') + monkeypatch.setattr(network_client,'verify_tunnel',fail) + with pytest.raises(ValueError,match='UDP unavailable'):profiles.sync_operator(row,{'peers':[]}) + assert calls==['stage','rollback'] + assert profiles.profiles[row['server_id']]['state']=='pending' + + +def test_browser_mdns_offer_uses_only_nodes_wireguard_answer_without_resolving_lan(): + sdp='v=0\r\nc=IN IP4 0.0.0.0\r\na=candidate:1 1 udp 100 browser-123.local 4567 typ host\r\na=candidate:2 1 udp 90 100.64.1.2 4568 typ host\r\na=end-of-candidates\r\n' + result=filter_sdp(sdp,'10.203.45.2',browser_offer=True) + assert 'a=candidate:' not in result and '.local' not in result and '100.64.' not in result + assert 'a=end-of-candidates' not in result + with pytest.raises(ValueError):filter_sdp(sdp,'10.203.45.3') + + +def test_legacy_quota_is_ignored_and_new_connection_file_has_no_quota(): + old = document() + assert 'capacity' not in parse_file(json.dumps(old)) + old.pop('capacity') + assert parse_file(json.dumps(old)) == old + +def test_core_accepts_more_than_fifty_routes(monkeypatch): + module = helper_module() + monkeypatch.setattr(module.socket, 'getaddrinfo', lambda *a: [(2,1,6,'',('8.8.8.8',51830))]) + config = dict(server_id='wg_'+'1'*32, address='10.203.45.2', subnet='10.203.45.0/24', server_public_key=base64.b64encode(b'1'*32).decode(), endpoint='vps.example.com:51830', role='core', allowed_ips=['10.203.45.1/32']+[f'10.203.45.{n}/32' for n in range(3,83)]) + module.validate(config) + config['role']='node';config['address']='10.203.45.83' + with pytest.raises(ValueError, match='only its Core'): + module.validate(config) diff --git a/tests/fleet/test_pairing.py b/tests/fleet/test_pairing.py index 3f833d1a..8772541d 100644 --- a/tests/fleet/test_pairing.py +++ b/tests/fleet/test_pairing.py @@ -148,6 +148,41 @@ def test_recovery_only_uses_previously_reported_tailnet_addresses(): ) == ["100.64.20.4"] +def test_underlay_changes_preserve_pairing_and_tailnet_recovery(setup): + from k1link.fleet.recovery import node_addresses + + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + original = fleet.find(public["id"]) + certificate = cert(original) + channel = {"core_endpoint": "https://100.64.20.5:8782", "endpoint_revision": 1} + # The inventory can change interface, subnet and transport without + # replacing the authenticated Node or issuing another invitation. + for interface, address in [ + ("wlan0", "192.168.20.4/24"), + ("wlan1", "10.23.7.9/24"), + ("wwan0", "172.21.8.3/28"), + ("eth0", "192.168.93.7/24"), + ]: + payload = {**heartbeat(original), **channel} + payload["host"]["networks"] = [ + {"name": interface, "up": True, "addresses": [address]}, + {"name": "tailscale0", "up": True, "addresses": ["100.64.20.4/32"]}, + ] + assert fleet.receive(certificate, "/v1/node/heartbeat", payload, + address="100.64.20.5")[0] == 200 + current = fleet.find(public["id"]) + assert current["id"] == original["id"] + assert current["node_id"] == original["node_id"] + assert current["binding"]["binding_id"] == original["binding"]["binding_id"] + assert current["binding"]["client_pem"] == original["binding"]["client_pem"] + assert current["inventory"]["networks"][0]["addresses"] == [address] + assert node_addresses(current) == ["100.64.20.4"] + assert fleet.public(current)["connectivity"] == "online" + assert len(fleet.rows()) == 1 + + def test_recovery_client_leaf_is_distinct_from_issuer_with_same_pinned_key(setup): from cryptography.x509.oid import ExtendedKeyUsageOID @@ -597,3 +632,66 @@ def test_uninitialized_x4_can_be_prepared_remotely_with_instance_progress(setup) assert fleet.receive(cert(row), "/v1/node/heartbeat", inventory)[0] == 200 assert sensors.operation(fleet, row["id"], command["operation_id"])["preparation"] == progress assert fleet.find(row["id"])["sensor_state"]["preparations"] == [progress] + + +def liveness(row): + value = heartbeat(row) + del value["host"] + del value["devices"] + return value + + +def test_liveness_keeps_connection_without_refreshing_inventory_or_authority(setup, monkeypatch): + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + assert fleet.receive(cert(row), "/v1/node/heartbeat", heartbeat(row))[0] == 200 + row = fleet.find(public["id"]) + original = json.dumps(row, sort_keys=True) + now = time.time() + monkeypatch.setattr("k1link.fleet.registry.time.time", lambda: now+25) + assert fleet.public(row)["connectivity"] == "offline" + assert fleet.receive(cert(row), "/v1/node/liveness", liveness(row)) == ( + 200, {"ok": True, "heartbeat_encoding": "gzip"}) + view = fleet.public(fleet.find(public["id"])) + assert view["connectivity"] == "online" + assert view["inventory_fresh"] is False + assert view["last_seen"] == row["last_seen"] + assert view["link_last_seen"] == now+25 + assert json.dumps(fleet.find(public["id"]), sort_keys=True) == original + assert fleet.monitor.query(row["node_id"])["available"] is False + monkeypatch.setattr("k1link.fleet.registry.time.time", lambda: now+46) + assert fleet.public(row)["connectivity"] == "offline" + + +def test_liveness_rejects_wrong_binding_endpoint_and_heavy_payload(setup): + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + body = liveness(row) + assert fleet.receive(cert(row), "/v1/node/liveness", {**body, "binding_id":"wrong"})[0] == 410 + for extra in [{"host":{}}, {"sensor_results":[]}, {"command":{}}, + {"core_endpoint":"https://100.64.20.5:8782", "endpoint_revision":1}]: + status, _ = fleet.receive( + cert(row), "/v1/node/liveness", {**body, **extra}, address="192.168.20.5") + assert status == 400 + assert fleet.presence == {} + fleet.revoke(public["id"]) + assert fleet.receive(cert(row), "/v1/node/liveness", body)[0] == 410 + + +def test_liveness_restarted_node_does_not_freshen_old_device_sessions(setup): + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + assert fleet.receive(cert(row), "/v1/node/heartbeat", heartbeat(row))[0] == 200 + row = fleet.find(public["id"]) + assert fleet.public(row)["inventory_fresh"] is True + body = liveness(row) + body["execution_binding"]["agent_instance_id"] = "agent_restarted" + assert fleet.receive(cert(row), "/v1/node/liveness", body)[0] == 200 + assert fleet.public(row)["inventory_fresh"] is False + assert fleet.find(public["id"])["runtime"]["agent_instance_id"] == "agent_test" diff --git a/tests/fleet/test_rover_channel.py b/tests/fleet/test_rover_channel.py new file mode 100644 index 00000000..2d24123b --- /dev/null +++ b/tests/fleet/test_rover_channel.py @@ -0,0 +1,308 @@ +"""Control remains responsive during durable writes, without stale authority.""" +import sqlite3 +import threading +import time +from concurrent.futures import ThreadPoolExecutor + +import pytest +from fastapi import Response +from test_pairing import cert, create, heartbeat, setup # noqa: F401 +from test_replacement import attach, candidate + +from k1link.fleet.registry import FleetRegistry +from k1link.fleet.trust import SCHEMA +from k1link.web.rover_api import rover_arm, rover_command, rover_state + + +@pytest.fixture +def paired(setup): # noqa: F811 — imported pytest fixture + fleet = setup[0] + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + fleet.rover_control.clock = lambda: 100. + return fleet, row + + +def payload(row): + return {"schema": SCHEMA, "node_id": row["node_id"], + "binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32, + "rover": {"instance": "synthetic", "state": "observing", "supported": True}} + + +def arm(fleet, row): + return rover_arm(row["id"], {"standstill_confirmed": True, + "current_a": 5, "max_erpm": 1000}, fleet)["session_id"] + + +def test_control_both_directions_does_not_wait_for_heartbeat_storage(paired, monkeypatch): + fleet, row = paired + entered, release = threading.Event(), threading.Event() + + def slow_archive(*_): + entered.set() + assert release.wait(3) + + monkeypatch.setattr(fleet.vesc_archive, "receive", slow_archive) + certificate = cert(row) + + def control_round_trip(): + # Production BFF functions and authenticated Node receive path, no motor + # or socket. A gated archive models disk blocking, not synthetic load. + assert fleet.receive(certificate, "/v1/node/rover", payload(row))[0] == 200 + assert rover_state(row["id"], Response(), fleet)["fresh"] + session = arm(fleet, row) + command = {"session_id": session, "sequence": 1, "left": 0, "right": 0, + "stop": False} + assert rover_command(row["id"], command, fleet)["accepted_sequence"] == 1 + status, value = fleet.receive(certificate, "/v1/node/rover-stream", payload(row)) + assert status == 200 and value["command"]["sequence"] == 1 + assert value["command"]["expires_mono_ms"] == pytest.approx(100400) + rover_command(row["id"], {**command, "sequence": 2, "stop": True}, fleet) + assert not rover_state(row["id"], Response(), fleet)["controlling"] + + with ThreadPoolExecutor(max_workers=2) as pool: + writer = pool.submit(fleet.receive, certificate, "/v1/node/heartbeat", + {**heartbeat(row), "vesc_configurations": {}}) + try: + assert entered.wait(1) + # The old shared writer lock cannot complete this until release. + pool.submit(control_round_trip).result(timeout=1) + assert not writer.done() + finally: + release.set() + assert writer.result(timeout=2)[0] == 200 + + +@pytest.mark.parametrize("path", ["/v1/node/rover", "/v1/node/rover-stream", "/v1/node/rover-link", "/v1/node/rover-diagnostics"]) +@pytest.mark.parametrize("change,status", [({"binding_id": "wrong"}, 410), + ({"node_id": "wrong"}, 410), ({"schema": "wrong"}, 400), + ({"endpoint_revision": True}, 400), ({"endpoint_revision": -1}, 400), + ({"endpoint_revision": 1, "core_endpoint": "https://100.64.2.3:8782"}, 400)]) +def test_fast_channel_keeps_authentication(paired, path, change, status): + fleet, row = paired + assert fleet.receive(cert(row), path, {**payload(row), **change})[0] == status + + +def test_projection_changes_only_after_commit_and_revocation_retires_lease(paired): + fleet, row = paired + body = payload(row) + certificate = cert(row) + assert fleet.receive(certificate, "/v1/node/rover", body)[0] == 200 + arm(fleet, row) + row["enrollment"] = "revoked" + # Unsaved mutation cannot change a previously committed binding projection. + assert fleet.receive(certificate, "/v1/node/rover-stream", body)[1]["command"] + fleet.db.execute("CREATE TRIGGER fail_save BEFORE UPDATE ON vehicles " + "BEGIN SELECT RAISE(ABORT, 'synthetic failure'); END") + with pytest.raises(sqlite3.IntegrityError): + fleet.save(row) + assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] == 200 + fleet.db.execute("DROP TRIGGER fail_save") + fleet.save(row) + assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] == 410 + assert not fleet.rover_control.view(row["node_id"])["controlling"] + assert not fleet.rover_control.view(row["node_id"])["fresh"] + with pytest.raises(ValueError, match="не привязан"): + fleet.rover_channel.operator(row["id"], "arm", {}) + + +def test_certificate_rotation_and_endpoint_revision_are_published(paired, setup): # noqa: F811 + fleet, row = paired + body, old_cert = payload(row), cert(row) + row["certificate_previous"] = {"pem": row["binding"]["client_pem"], + "until": time.time() + 60} + row["binding"]["client_pem"] = fleet.trust.leaf(row["node_id"], setup[2].public_key()) + row["binding"]["endpoint_revision"] = 2 + fleet.save(row) + path = "/v1/node/rover-stream" + assert fleet.receive(old_cert, path, body)[0] == 409 + body["endpoint_revision"] = 2 + assert fleet.receive(old_cert, path, body)[0] == 200 + row["certificate_previous"]["until"] = 0 + fleet.save(row) + assert fleet.receive(old_cert, path, body)[0] == 403 + assert fleet.receive(cert(row), path, body)[0] == 200 + + +def test_startup_loads_bindings_but_never_restores_control(paired): + fleet, row = paired + fleet.receive(cert(row), "/v1/node/rover", payload(row)) + arm(fleet, row) + reopened = FleetRegistry(fleet.root) + try: + assert reopened.rover_channel.operator(row["id"], "view") == { + "fresh": False, "controlling": False, "snapshot": {}} + assert reopened.receive(cert(row), "/v1/node/rover", payload(row))[0] == 200 + finally: + reopened.close() + + +def test_replacement_removes_old_node_and_cannot_race_an_arm(paired, monkeypatch): + fleet, row = paired + fleet.receive(cert(row), "/v1/node/rover", payload(row)) + preview = candidate(fleet, monkeypatch) + entered, release, attempted = threading.Event(), threading.Event(), threading.Event() + from k1link.fleet import replacement + original = replacement.check_replacement + + def gated_check(*args): + original(*args) + entered.set() + assert release.wait(3) + + def concurrent_arm(): + attempted.set() + with pytest.raises(ValueError, match="не привязан"): + fleet.rover_channel.operator(row["id"], "arm", {}) + + monkeypatch.setattr(replacement, "check_replacement", gated_check) + with ThreadPoolExecutor(max_workers=2) as pool: + replacing = pool.submit(attach, fleet, row, preview) + try: + assert entered.wait(1) + arming = pool.submit(concurrent_arm) + assert attempted.wait(1) + assert not arming.done() + finally: + release.set() + replacing.result(timeout=2) + arming.result(timeout=2) + assert fleet.receive(cert(row), "/v1/node/rover-stream", payload(row))[0] == 410 + assert not fleet.rover_control.view(row["node_id"])["fresh"] + + +def test_link_probe_never_refreshes_telemetry_or_control(paired): + fleet, row = paired + certificate = cert(row) + body = payload(row) + probe = {k: v for k, v in body.items() if k != "rover"} + status, reply = fleet.receive(certificate, "/v1/node/rover-link", probe) + assert status == 200 and reply["connected"] and reply["sample_clock_v1"] + assert reply["control_clock"]["instance"] == fleet.rover_control.clock_id + assert not fleet.rover_control.boards + fleet.receive(certificate, "/v1/node/rover", body) + arm(fleet, row) + board = fleet.rover_control.boards[row["node_id"]] + seen, deadline = board["seen"], board["session"]["until"] + fleet.rover_control.clock = lambda: 102. + status, reply = fleet.receive(certificate, "/v1/node/rover-link", probe) + assert status == 200 and reply["connected"] and reply["sample_clock_v1"] + assert reply["control_clock"]["instance"] == fleet.rover_control.clock_id + assert board["seen"] == seen + assert board["session"]["until"] == deadline + assert fleet.receive(certificate, "/v1/node/rover-link", body)[0] == 400 + view = fleet.rover_control.view(row["node_id"]) + assert not view["fresh"] and not view["controlling"] and view["snapshot"] == {} + row["enrollment"] = "revoked" + fleet.save(row) + assert fleet.receive(certificate, "/v1/node/rover-link", probe)[0] == 410 + + +@pytest.mark.parametrize("phase", ["ingest", "desired"]) +def test_slow_dev_ingest_does_not_hold_authenticated_control_channel(paired, monkeypatch, phase): + fleet, row = paired + certificate, body = cert(row), payload(row) + fleet.receive(certificate, "/v1/node/rover", body) + diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"]) + entered, release = threading.Event(), threading.Event() + + original = getattr(diagnostics, phase) + + def gated(*args, **kwargs): + if phase == "ingest" and args[0] is None: + return original(*args, **kwargs) + entered.set() + assert release.wait(3) + return original(*args, **kwargs) + + monkeypatch.setattr(diagnostics, phase, gated) + + def control_round_trip(): + # Real channel entry points with a synthetic paired board. No sockets + # or hardware: DEV is parked, rather than generating load on the Mac. + assert fleet.receive(certificate, "/v1/node/rover", + {**body, "diagnostic_lane_v1": True})[0] == 200 + assert rover_state(row["id"], Response(), fleet)["fresh"] + session = arm(fleet, row) + command = {"session_id": session, "sequence": 1, "left": 0, "right": 0, + "stop": False} + rover_command(row["id"], command, fleet) + status, value = fleet.receive(certificate, "/v1/node/rover-stream", body) + assert status == 200 and value["command"]["sequence"] == 1 + rover_command(row["id"], {**command, "sequence": 2, "stop": True}, fleet) + + with ThreadPoolExecutor(max_workers=2) as pool: + optional = pool.submit(fleet.receive, certificate, "/v1/node/rover-diagnostics", + {**body, "diagnostics": {}}) + try: + assert entered.wait(1) + pool.submit(control_round_trip).result(timeout=1) + assert not optional.done() + finally: + release.set() + assert optional.result(timeout=2)[0] == 200 + + +def test_inflight_dev_cannot_cross_revocation_or_recreate_board(paired, monkeypatch): + fleet, row = paired + certificate, body = cert(row), payload(row) + fleet.receive(certificate, "/v1/node/rover", body) + diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"]) + entered, release = threading.Event(), threading.Event() + original = diagnostics.ingest + + def gated_ingest(packet): + entered.set() + assert release.wait(3) + original(packet) + + monkeypatch.setattr(diagnostics, "ingest", gated_ingest) + + def revoke(): + row["enrollment"] = "revoked" + fleet.save(row) + + with ThreadPoolExecutor(max_workers=2) as pool: + optional = pool.submit(fleet.receive, certificate, "/v1/node/rover-diagnostics", body) + try: + assert entered.wait(1) + pool.submit(revoke).result(timeout=1) + assert row["node_id"] not in fleet.rover_control.boards + finally: + release.set() + assert optional.result(timeout=2)[0] == 410 + assert row["node_id"] not in fleet.rover_control.boards + + +def test_telemetry_dispatch_timing_is_dev_only_and_has_no_authority(paired): + fleet, row = paired + body, certificate = payload(row), cert(row) + fleet.receive(certificate, "/v1/node/rover", body) + diagnostics = fleet.rover_control.diagnostics(row["node_id"], row["id"]) + assert diagnostics.trace.sequence == 0 + diagnostics.set_enabled(True) + status, reply = fleet.receive(certificate, "/v1/node/rover", body) + assert status == 200 + events = diagnostics.desired()["core_events"] + timing = [e for e in events if e["event"] == "node_telemetry_handled"] + assert len(timing) == 1 and timing[0]["dispatch_max_ms"] >= 0 + assert timing[0]["exchanges"] == 1 + assert timing[0]["reply_mono_ms"] == reply["control_clock"]["monotonic_ms"] + assert not {"binding_id", "certificate", "node_id", "rover"} & timing[0].keys() + for _ in range(10): + fleet.rover_control.record_telemetry_timing(row["node_id"], 25., 100000.) + assert diagnostics.trace.sequence == 2 # start + first report, not ten more rows + fleet.rover_control.clock = lambda: 101. + fleet.rover_control.record_telemetry_timing(row["node_id"], 3., 101000.) + latest = diagnostics.desired()["core_events"][-1] + assert latest["exchanges"] == 11 and latest["dispatch_max_ms"] == 25. + diagnostics.set_enabled(False) + previous = diagnostics.trace.sequence + fleet.receive(certificate, "/v1/node/rover", body) + assert diagnostics.trace.sequence == previous + # Timing itself cannot create a forgotten board, even if it arrives after + # revocation or an old request finishes while a new binding is pending. + fleet.rover_control.forget(row["node_id"]) + fleet.rover_control.record_telemetry_timing(row["node_id"], 10., 100000.) + assert row["node_id"] not in fleet.rover_control.boards diff --git a/tests/fleet/test_rover_control.py b/tests/fleet/test_rover_control.py index a535114c..45e185cf 100644 --- a/tests/fleet/test_rover_control.py +++ b/tests/fleet/test_rover_control.py @@ -11,6 +11,21 @@ def hub(): def arm(h): return h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':2000})['session_id'] +def test_throttle_requires_capable_current_board_and_preserves_units(hub): + h,now=hub + body={'standstill_confirmed':True,'current_a':30,'max_duty_percent':50} + with pytest.raises(ValueError):h.arm('node',body) + exchange(h,control_modes=['rpm','duty']) + h.arm('node',body) + assert h.stream('node','a'*32)['command']['settings']==body + +@pytest.mark.parametrize('change',[{'current_a':float('inf')},{'current_a':float('nan')},{'current_a':True},{'current_a':.49},{'max_duty_percent':0},{'max_duty_percent':101}, + {'max_duty_percent':float('nan')},{'max_duty_percent':True},{'max_erpm':3000}]) +def test_throttle_invalid_parameters_never_arm(hub,change): + h,_=hub;exchange(h,control_modes=['rpm','duty']) + with pytest.raises(ValueError):h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_duty_percent':50,**change}) + assert not h.view('node')['controlling'] + def cmd(id,seq=1,**kw): return {'session_id':id,'sequence':seq,'left':1,'right':1,'stop':False,**kw} @@ -22,6 +37,19 @@ def test_expired_browser_cannot_be_revived_by_late_packet(hub): assert exchange(h)['command'] is None with pytest.raises(ValueError):h.command('node',cmd(id,2)) +def test_socket_deadline_is_not_renewed_by_delayed_local_delivery(hub): + h,now=hub;identifier=arm(h) + h.command('node',cmd(identifier),expires_at=10.15) + assert h.stream('node','a'*32)['command']['expires_mono_ms']==pytest.approx(10150) + now[0]=10.16 + with pytest.raises(ValueError):h.command('node',cmd(identifier,2),expires_at=10.15) + assert not h.view('node')['controlling'] + +def test_expired_socket_arm_never_creates_authority(hub): + h,_=hub + with pytest.raises(ValueError):h.arm('node',{'standstill_confirmed':True,'current_a':30,'max_erpm':2000},expires_at=9.99) + assert not h.view('node')['controlling'] + def test_sequence_stop_and_single_owner(hub): h,_=hub;id=arm(h) with pytest.raises(ValueError):arm(h) @@ -32,11 +60,21 @@ def test_sequence_stop_and_single_owner(hub): with pytest.raises(ValueError):h.command('node',cmd(id,4)) assert exchange(h)['command'] is None -@pytest.mark.parametrize('snapshot',[{'state':'receiver'},{'state':'fault'},{'instance':'new-driver'}]) +@pytest.mark.parametrize('snapshot',[{'state':'receiver'},{'state':'fault'},{'state':'stopping','release_confirmed':False},{'instance':'new-driver'}]) def test_takeover_fault_or_driver_restart_revokes(hub,snapshot): h,_=hub;id=arm(h) assert exchange(h,session_id=id,**snapshot)['command'] is None +def test_stopping_retires_neutral_hold_before_settlement(hub): + h, _ = hub + identifier = arm(h) + h.hold('node', {'session_id': identifier, 'sequence': 1}) + assert exchange(h, session_id=identifier, state='stopping', release_confirmed=False)['command'] is None + assert not h.maintain_neutral('node', identifier) + with pytest.raises(ValueError): + h.command('node', cmd(identifier, 2, left=0, right=0)) + assert not h.view('node')['controlling'] + def test_relay_restart_and_cross_board_do_not_inherit_authority(hub): h,_=hub;id=arm(h) with pytest.raises(ValueError):h.command('other',cmd(id)) @@ -113,3 +151,124 @@ def test_intent_wait_wakes_on_update_and_does_not_miss_prior_update(hub): h.command('node', cmd(identifier, 2, stop=True)) with patch.object(h.changed, 'wait', side_effect=AssertionError('missed stop')): h.wait_for_intent('node', 'a'*32, latest, timeout=2) + + +def test_neutral_hold_keeps_same_session_for_five_seconds_and_separates_sequences(hub): + h, now = hub + identifier = arm(h) + h.command('node', cmd(identifier, 1)) + h.hold('node', {'session_id': identifier, 'sequence': 2}) + sequences = [] + for _ in range(60): + now[0] += .1 + exchange(h, state='ready', session_id=identifier) + assert h.maintain_neutral('node', identifier) + frame = h.stream('node', 'a'*32)['command'] + assert frame['id'] == identifier and frame['left'] == frame['right'] == 0 + assert set(frame) == {'id','sequence','left','right','settings','expires_mono_ms'} + sequences.append(frame['sequence']) + assert all(a < b for a,b in zip(sequences, sequences[1:])) + # Operator counter is independent of the native neutral heartbeat counter. + assert h.command('node', cmd(identifier, 3, left=-.5))['accepted_sequence'] == 3 + frame = h.stream('node', 'a'*32)['command'] + assert frame['sequence'] > sequences[-1] and frame['left'] == -.5 + assert not h.maintain_neutral('node', identifier), 'never renew movement' + now[0] += .401 + assert h.stream('node', 'a'*32)['command'] is None + + +def test_neutral_maintenance_cannot_start_extend_motion_or_revive_expired_lease(hub): + h, now = hub + assert not h.maintain_neutral('node', 'missing') + identifier = arm(h) + h.command('node', cmd(identifier, 1)) + before = h.stream('node', 'a'*32)['command'] + assert not h.maintain_neutral('node', identifier) + assert h.stream('node', 'a'*32)['command'] == before + h.hold('node', {'session_id': identifier, 'sequence': 2}) + assert not h.maintain_neutral('node', 'another-owner') + now[0] += .401 + exchange(h, state='ready', session_id=identifier) + assert not h.maintain_neutral('node', identifier) + with pytest.raises(ValueError): h.hold('node', {'session_id':identifier,'sequence':3}) + + +@pytest.mark.parametrize('failure',['disconnect','telemetry','fault','receiver','stopped','restart','relay','revoke']) +def test_neutral_hold_does_not_survive_real_failures(hub, failure): + h, now = hub + identifier = arm(h) + h.hold('node', {'session_id': identifier, 'sequence': 1}) + if failure == 'disconnect': h.disconnect('node', identifier) + elif failure == 'revoke': h.forget('node') + elif failure == 'telemetry': + for _ in range(11): + now[0] += .1 + h.maintain_neutral('node', identifier) + elif failure == 'relay': h.exchange('node', {'relay_id':'b'*32,'rover':{'instance':'driver'}}) + elif failure == 'restart': exchange(h, instance='new') + else: exchange(h, session_id=identifier, state=failure) + assert not h.maintain_neutral('node', identifier) + assert h.stream('node','a'*32)['command'] is None + + +@pytest.mark.parametrize('patch',[{'left':1},{'sequence':True},{'sequence':0},{'sequence':float('nan')},{'session_id':'other'}]) +def test_invalid_or_replayed_hold_cannot_overwrite_fresh_input(hub, patch): + h, _ = hub + identifier = arm(h) + h.command('node', cmd(identifier, 1)) + before = h.stream('node','a'*32)['command'] + with pytest.raises(ValueError):h.hold('node', {'session_id':identifier,'sequence':1,**patch}) + assert h.stream('node','a'*32)['command'] == before + + +def test_cached_readings_continue_aging_without_mutating_board_sample(hub): + h,now=hub + exchange(h,devices=[{'uuid':'synthetic','session_id':'usb-generation','age_ms':300}]) + now[0]+=.6 + first=h.view('node')['snapshot']['devices'][0] + assert first['age_ms']==pytest.approx(900,abs=1) + now[0]+=.2 + second=h.view('node')['snapshot']['devices'][0] + assert second['age_ms']==pytest.approx(1100,abs=1) + assert h.boards['node']['snapshot']['devices'][0]['age_ms']==300 + now[0]+=.21 + assert h.view('node')['snapshot']=={} + +@pytest.mark.parametrize('current',[35,60,100,120,150]) +def test_selected_current_reaches_board_without_a_hidden_30a_cap(hub,current): + h,_=hub;exchange(h,control_modes=['rpm','duty']) + body={'standstill_confirmed':True,'current_a':current,'max_duty_percent':100} + h.arm('node',body) + assert h.stream('node','a'*32)['command']['settings']==body + + +def test_idle_dev_hint_wakes_capture_stop_and_export_without_optional_lock(hub, monkeypatch): + h, _ = hub + d = h.diagnostics('node', 'rover') + body = {'relay_id': 'a'*32, 'rover': {'instance': 'driver', 'state': 'observing'}, 'diagnostic_lane_v1': True} + def forbidden(**kwargs): + raise AssertionError('critical lane entered optional recorder/export lock') + monkeypatch.setattr(d, 'desired', forbidden) + reply = h.exchange('node', body) + assert reply['diagnostics_pending'] is False and reply['diagnostics'] is None + assert reply['control_active'] is False and reply['command'] is None + for enabled, closing, export in [(True, False, False), (False, True, False), (False, False, True)]: + d.enabled, d.closing, d.export.busy = enabled, closing, export + reply = h.exchange('node', body) + assert reply['diagnostics_pending'] is True + assert reply['diagnostics'] is None and reply['command'] is None + + +def test_budget_summary_ages_independently_of_fresh_motor_samples(): + from k1link.fleet.rover_control import RoverControl + now = [100.] + control = RoverControl(clock=lambda: now[0]) + body = {'relay_id':'a'*32, 'rover':{'supported':True,'instance':'driver','state':'stopped'}} + control.exchange('node',{**body,'link_budget':{'effective_kbps':4000}}) + now[0] += .5 + control.exchange('node',body) + assert control.view('node')['link_budget']['snapshot_age_ms'] == 500 + now[0] += 2 + control.exchange('node',body) + value = control.view('node') + assert value['fresh'] and 'link_budget' not in value diff --git a/tests/fleet/test_rover_datagram.py b/tests/fleet/test_rover_datagram.py new file mode 100644 index 00000000..b8239177 --- /dev/null +++ b/tests/fleet/test_rover_datagram.py @@ -0,0 +1,123 @@ +"""Authentication, ordering and bounded latest-state framing; synthetic keys.""" +import pytest + +from k1link.fleet.rover_datagram import MAX_COUNTER, DatagramCipher + + +def test_authentication_replay_reorder_direction_and_counter_bounds(): + channel, key = bytes.fromhex('11' * 16), bytes.fromhex('22' * 32) + tx, rx = DatagramCipher(channel, key), DatagramCipher(channel, key) + old, fresh = tx.seal({}), tx.seal({'fresh': True}) + corrupt = fresh[:-1] + bytes([fresh[-1] ^ 1]) + assert rx.open(corrupt) is None + assert rx.open(fresh) == (2, {'fresh': True}) + for packet in (old, fresh, fresh + b'x', fresh[:20]): + assert rx.open(packet) is None + assert DatagramCipher(channel, bytes.fromhex('33' * 32)).open(fresh) is None + tx.sent = MAX_COUNTER + with pytest.raises(ValueError): + tx.seal({}) + with pytest.raises(ValueError): + rx.seal({'data': 'x' * 1200}) + + +def test_public_interoperability_vector(): + cipher = DatagramCipher(bytes.fromhex('11' * 16), bytes.fromhex('22' * 32)) + assert cipher.seal({}).hex() == ( + '4d435231111111111111111111111111111111110000000000000001' + '08b7c9b2eb8c526f9dc03ac92264617fd09b') + + +def test_server_rechecks_authority_and_never_answers_forged_or_replayed_probe(): + import socket + import time + from types import SimpleNamespace + + from k1link.fleet.rover_datagram import RoverDatagramServer + + authorized, calls, traces = [True], [], [] + def receive(cert, path, value, *, address): + calls.append((cert, path, value, address)) + if not authorized[0]: + return 410, {} + return 200, {'watch': True, 'command': None, + 'control_clock': {'instance': 'a' * 32, 'monotonic_ms': 10000}} + registry = SimpleNamespace(receive=receive, rover_channel=SimpleNamespace(same_generation=lambda _: True), rover_control=SimpleNamespace( + _clock=lambda: {'instance': 'a' * 32, 'monotonic_ms': 10000}, + stream_trace=lambda _: SimpleNamespace( + add=lambda event, **data: traces.append((event, data))), + intent_changed=lambda *_: False)) + server = RoverDatagramServer('127.0.0.1', registry, port=0) + client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + client.settimeout(.2) + try: + status, grant = server.open( + b'authenticated-fixture-cert', {'node_id': 'fixture', 'relay_id': 'b' * 32}) + assert status == 200 + address = ('127.0.0.1', grant['port']) + channel = bytes.fromhex(grant['channel']) + tx = DatagramCipher(channel, bytes.fromhex(grant['send_key'])) + rx = DatagramCipher(channel, bytes.fromhex(grant['receive_key'])) + probe = tx.seal({}) + client.sendto(probe[:-1] + bytes([probe[-1] ^ 1]), address) + with pytest.raises(TimeoutError): + client.recv(1201) + assert not calls + client.sendto(probe, address) + packet, _ = client.recvfrom(1201) + _, frame = rx.open(packet) + assert frame['probe'] == 1 and frame['reply']['command'] is None + assert len(packet) <= 1200 + with server.lock: + last_probe = server.channels[channel]['last_probe'] + client.sendto(probe, address) + time.sleep(.025) + with server.lock: + assert server.channels[channel]['last_probe'] == last_probe + authorized[0] = False + time.sleep(.1) + with server.lock: + assert channel not in server.channels + assert len(calls) >= 2 + assert traces and all(event == "datagram_sent" for event, _ in traces) + for _, row in traces: + phases = [row[key] for key in ("registry_ms", "encrypt_ms", "socket_ms")] + assert all(value >= 0 for value in phases) + assert sum(phases) == pytest.approx(row["dispatch_ms"]) + assert "authenticated-fixture-cert" not in str(row) + assert all(call[0] == b'authenticated-fixture-cert' and + call[1] == '/v1/node/rover-stream' for call in calls) + finally: + client.close() + server.close() + assert not server.thread.is_alive() + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_transport_listener_owns_datagram_lifecycle(monkeypatch, enabled): + from http.server import ThreadingHTTPServer + from types import SimpleNamespace + + from k1link.fleet import transport + from k1link.fleet.rover_datagram import RoverDatagramServer + + # Only addresses use ephemeral test ports. Exercise production ownership + # of both sockets and the datagram worker, including disabled compatibility. + initialize = ThreadingHTTPServer.__init__ + monkeypatch.setattr(ThreadingHTTPServer, "__init__", lambda self, addr, handler: + initialize(self, (addr[0], 0), handler)) + monkeypatch.setattr(transport, "QUALIFIED", enabled) + monkeypatch.setattr(transport, "RoverDatagramServer", lambda address, registry: + RoverDatagramServer(address, registry, port=0)) + registry = SimpleNamespace(trust=SimpleNamespace(server_context=lambda _: None)) + server = transport.NodeChannelServer("127.0.0.1", registry) + datagrams = server.datagrams + try: + assert (datagrams is not None) == enabled + if enabled: + assert datagrams.thread.is_alive() and datagrams.socket.fileno() >= 0 + finally: + server.server_close() + assert server.socket.fileno() == -1 + if enabled: + assert not datagrams.thread.is_alive() and datagrams.socket.fileno() == -1 diff --git a/tests/fleet/test_rover_datagram_binding.py b/tests/fleet/test_rover_datagram_binding.py new file mode 100644 index 00000000..11a27618 --- /dev/null +++ b/tests/fleet/test_rover_datagram_binding.py @@ -0,0 +1,179 @@ +"""Real committed pairing checks on every datagram frame, synthetic identities.""" +import socket +import time + +import pytest +from test_pairing import cert, create, setup # noqa: F401 + +from k1link.fleet.rover_datagram import DatagramCipher, RoverDatagramServer +from k1link.fleet.trust import SCHEMA + + +@pytest.mark.parametrize("change", ["revocation", "certificate", "endpoint"]) +def test_replacement_destroys_old_channel_and_committed_auth_change_closes_new(setup, change): # noqa: F811 + fleet, _, key, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + body = {"schema": SCHEMA, "node_id": row["node_id"], + "binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32} + fleet.rover_control.view(row["node_id"]) + certificate = cert(row) + server = RoverDatagramServer("127.0.0.1", fleet, port=0) + client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + client.settimeout(.2) + address = server.socket.getsockname() + try: + status, first = server.open(certificate, body) + assert status == 200 + old = DatagramCipher(bytes.fromhex(first["channel"]), bytes.fromhex(first["send_key"])) + client.sendto(old.seal({}), address) + client.recv(1201) + status, second = server.open(certificate, body) + assert status == 200 + assert all(first[k] != second[k] for k in ("channel", "send_key", "receive_key")) + with server.lock: + assert len(server.channels) == 1 + assert bytes.fromhex(first["channel"]) not in server.channels + # Drain only packets sent before replacement. The old generation cannot + # establish the new reply address or renew its probe lifetime. + client.settimeout(.03) + while True: + try: + client.recv(1201) + except TimeoutError: + break + client.sendto(old.seal({}), address) + with pytest.raises(TimeoutError): + client.recv(1201) + fresh = DatagramCipher(bytes.fromhex(second["channel"]), bytes.fromhex(second["send_key"])) + reply = DatagramCipher( + bytes.fromhex(second["channel"]), bytes.fromhex(second["receive_key"])) + client.settimeout(.2) + client.sendto(fresh.seal({}), address) + assert reply.open(client.recv(1201))[1]["reply"]["command"] is None + if change == "revocation": + row["enrollment"] = "revoked" + elif change == "certificate": + row["binding"]["client_pem"] = fleet.trust.leaf(row["node_id"], key.public_key()) + else: + row["binding"]["endpoint_revision"] = 2 + fleet.save(row) + deadline = time.monotonic() + .3 + while time.monotonic() < deadline: + with server.lock: + if not server.channels: + break + time.sleep(.005) + with server.lock: + assert not server.channels + assert fleet.receive(certificate, "/v1/node/rover-stream", body)[0] in (403, 409, 410) + finally: + client.close() + server.close() + assert not server.thread.is_alive() + + +def test_fresh_latest_input_and_stop_bypass_pending_keepalive(setup): # noqa: F811 + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public['id']) + row = fleet.find(public['id']) + node = row['node_id'] + base = {'schema': SCHEMA, 'node_id': node, + 'binding_id': row['binding']['binding_id'], 'relay_id': 'a' * 32} + certificate = cert(row) + assert fleet.receive(certificate, '/v1/node/rover', {**base, 'rover': { + 'instance': 'synthetic', 'supported': True, 'state': 'observing'}})[0] == 200 + fleet.rover_control.view(node) + server = RoverDatagramServer('127.0.0.1', fleet, port=0) + client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + client.settimeout(.3) + try: + _, grant = server.open(certificate, base) + 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()) + assert rx.open(client.recv(1201))[1]['reply']['command'] is None + # Hold only the periodic deadline far enough out to avoid fragile + # millisecond timing assertions. Fresh authority must still be sampled. + with server.lock: + server.channels[channel]['next'] = time.monotonic() + 5 + sid = fleet.rover_control.arm(node, { + 'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000})['session_id'] + for sequence in (1, 2, 3): + fleet.rover_control.command(node, {'session_id': sid, 'sequence': sequence, + 'left': 0, 'right': 0, 'stop': False}) + expires = fleet.rover_control.boards[node]['session']['until'] * 1000 + frame = rx.open(client.recv(1201))[1]['reply'] + assert frame['command']['sequence'] == 3 # no queued older commands + assert frame['command']['expires_mono_ms'] == expires + with server.lock: + server.channels[channel]['next'] = time.monotonic() + 5 + fleet.rover_control.command(node, {'session_id': sid, 'sequence': 4, + 'left': 0, 'right': 0, 'stop': True}) + assert rx.open(client.recv(1201))[1]['reply']['command'] is None + finally: + client.close() + server.close() + assert not server.thread.is_alive() + + +def test_early_fresh_send_still_rechecks_committed_binding(setup): # noqa: F811 + fleet, _, _, _ = setup + public, _ = create(setup) + fleet.advance(public['id']) + row = fleet.find(public['id']) + node = row['node_id'] + base = {'schema': SCHEMA, 'node_id': node, + 'binding_id': row['binding']['binding_id'], 'relay_id': 'a' * 32} + certificate = cert(row) + assert fleet.receive(certificate, '/v1/node/rover', {**base, 'rover': { + 'instance': 'synthetic', 'supported': True, 'state': 'observing'}})[0] == 200 + fleet.rover_control.view(node) + server = RoverDatagramServer('127.0.0.1', fleet, port=0) + client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + client.settimeout(.15) + try: + _, grant = server.open(certificate, base) + channel = bytes.fromhex(grant['channel']) + tx = DatagramCipher(channel, bytes.fromhex(grant['send_key'])) + client.sendto(tx.seal({}), server.socket.getsockname()) + client.recv(1201) + with server.lock: + server.channels[channel]['next'] = time.monotonic() + 5 + fleet.rover_control.arm(node, { + 'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000}) + # Commit a new endpoint revision while the new input is waiting. + row['binding']['endpoint_revision'] = 2 + fleet.save(row) + assert not fleet.rover_control.view(node)['controlling'] + with pytest.raises(TimeoutError): + client.recv(1201) + with server.lock: + assert not server.channels + finally: + client.close() + server.close() + + +def test_wake_hint_does_not_create_board_or_renew_authority(): + from k1link.fleet.rover_control import RoverControl + + now = [10.] + control = RoverControl(lambda: now[0]) + assert not control.intent_changed('absent', 'a' * 32, None) + assert control.boards == {} + control.exchange('node', {'relay_id': 'a' * 32, 'rover': { + 'instance': 'synthetic', 'supported': True, 'state': 'observing'}}) + sid = control.arm('node', { + 'standstill_confirmed': True, 'current_a': 5, 'max_erpm': 1000})['session_id'] + deadline = control.boards['node']['session']['until'] + assert control.intent_changed('node', 'a' * 32, None) + assert not control.intent_changed('node', 'b' * 32, None) + assert not control.intent_changed('node', 'a' * 32, {'id': sid, 'sequence': 0}) + now[0] = deadline + .001 + assert control.intent_changed('node', 'a' * 32, None) + assert control.boards['node']['session']['until'] == deadline + assert control.stream('node', 'a' * 32)['command'] is None diff --git a/tests/fleet/test_rover_diagnostics.py b/tests/fleet/test_rover_diagnostics.py new file mode 100644 index 00000000..c2d3dd74 --- /dev/null +++ b/tests/fleet/test_rover_diagnostics.py @@ -0,0 +1,154 @@ +import base64 +import threading +from k1link.fleet.rover_diagnostics import RoverDiagnostics + +def test_capture_is_independent_of_motion_and_does_not_expire(): + now=[0];d=RoverDiagnostics(lambda:now[0]) + assert d.desired() is None + d.set_enabled(True);identifier=d.trace.id + now[0]=7200;assert d.desired()['enabled'] + d.browser({'id':identifier,'events':[{'event':'key_down','code':'KeyQ','held':['KeyQ','secret text']}]}) + sent=d.desired()['core_events'];assert len(sent)==2 + assert sent[-1]['held']==['KeyQ'] + d.ingest({'id':identifier,'frames':[{'record_sequence':1,'event':'sample','source':'vesc'}], + 'storage':{'closed':False,'external_ack':{'core':2}}}) + assert not d.desired()['core_events'] # Received VESC records cannot echo back to disk. + d.set_enabled(False);assert d.desired()['enabled'] # Flush final Core event. + d.ingest({'id':identifier,'frames':[],'storage':{'closed':False,'external_ack':{'core':3}}}) + assert not d.desired()['enabled'];assert d.closing + d.ingest({'id':identifier,'frames':[],'storage':{'closed':True,'external_ack':{'core':3}}}) + assert not d.closing + d.set_enabled(True);assert d.trace.id!=identifier + +def test_export_reads_board_chunks_not_live_ring(): + d=RoverDiagnostics(lambda:0);d.set_enabled(True) + result=[] + def read(): + first=d.export.begin(d.trace.id);result.extend(d.export.stream(first)) + thread=threading.Thread(target=read);thread.start() + import time + deadline=time.monotonic()+2 + sent=set() + while thread.is_alive() and time.monotonic() 0 and page["bytes"] <= 1100 and len(page["frames"]) <= 4 + assert page["first_sequence"] > 1 + trace.stop(identifier) + with pytest.raises(ValueError): + trace.start() + assert trace.start(previous_id=identifier)["id"] != identifier + with pytest.raises(ValueError): + trace.page(identifier) + + +def test_local_api_rejects_foreign_origins_wrong_generations_and_does_not_arm(request): + control, client = request.getfixturevalue("fixture") + url = "/api/v1/fleet/vehicle/rover/diagnostics/local" + assert ( + client.post( + url, json={"enabled": True}, headers={"Origin": "https://foreign.invalid"} + ).status_code + == 403 + ) + assert client.post(url, json={"enabled": 1}).status_code == 400 + assert client.post(url, json={"enabled": True, "duration_s": 3601}).status_code == 409 + local_id = client.post(url, json={"enabled": True, "duration_s": 10}).json()["id"] + assert client.post(url, json={"enabled": True}).status_code == 409 + with connect(client) as socket: + state = socket.receive_json() + # Deliberately expired request against an in-memory fixture, no actuator. + socket.send_json( + { + "id": 37, + "action": "command", + "expires_ms": state["clock_ms"] - 1, + "body": {"session_id": "a" * 32, "sequence": 19}, + } + ) + value = reply(socket) + assert value["status"] == 408 and value["socket_id"] == state["socket_id"] + rows = client.get(url, params={"capture_id": local_id}).json()["frames"] + received = next(r for r in rows if r["event"] == "operator_socket_received") + assert received["request_id"] == 37 and received["sequence"] == 19 + assert received["socket_id"] == state["socket_id"] + assert not control.view("node")["controlling"] + assert control.stream("node", "a" * 32)["command"] is None + assert not client.get("/api/v1/fleet/vehicle/rover/diagnostics").json()["active"] + assert client.get(url, params={"capture_id": "f" * 32}).status_code == 409 + assert client.get(url, params={"capture_id": local_id, "limit": 501}).status_code == 422 + assert client.post(url, json={"enabled": False, "capture_id": "f" * 32}).status_code == 409 + assert client.post(url, json={"enabled": False, "capture_id": local_id}).status_code == 200 + assert client.post(url + "/events", json={"id": local_id, "events": []}).json() == { + "accepted": False + } + + +def test_preview_metrics_are_local_only_and_explicitly_projected(): + from k1link.fleet.rover_preview_evidence import preview_sample + + d = RoverDiagnostics(lambda: 10.0) + d.supports_options = True + d.set_enabled(True, {**LOCAL_OPTIONS, 'core_trace': True}) + identifier = d.trace.local.start()['id'] + sample = {'peer_id': 'peer_a', 'device_session': 'session_a', 'allocation_bps': 5000000, + 'encoder_bps': 500000, 'receiver_bps': 307644, 'source_age_ms': 5, + 'sdp': 'must not be recorded'} + body = {'id': identifier, 'events': [{'event': 'preview', 'sample': sample}]} + assert d.browser(body, local=True) + row = d.trace.local.snapshot()['frames'][-1] + assert row['event'] == 'browser_preview' and row['sample']['encoder_bps'] == 500000 + assert 'sdp' not in row['sample'] + before = d.trace.sequence + with pytest.raises(ValueError): + d.browser({**body, 'id': d.trace.id}) + assert d.trace.sequence == before + assert all(row['event'] != 'browser_preview' for row in d.desired()['core_events']) + for invalid in (True, float('nan'), float('inf'), -1, 10**1000, '500000'): + with pytest.raises(ValueError): + preview_sample({**sample, 'encoder_bps': invalid}) + d.trace.local.stop(identifier) + assert not d.browser(body, local=True) + + +def test_dev_ui_options_pair_local_capture_without_wan_trace(request): + from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS + control, client = request.getfixturevalue('fixture') + url = '/api/v1/fleet/vehicle/rover/diagnostics' + d = control.diagnostics('node', 'vehicle') + body = {'enabled': True, 'options': dict(LOCAL_OPTIONS), + 'local_options': {'enabled': True, 'preview': False}} + assert client.post(url, json=body).status_code == 409 + assert d.trace.local.id is None + d.supports_options = True + result = client.post(url, json=body) + assert result.status_code == 200 + identifier = result.json()['local_capture']['id'] + assert d.local_owner == identifier + assert not d.trace.local.preview + assert not control.view('node')['controlling'] + assert d.desired()['core_events'] == [] + assert d.browser({'id': identifier, 'events': [{'event': 'preview', 'sample': {}}]}, local=True) + assert not any(row['event'] == 'browser_preview' for row in d.trace.local.snapshot()['frames']) + assert client.post(url, json={'enabled': False}).status_code == 200 + assert not d.trace.local.active() + export = client.get(url + '/local/export', params={'capture_id': identifier}) + assert export.status_code == 200 + import json + rows = [json.loads(line) for line in export.text.splitlines()] + assert rows[0]['schema'] == 'missioncore.operator-capture/v1' + assert rows[0]['scope'] == 'operator_host_only' + assert rows[0]['id'] == identifier and rows[0]['active'] is False + context = next(row for row in rows if row.get('event') == 'local_capture_context') + assert context['board_capture_id'] == result.json()['id'] + assert client.get(url + '/local/export', params={'capture_id': 'f' * 32}).status_code == 409 + assert client.get(url + '/local/export', params={'capture_id': identifier}, + headers={'Origin': 'https://foreign.invalid'}).status_code == 403 + assert d.trace.local.id == identifier # Export does not clear evidence. + + +def test_invalid_ui_options_and_previous_capture_are_not_overwritten(): + from missioncore_plugin_sdk.diagnostic_options import LOCAL_OPTIONS + d = RoverDiagnostics(lambda: 10.) + d.supports_options = True + for invalid in ({'enabled': 1, 'preview': True}, {'enabled': True, 'preview': 1}, + {'enabled': True, 'preview': True, 'unknown': 1}): + with pytest.raises(ValueError): + d.set_enabled(True, dict(LOCAL_OPTIONS), invalid) + assert not d.enabled and d.trace.local.id is None + identifier = d.trace.local.start()['id'] + with pytest.raises(ValueError): + d.set_enabled(True, dict(LOCAL_OPTIONS), {'enabled': True, 'preview': True}) + assert not d.enabled and d.trace.local.id == identifier + d.trace.local.stop(identifier) + with pytest.raises(ValueError): + d.set_enabled(True, dict(LOCAL_OPTIONS), {'enabled': True, 'preview': True}) + assert not d.enabled and d.trace.local.id == identifier + d.set_enabled(True, dict(LOCAL_OPTIONS), + {'enabled': True, 'preview': True, 'previous_id': identifier}) + assert d.trace.local.id != identifier and d.trace.local.active() diff --git a/tests/fleet/test_rover_metadata.py b/tests/fleet/test_rover_metadata.py new file mode 100644 index 00000000..895f657b --- /dev/null +++ b/tests/fleet/test_rover_metadata.py @@ -0,0 +1,162 @@ +import copy + +import pytest + +from k1link.fleet.rover_control import RoverControl + + +def packet(hub, at=100, revision=1, details=True, **changes): + snapshot = { + "instance": "driver", + "state": "stopped", + "release_confirmed": None, + "control_active": False, + "session_id": None, + "devices": [ + { + "id": "motor", + "session_id": "attachment", + "age_ms": 25, + "values": {"erpm": 0, "motor_current_a": 0.2, "fault_code": 0}, + } + ], + } + snapshot.update(changes) + envelope = {"revision": revision} + if details: + envelope["details"] = { + "supported": True, + "control_modes": ["rpm", "duty"], + "profile": {"revision": 2, "bindings": {}}, + "devices": {"motor": {"uuid": "physical", "slot": "left.1", "label": "Left"}}, + } + return { + "relay_id": "a" * 32, + "rover": snapshot, + "rover_details_v1": envelope, + "sample_clock": {"instance": hub.clock_id, "monotonic_ms": at * 1000}, + } + + +def test_compact_metadata_preserves_every_live_value_age_and_release_truth(): + now = [100.0] + hub = RoverControl(lambda: now[0]) + body = packet(hub) + unchanged = copy.deepcopy(body) + hub.exchange("node", body) + assert body == unchanged + for release in (None, False, True): + now[0] += 0.1 + live = packet(hub, now[0] - 0.03, details=False, release_confirmed=release) + live["rover"]["devices"][0]["values"]["erpm"] = 123 + hub.exchange("node", live) + view = hub.view("node") + assert view["snapshot"]["release_confirmed"] is release + row = view["snapshot"]["devices"][0] + assert row["values"]["erpm"] == 123 and row["uuid"] == "physical" + assert row["session_id"] == "attachment" and 54 <= row["age_ms"] <= 56 + assert view["snapshot"]["profile"]["revision"] == 2 + assert not view["controlling"] + + +def test_metadata_reference_survives_delay_without_renewing_measurements(): + now = [100.0] + hub = RoverControl(lambda: now[0]) + hub.exchange("node", packet(hub, 99.2)) + now[0] = 101.21 + # A fresh sample asserts the unchanged metadata revision after a delayed + # preceding exchange. Labels/profile age must not reject fresh measurements. + hub.exchange("node", packet(hub, 101.2, details=False)) + assert hub.view("node")["fresh"] + assert hub.view("node")["snapshot"]["devices"][0]["uuid"] == "physical" + now[0] = 103.3 + hub.exchange("node", packet(hub, 101.3, details=False)) + assert not hub.view("node")["fresh"] + assert hub.boards["node"]["seen"] == 101.3 + assert not hub.view("node")["controlling"] + + +def test_late_full_metadata_does_not_rejuvenate_sample_or_lease(): + now = [103.0] + hub = RoverControl(lambda: now[0]) + hub.exchange("node", packet(hub, 100.0)) + assert not hub.view("node")["fresh"] + assert hub.boards["node"]["seen"] == 100.0 + with pytest.raises(ValueError, match="недоступен"): + hub.arm("node", {"standstill_confirmed": True, "current_a": 1, "max_erpm": 300}) + # Latest-only cache is scoped to this relay/driver/revision, not a time + # series. A reference can recover publication, but cannot create a lease. + hub.exchange("node", packet(hub, 102.9, details=False)) + assert hub.view("node")["fresh"] + assert not hub.view("node")["controlling"] + + +@pytest.mark.parametrize( + "change", [{"relay_id": "b" * 32}, {"revision": 2}, {"instance": "new-driver"}] +) +def test_cached_identity_cannot_cross_relay_driver_or_revision(change): + hub = RoverControl(lambda: 100.0) + hub.exchange("node", packet(hub, 99.9)) + value = packet(hub, details=False) + for k, v in change.items(): + if k == "revision": + value["rover_details_v1"][k] = v + elif k == "instance": + value["rover"][k] = v + else: + value[k] = v + with pytest.raises(ValueError): + hub.exchange("node", value) + assert hub.boards["node"]["seen"] == 99.9 + + +def test_metadata_revision_changes_immediately_and_old_packet_cannot_replace_it(): + hub = RoverControl(lambda: 100.0) + hub.exchange("node", packet(hub, 99.8)) + updated = packet(hub, 99.9, revision=2) + updated["rover_details_v1"]["details"]["profile"]["revision"] = 3 + hub.exchange("node", updated) + hub.exchange("node", packet(hub, 99.8)) + assert hub.view("node")["snapshot"]["profile"]["revision"] == 3 + invalid = copy.deepcopy(updated) + invalid["sample_clock"]["monotonic_ms"] = 100000 + invalid["rover_details_v1"]["details"]["profile"]["revision"] = 99 + with pytest.raises(ValueError): + hub.exchange("node", invalid) + + +@pytest.mark.parametrize( + "change", ["duplicate", "foreign", "static_override", "missing_session", "bad_revision"] +) +def test_invalid_compact_snapshot_never_publishes_or_creates_authority(change): + hub = RoverControl(lambda: 100.0) + hub.exchange("node", packet(hub, 99.9)) + value = packet(hub, details=False) + row = value["rover"]["devices"][0] + if change == "duplicate": + value["rover"]["devices"].append(copy.deepcopy(row)) + if change == "foreign": + row["id"] = "foreign" + if change == "static_override": + row["uuid"] = "wrong" + if change == "missing_session": + del row["session_id"] + if change == "bad_revision": + value["rover_details_v1"]["revision"] = True + with pytest.raises(ValueError): + hub.exchange("node", value) + assert hub.boards["node"]["seen"] == 99.9 + assert not hub.view("node")["controlling"] + + +def test_legacy_full_snapshot_remains_compatible_and_invalidates_metadata_cache(): + hub = RoverControl(lambda: 100.0) + hub.exchange("node", packet(hub, 99.9)) + legacy = { + "relay_id": "a" * 32, + "rover": {"instance": "driver", "supported": True, "state": "stopped", "devices": []}, + } + hub.exchange("node", legacy) + assert hub.view("node")["snapshot"] == legacy["rover"] + with pytest.raises(ValueError): + hub.exchange("node", packet(hub, details=False)) diff --git a/tests/fleet/test_rover_observation_evidence.py b/tests/fleet/test_rover_observation_evidence.py new file mode 100644 index 00000000..1892360f --- /dev/null +++ b/tests/fleet/test_rover_observation_evidence.py @@ -0,0 +1,46 @@ +from datetime import UTC, datetime, timedelta + +from k1link.fleet.rover_control import RoverControl +from k1link.fleet.rover_observation_evidence import ObservationEvidence + + +def test_receipt_time_distinguishes_missing_packets_from_old_source_samples(): + now = [100.] + hub = RoverControl(lambda: now[0]) + packet = {"relay_id": "a"*32, "rover": {"supported": True, "devices": []}, + "sample_clock": {"instance": hub.clock_id, "monotonic_ms": 98000}} + hub.exchange("node", packet) + assert not hub.view("node")["fresh"] + value = hub.observation("node") + assert value["latest"]["received_mono_ms"] == 100000 + assert value["latest"]["sample_age_at_receipt_ms"] == 2000 + now[0] = 100.5 + packet["sample_clock"]["monotonic_ms"] = 100400 + hub.exchange("node", packet) + assert hub.view("node")["fresh"] + now[0] = 102. + assert not hub.view("node")["fresh"] + before = hub.boards["node"]["watch"] + value = hub.observation("node", "operator_socket_closed") + assert hub.boards["node"]["watch"] == before + assert value["receipts"] == 2 + assert value["latest"]["received_mono_ms"] == 100500 + assert [e["event"] for e in value["events"]] == [ + "first_receipt", "stale", "fresh", "stale", "operator_socket_closed"] + assert hub.boards["node"]["session"] is None + assert not hub.diagnostics("node", "fixture").enabled + + +def test_transition_memory_is_bounded_and_daily_without_raw_samples(): + day = [datetime(2026, 10, 28, tzinfo=UTC)] + evidence = ObservationEvidence(lambda: 100., lambda: day[0]) + for n in range(200): + evidence.view(bool(n % 2)) + assert len(evidence.snapshot()["events"]) == 64 + evidence.receive(99., False, 500) + assert evidence.snapshot()["ignored_older_receipts"] == 1 + assert evidence.snapshot()["latest"]["sampled_devices"] == 128 + day[0] += timedelta(days=1) + assert evidence.snapshot()["events"] == [] + assert evidence.snapshot()["latest"] is None + assert evidence.snapshot()["receipts"] == 0 diff --git a/tests/fleet/test_rover_python_interop.py b/tests/fleet/test_rover_python_interop.py new file mode 100644 index 00000000..17189906 --- /dev/null +++ b/tests/fleet/test_rover_python_interop.py @@ -0,0 +1,112 @@ +"""Opt-in ordinary real Python/Go interoperability; no load or physical board.""" +import json +import os +import subprocess +import threading +import time +from http.server import ThreadingHTTPServer +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from test_pairing import cert, create, setup # noqa: F401 + +from k1link.fleet.rover_datagram import RoverDatagramServer +from k1link.fleet.transport import NodeChannelHandler +from k1link.fleet.trust import SCHEMA, pem + +pytestmark = pytest.mark.skipif( + not os.environ.get("MISSION_CORE_GO"), reason="opt-in existing Go compiler") +ROOT = Path(__file__).resolve().parents[2] + + +def test_paired_python_core_and_go_node_neutral_intent_then_revocation(setup, tmp_path): # noqa: F811 + fleet, _, key, _ = setup + public, _ = create(setup) + fleet.advance(public["id"]) + row = fleet.find(public["id"]) + base = {"schema": SCHEMA, "node_id": row["node_id"], + "binding_id": row["binding"]["binding_id"], "relay_id": "a" * 32} + status, _ = fleet.receive(cert(row), "/v1/node/rover", {**base, "rover": { + "instance": "synthetic", "state": "observing", "supported": True}}) + assert status == 200 + fleet.rover_control.view(row["node_id"]) + context = fleet.trust.server_context("192.168.20.5") + + class Server(ThreadingHTTPServer): + daemon_threads = True + + def get_request(self): + sock, address = super().get_request() + sock.settimeout(3) + return context.wrap_socket(sock, server_side=True), address + + # Only the private-address binding is substituted with loopback. mTLS, + # certificate/binding checks, HTTP handler, control and UDP are production. + server = Server(("127.0.0.1", 0), NodeChannelHandler) + server.address, server.registry = "192.168.20.5", fleet + server.datagrams = RoverDatagramServer("127.0.0.1", fleet, port=0) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + config = {"Endpoint": "https://127.0.0.1:" + str(server.server_port), + "CA": pem(fleet.trust.ca), "Certificate": row["binding"]["client_pem"], + "Key": key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()).decode(), + "Base": base, "Directory": str(tmp_path)} + path = tmp_path / "synthetic-config.json" + path.write_text(json.dumps(config)) + path.chmod(0o600) + overlay = tmp_path / "overlay.json" + overlay.write_text(json.dumps({"Replace": { + str(ROOT / "apps/node-agent/internal/node/worker_rover_python_interop_test.go"): + str(ROOT / "tests/qualification/rover_python_interop_test.go")}})) + env = {**os.environ, "GOCACHE": str(tmp_path / "cache"), "GOTMPDIR": str(tmp_path), + "GOPROXY": "off", "GOTOOLCHAIN": "local", "CGO_ENABLED": "0", "GOMAXPROCS": "2", + "GOMEMLIMIT": "512MiB", "MISSION_CORE_PYTHON_INTEROP": str(path)} + proc = None + try: + binary = tmp_path / "interop.test" + subprocess.run([os.environ["MISSION_CORE_GO"], "test", "-c", "-p", "1", + "-overlay="+str(overlay), "-o", str(binary), "./internal/node"], + cwd=ROOT/"apps/node-agent", env=env, capture_output=True, + check=True, timeout=90) + # Compile before the fresh test observation; compilation never renews it. + fleet.receive(cert(row), "/v1/node/rover", {**base, "rover": { + "instance": "synthetic", "state": "observing", "supported": True}}) + fleet.rover_control.view(row["node_id"]) + proc = subprocess.Popen([str(binary), "-test.run=^TestPythonDatagramInterop$", "-test.v"], + env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True) + + def wait(name): + deadline = time.monotonic() + 2 + while (not (tmp_path/name).exists() + and proc.poll() is None and time.monotonic() < deadline): + time.sleep(.005) + assert (tmp_path/name).exists(), ( + name, proc.communicate(timeout=2)[0] if proc.poll() is not None else "no marker") + + wait("ready") + session = fleet.rover_control.arm(row["node_id"], { + "standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})["session_id"] + for sequence in range(1, 4): + fleet.rover_control.command(row["node_id"], {"session_id": session, + "sequence": sequence, "left": 0, "right": 0, "stop": False}) + wait("seen-" + str(sequence)) + row["enrollment"] = "revoked" + fleet.save(row) + output, _ = proc.communicate(timeout=3) + assert proc.returncode == 0, output + assert '"retired":true' in output + print(output) + assert not fleet.rover_control.view(row["node_id"])["controlling"] + finally: + if proc is not None and proc.poll() is None: + proc.kill() + proc.wait(timeout=2) + server.shutdown() + server.server_close() + server.datagrams.close() + worker.join(timeout=2) + assert not worker.is_alive() and not server.datagrams.thread.is_alive() diff --git a/tests/fleet/test_rover_runtime_diagnostics.py b/tests/fleet/test_rover_runtime_diagnostics.py new file mode 100644 index 00000000..a59e6a69 --- /dev/null +++ b/tests/fleet/test_rover_runtime_diagnostics.py @@ -0,0 +1,39 @@ +import threading + +from test_rover_socket import fixture as fixture + + +def test_runtime_snapshot_is_local_read_only_and_excludes_frame_values(fixture): + control, client = fixture + secret_value = "private-value-never-in-thread-snapshot" + url = "/api/v1/fleet/vehicle/rover/diagnostics/runtime" + result = client.get(url) + assert result.status_code == 200 + assert secret_value not in result.text + assert "no-store" in result.headers["cache-control"] + data = result.json() + assert data["schema"] == "missioncore.runtime-threads/v1" + assert 0 < len(data["threads"]) <= 128 + assert all(len(row["stack"]) <= 24 for row in data["threads"]) + assert all(set(frame) == {"file", "function", "line"} + for row in data["threads"] for frame in row["stack"]) + assert not control.view("node")["controlling"] + assert control.stream("node", "a"*32)["command"] is None + assert not client.get(url.removesuffix("/runtime")).json()["active"] + assert client.get(url, headers={"Origin": "https://foreign.invalid"}).status_code == 403 + assert client.get(url.replace("vehicle/", "unknown/")).status_code == 409 + + +def test_native_id_identifies_a_blocked_thread_without_inspecting_its_locals(): + from k1link.web.rover_runtime_diagnostics import snapshot + stop = threading.Event() + worker = threading.Thread(target=stop.wait, name="runtime-diagnostic-fixture") + worker.start() + try: + row = next(row for row in snapshot()["threads"] if row["native_id"] == worker.native_id) + assert row["name"] == worker.name + assert row["stack"][0]["function"] == "wait" + finally: + stop.set() + worker.join(1) + assert not worker.is_alive() diff --git a/tests/fleet/test_rover_sample_age.py b/tests/fleet/test_rover_sample_age.py new file mode 100644 index 00000000..ddbf4341 --- /dev/null +++ b/tests/fleet/test_rover_sample_age.py @@ -0,0 +1,58 @@ +import pytest +from k1link.fleet.rover_control import RoverControl + + +def packet(hub, observed, **snapshot): + return {"relay_id": "a"*32, "sample_clock": {"instance": hub.clock_id, "monotonic_ms": observed*1000}, + "rover": {"instance": "driver", "supported": True, "state": "observing", **snapshot}} + + +def test_network_delay_counts_in_sample_age_and_cannot_refresh_old_data(): + now = [100.] + hub = RoverControl(lambda: now[0]) + hub.exchange("node", packet(hub, 99.6, devices=[{"age_ms": 50}])) + view = hub.view("node") + assert view["fresh"] + assert 449 <= view["snapshot"]["devices"][0]["age_ms"] <= 451 + now[0] += .61 + assert not hub.view("node")["fresh"] + hub.exchange("node", packet(hub, 99.6)) + assert not hub.view("node")["fresh"] + with pytest.raises(ValueError): + hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000}) + + +def test_late_old_relay_cannot_replace_newer_snapshot_or_session(): + hub = RoverControl(lambda: 100.) + hub.exchange("node", packet(hub, 99.9, generation=2)) + identifier = hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000})["session_id"] + deadline = hub.boards["node"]["session"]["until"] + old = packet(hub, 99.7, generation=1, instance="old-driver") + old["relay_id"] = "b"*32 + hub.exchange("node", old) + assert hub.view("node")["snapshot"]["generation"] == 2 + assert hub.boards["node"]["session"]["id"] == identifier + assert hub.boards["node"]["session"]["until"] == deadline + + +@pytest.mark.parametrize("clock", [None, {}, {"instance": "old", "monotonic_ms": 99000}, + {"instance": "CURRENT", "monotonic_ms": True}, {"instance": "CURRENT", "monotonic_ms": float("nan")}, + {"instance": "CURRENT", "monotonic_ms": 100001}, {"instance": "CURRENT", "monotonic_ms": -1}]) +def test_bad_observation_clock_never_updates_state(clock): + hub = RoverControl(lambda: 100.) + body = packet(hub, 99.9) + if clock is None:clock = {"instance": hub.clock_id, "monotonic_ms": float("inf")} + if clock.get("instance") == "CURRENT":clock = {**clock, "instance": hub.clock_id} + body["sample_clock"] = clock + with pytest.raises(ValueError):hub.exchange("node", body) + assert not hub.boards + + +def test_source_timestamp_does_not_renew_motion_lease(): + now=[100.];hub=RoverControl(lambda:now[0]) + hub.exchange("node", packet(hub,99.9)) + hub.arm("node", {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000}) + now[0]=100.401 + hub.exchange("node", packet(hub,100.3)) + assert hub.view("node")["fresh"] + assert not hub.view("node")["controlling"] diff --git a/tests/fleet/test_rover_socket.py b/tests/fleet/test_rover_socket.py new file mode 100644 index 00000000..c6104c0d --- /dev/null +++ b/tests/fleet/test_rover_socket.py @@ -0,0 +1,166 @@ +import time +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + +from k1link.fleet.rover_channel import RoverChannel +from k1link.fleet.rover_control import RoverControl +from k1link.web.rover_api import router + + +@pytest.fixture +def fixture(): + control = RoverControl() + control.exchange("node", {"relay_id": "a"*32, "rover": { + "supported": True, "instance": "fixture", "state": "observing"}}) + channel = RoverChannel(control) + channel.vehicles["vehicle"] = {"node_id": "node", "enrollment": "paired"} + app = FastAPI() + app.state.fleet = SimpleNamespace(rover_channel=channel) + app.include_router(router) + with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client: + yield control, client + + +def connect(client, origin="http://127.0.0.1:8000"): + return client.websocket_connect("ws://127.0.0.1:8000/api/v1/fleet/vehicle/rover-channel", headers={"Origin": origin}) + + +def reply(socket): + while True: + value = socket.receive_json() + if value["type"] == "reply": + return value + + +def arm(socket, clock, offset=350): + socket.send_json({"id": 1, "action": "arm", "expires_ms": clock+offset, + "body": {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000}}) + return reply(socket) + + +def test_socket_observation_and_commands_share_existing_authority(fixture): + control, client = fixture + with connect(client) as socket: + first = socket.receive_json() + assert first["value"]["fresh"] + acknowledged = arm(socket, first["clock_ms"]) + assert acknowledged["state"]["controlling"] + identifier = acknowledged["value"]["session_id"] + socket.send_json({"id": 2, "action": "command", "expires_ms": first["clock_ms"]+300, + "body": {"session_id": identifier, "sequence": 1, "left": 0, + "right": 0, "stop": False}}) + assert reply(socket)["value"]["accepted_sequence"] == 1 + command = control.stream("node", "a"*32)["command"] + assert command["left"] == 0 + assert command["expires_mono_ms"] == pytest.approx(first["clock_ms"]+300) + assert not control.view("node")["controlling"] + + +@pytest.mark.parametrize("offset", [-1, 10000]) +def test_queued_or_overlong_request_cannot_create_a_lease(fixture, offset): + control, client = fixture + with connect(client) as socket: + first = socket.receive_json() + assert arm(socket, first["clock_ms"], offset)["status"] == 408 + assert not control.view("node")["controlling"] + + +def test_observer_disconnect_does_not_retire_other_operator(fixture): + control, client = fixture + with connect(client) as owner: + first = owner.receive_json() + identifier = arm(owner, first["clock_ms"])["value"]["session_id"] + with connect(client) as observer: + observed = observer.receive_json() + observer.send_json({"id": 2, "action": "command", "expires_ms": observed["clock_ms"]+300, + "body": {"session_id": identifier, "sequence": 1, "left": 0, + "right": 0, "stop": True}}) + assert reply(observer)["status"] == 409 + assert control.view("node")["controlling"] + control.disconnect("node", "other-session") + assert control.stream("node", "a"*32)["command"]["id"] == identifier + + +def test_state_push_cannot_renew_motion_lease(fixture): + control, client = fixture + with connect(client) as socket: + first = socket.receive_json() + arm(socket, first["clock_ms"]) + time.sleep(.42) + assert not control.view("node")["controlling"] + + +@pytest.mark.parametrize("origin", ["https://example.com", "null", "http://localhost:8000"]) +def test_cross_origin_websocket_is_rejected_before_accept(fixture, origin): + _, client = fixture + with pytest.raises(WebSocketDisconnect) as error: + with connect(client, origin): + pass + assert error.value.code == 1008 + + +def test_malformed_frame_cannot_invoke_control(fixture): + control, client = fixture + with connect(client) as socket: + socket.receive_json() + socket.send_json({"id": 1, "action": "arm", "body": {}, "expires_ms": "forever"}) + with pytest.raises(WebSocketDisconnect): + reply(socket) + assert not control.view("node")["controlling"] + + +def test_live_owner_socket_holds_neutral_while_browser_js_sends_nothing(fixture): + control, client = fixture + with connect(client) as socket: + first = socket.receive_json() + identifier = arm(socket, first['clock_ms'])['value']['session_id'] + socket.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350, + 'body':{'session_id':identifier,'sequence':1}}) + assert reply(socket)['value']['accepted_sequence'] == 1 + sequences=[] + for _ in range(60): + # Synthetic board feedback stays fresh while browser JS is silent. + control.exchange('node', {'relay_id':'a'*32,'rover':{ + 'instance':'fixture','supported':True,'state':'ready','session_id':identifier}}) + time.sleep(.1) + frame=control.stream('node','a'*32)['command'] + assert frame and frame['id']==identifier + assert frame['left']==frame['right']==0 + sequences.append(frame['sequence']) + assert len(set(sequences))>=40 + socket.send_json({'id':3,'action':'command','expires_ms':time.monotonic()*1000+350, + 'body':{'session_id':identifier,'sequence':2,'left':.5,'right':.5,'stop':False}}) + assert reply(socket)['value']['accepted_sequence']==2 + frame=control.stream('node','a'*32)['command'] + assert frame['left']==.5 and frame['sequence']>max(sequences) + time.sleep(.42) + assert not control.view('node')['controlling'], 'native loop must not renew resumed movement' + assert not control.view('node')['controlling'] + + +def test_observer_cannot_hold_and_owner_socket_close_retires_neutral(fixture): + control, client = fixture + with connect(client) as owner: + first=owner.receive_json();identifier=arm(owner, first['clock_ms'])['value']['session_id'] + with connect(client) as observer: + observer.receive_json() + observer.send_json({'id':1,'action':'hold','expires_ms':time.monotonic()*1000+350, + 'body':{'session_id':identifier,'sequence':1}}) + assert reply(observer)['status']==409 + owner.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350, + 'body':{'session_id':identifier,'sequence':1}}) + assert reply(owner)['value']['accepted_sequence']==1 + assert not control.view('node')['controlling'] + assert not control.maintain_neutral('node',identifier) + + +def test_browser_cannot_invoke_native_maintenance_directly(fixture): + _, client=fixture + with connect(client) as socket: + socket.receive_json() + socket.send_json({'id':1,'action':'maintain_neutral','expires_ms':time.monotonic()*1000+350,'body':{}}) + with pytest.raises(WebSocketDisconnect):reply(socket) diff --git a/tests/fleet/test_rover_stop_evidence.py b/tests/fleet/test_rover_stop_evidence.py new file mode 100644 index 00000000..06ca07b5 --- /dev/null +++ b/tests/fleet/test_rover_stop_evidence.py @@ -0,0 +1,147 @@ +"""Latest withdrawal survives DEV being off without adding motion authority.""" +from datetime import UTC, datetime, timedelta +from unittest.mock import patch + +import pytest +from test_rover_control import arm, cmd, exchange +from test_rover_control import hub as hub +from test_rover_socket import fixture as fixture + +from k1link.fleet.rover_stop_evidence import CoreStopEvidence + + +def latest(h): + return h.diagnostics('node', 'vehicle').view()['core_stop_v1'] + + +@pytest.mark.parametrize('trigger,reason', [ + ('deadline', 'input_deadline_expired'), + ('disconnect', 'operator_socket_closed'), + ('stop', 'operator_stop'), + ('telemetry', 'telemetry_stale'), + ('restart', 'driver_restarted'), + ('relay', 'relay_changed'), + ('stopped', 'driver_terminal'), + ('fault', 'driver_terminal'), + ('receiver', 'driver_terminal'), +]) +def test_reason_is_retained_with_all_recorders_off(hub, trigger, reason): + h, now = hub + diagnostics = h.diagnostics('node', 'vehicle') + assert not diagnostics.enabled and not diagnostics.trace.recording() + assert latest(h) is None + identifier = arm(h) + h.command('node', cmd(identifier)) + if trigger == 'deadline': + now[0] += .401 + h.stream('node', 'a'*32) + elif trigger == 'disconnect': + h.disconnect('node', identifier) + elif trigger == 'stop': + h.command('node', cmd(identifier, 2, stop=True)) + elif trigger == 'telemetry': + for sequence in range(2, 14): + now[0] += .09 + h.command('node', cmd(identifier, sequence)) + h.stream('node', 'a'*32) + elif trigger == 'restart': + exchange(h, instance='new-driver') + elif trigger == 'relay': + h.exchange('node', {'relay_id': 'b'*32, 'rover': {'instance': 'driver'}}) + else: + exchange(h, state=trigger, session_id=identifier) + record = latest(h) + assert record['reason'] == reason + assert record['session_id'] == identifier + assert record['core_clock_instance'] == h.clock_id + assert record['monotonic_ms'] == now[0]*1000 + assert record['remaining_ms'] <= 400 + 1e-7 + assert not h.view('node')['controlling'] + assert diagnostics.desired() is None, 'never transmit this record on the board lane' + # Follow-up disconnect or status polling cannot replace the first withdrawal. + h.disconnect('node', identifier) + h.stream('node', 'a'*32) + assert latest(h) == record + record['reason'] = 'mutated-client-copy' + assert latest(h)['reason'] == reason + with pytest.raises(ValueError): + h.command('node', cmd(identifier, 100)) + + +@pytest.mark.parametrize('cause,reason', [ + ('stale', 'telemetry_stale'), ('unsupported', 'driver_unavailable'), +]) +def test_neutral_maintenance_records_its_existing_stop_conditions(hub, cause, reason): + h, now = hub + identifier = arm(h) + h.hold('node', {'session_id': identifier, 'sequence': 1}) + if cause == 'unsupported': + exchange(h, supported=False) + else: + # Current zero commands with old return telemetry isolate this guard. + for sequence in range(2, 14): + now[0] += .09 + h.hold('node', {'session_id': identifier, 'sequence': sequence}) + assert not h.maintain_neutral('node', identifier) + assert latest(h)['reason'] == reason + assert latest(h)['neutral_hold'] is True + + +def test_foreign_disconnect_and_dev_toggle_do_not_erase_latest(hub): + h, _ = hub + identifier = arm(h) + h.disconnect('node', 'another-owner') + assert latest(h) is None + h.disconnect('node', identifier) + recorded = latest(h) + diagnostics = h.diagnostics('node', 'vehicle') + diagnostics.set_enabled(True) + diagnostics.set_enabled(False) + assert latest(h) == recorded + h.forget('node') + assert latest(h) is None + + +def test_withdrawal_does_not_acquire_optional_export_or_diagnostics_lock(hub): + h, _ = hub + identifier = arm(h) + diagnostics = h.diagnostics('node', 'vehicle') + class Forbidden: + def __enter__(self): + raise AssertionError('optional diagnostics lock in withdrawal') + def __exit__(self, *args): + pass + with patch.object(diagnostics, 'lock', Forbidden()): + h.disconnect('node', identifier) + assert latest(h)['reason'] == 'operator_socket_closed' + + +@pytest.mark.parametrize('advance_seconds', [2, 86400]) +def test_latest_is_bounded_expires_and_resets_each_utc_day(advance_seconds): + now, wall = [10.], [datetime(2026, 10, 26, 23, 59, 59, tzinfo=UTC)] + evidence = CoreStopEvidence(lambda: now[0], lambda: wall[0]) + session = dict(id='a'*32, sequence=7, operator_sequence=3, neutral_hold=True, until=10.4) + evidence.record('telemetry_stale', session, core_instance='b'*32, + telemetry_age_ms=1234, driver_state={'unexpected': 'x'*100000}) + record = evidence.snapshot() + assert record['driver_state'] is None + assert record['remaining_ms'] == pytest.approx(400) + now[0] += advance_seconds + if advance_seconds == 2: + wall[0] += timedelta(seconds=2) + assert evidence.snapshot() is None + # Expiration clears storage, even if the wall clock subsequently goes back. + wall[0] -= timedelta(days=1) + assert evidence.snapshot() is None + + +def test_local_api_exposes_reason_without_dev_and_preserves_origin_boundary(fixture): + control, client = fixture + url = '/api/v1/fleet/vehicle/rover/diagnostics' + assert client.get(url).json()['core_stop_v1'] is None + identifier = arm(control) + control.disconnect('node', identifier) + result = client.get(url) + assert result.status_code == 200 and not result.json()['active'] + assert result.json()['core_stop_v1']['reason'] == 'operator_socket_closed' + assert client.get(url, headers={'Origin': 'https://foreign.invalid'}).status_code == 403 diff --git a/tests/fleet/test_rover_stream_timing.py b/tests/fleet/test_rover_stream_timing.py new file mode 100644 index 00000000..0ed2494e --- /dev/null +++ b/tests/fleet/test_rover_stream_timing.py @@ -0,0 +1,85 @@ +"""Distinguish Core/socket stalls without changing bytes or socket failures.""" +import io + +import pytest + +from k1link.fleet.rover_control import RoverControl +from k1link.fleet.rover_stream_timing import RoverStreamTiming + + +def recorder(): + now = [10.] + control = RoverControl(clock=lambda: now[0]) + diagnostics = control.diagnostics("node", "synthetic") + return now, diagnostics, control.stream_trace("node") + + +def test_disabled_capture_does_not_record_or_sample_clock(): + _, diagnostics, trace = recorder() + def forbidden_clock(): + raise AssertionError("Disabled capture sampled clock") + timing = RoverStreamTiming(trace, clock=forbidden_clock) + writer = io.BytesIO() + timing.write(writer, b"frame\n", {}, dispatch_ms=2, wait_ms=50) + assert writer.getvalue() == b"frame\n" + assert diagnostics.trace.sequence == 0 + + +def test_socket_write_stall_is_distinct_from_dispatch_and_wait(): + now, diagnostics, trace = recorder() + diagnostics.set_enabled(True) + timing = RoverStreamTiming(trace, clock=lambda: now[0]) + writes = [] + class Writer: + def write(self, raw): + writes.append(raw) + now[0] += .4 + data = {"command": {"id": "synthetic", "sequence": 8}, + "control_clock": {"monotonic_ms": 9999}} + timing.write(Writer(), b"one\n", data, dispatch_ms=3, wait_ms=50) + now[0] += .05 + timing.write(Writer(), b"two\n", data, dispatch_ms=1, wait_ms=50) + rows = [r for r in trace.snapshot()["frames"] if r["event"] == "command_stream_frame"] + assert writes == [b"one\n", b"two\n"] + assert rows[0]["gap_ms"] is None + assert rows[0]["write_ms"] == pytest.approx(400) + assert rows[0]["dispatch_ms"] == 3 + assert rows[1]["gap_ms"] == pytest.approx(450) + assert rows[1]["frame_index"] == 2 + assert rows[1]["sequence"] == 8 + assert rows[1]["frame_clock_ms"] == 9999 + assert rows[0]["stream_id"] == rows[1]["stream_id"] + + +def test_write_failure_is_not_retried_and_private_error_not_recorded(): + now, diagnostics, trace = recorder() + diagnostics.set_enabled(True) + failure = BrokenPipeError("private endpoint") + class Writer: + calls = 0 + def write(self, _): + self.calls += 1 + now[0] += .2 + raise failure + writer = Writer() + with pytest.raises(BrokenPipeError) as caught: + RoverStreamTiming(trace, clock=lambda: now[0]).write( + writer, b"x\n", {}, dispatch_ms=0, wait_ms=0) + assert caught.value is failure and writer.calls == 1 + row = trace.snapshot()["frames"][-1] + assert row["outcome"] == "write_error" + assert row["write_ms"] == pytest.approx(200) + assert "private" not in str(row) + + +def test_evidence_failure_cannot_replace_socket_failure(): + class Trace: + id = "capture" + def active(self): return True + def add(self, *_args, **_kwargs): raise RuntimeError("recorder failure") + original = BrokenPipeError("socket failure") + class Writer: + def write(self, _): raise original + with pytest.raises(BrokenPipeError) as caught: + RoverStreamTiming(Trace()).write(Writer(), b"x\n", {}, dispatch_ms=0, wait_ms=0) + assert caught.value is original diff --git a/tests/fleet/test_rover_stream_transport.py b/tests/fleet/test_rover_stream_transport.py index 56e23a6b..b4f5a37c 100644 --- a/tests/fleet/test_rover_stream_transport.py +++ b/tests/fleet/test_rover_stream_transport.py @@ -28,7 +28,8 @@ def test_stream_rechecks_binding_and_closes_when_revoked(): server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) server.address = "127.0.0.1" server.registry = SimpleNamespace(receive=receive, stop=threading.Event(), - rover_control=SimpleNamespace(wait_for_intent=lambda *_: time.sleep(.01))) + rover_control=SimpleNamespace(wait_for_intent=lambda *_: time.sleep(.01), + stream_trace=lambda _: None)) worker = threading.Thread(target=server.serve_forever, daemon=True) worker.start() client = http.client.HTTPConnection(*server.server_address, timeout=2) diff --git a/tests/fleet/test_runtime_http_timing.py b/tests/fleet/test_runtime_http_timing.py new file mode 100644 index 00000000..15d109ef --- /dev/null +++ b/tests/fleet/test_runtime_http_timing.py @@ -0,0 +1,80 @@ +import asyncio +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from starlette.responses import JSONResponse +from starlette.testclient import TestClient + +from k1link.web.response_compression import ResponseCompressionMiddleware +from k1link.web.runtime_http_timing import HttpTimingWindow, RuntimeHttpTimingMiddleware + + +def test_metadata_retains_template_not_path_query_headers_or_body(): + window = HttpTimingWindow() + app = FastAPI() + app.add_middleware(ResponseCompressionMiddleware) + app.add_middleware(RuntimeHttpTimingMiddleware, window=window) + + @app.post("/api/items/{item_id}") + def body(item_id: str): + return JSONResponse({"value": item_id * 300}) + + with TestClient(app) as client: + result = client.post("/api/items/private-path?key=private-query", + content=b"private-body", headers={"Authorization": "private-header"}) + assert result.status_code == 200 + assert result.json()["value"] == "private-path" * 300 + assert result.headers["content-encoding"] == "gzip" + row = window.snapshot()[-1] + assert row["route"] == "/api/items/{item_id}" + assert row["bytes"] == int(result.headers["content-length"]) + assert 0 <= row["response_start_ms"] <= row["duration_ms"] + assert row["complete"] + assert "private" not in str(window.snapshot()) + client.get("/unknown/private-token") + assert window.snapshot()[-1]["route"] == "" + + +def test_ram_window_is_bounded_expires_and_does_not_expose_mutable_rows(): + now = [0.0] + window = HttpTimingWindow(lambda: now[0]) + for i in range(300): + window.add({"ended_mono_ms": i, "bytes": i}) + assert len(window.snapshot()) == 256 + rows = window.snapshot() + rows[0]["bytes"] = -1 + assert window.snapshot()[0]["bytes"] == 44 + now[0] = 31 + assert window.snapshot() == [] + assert not window.rows + + +def test_stream_failure_and_websocket_passthrough_preserve_behavior(): + window = HttpTimingWindow() + sent = [] + + async def app(scope, receive, send): + if scope["type"] == "websocket": + await send({"type": "websocket.close"}) + return + scope["route"] = SimpleNamespace(path="/api/stream") + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"abc", "more_body": True}) + raise RuntimeError("private-failure") + + async def sink(message): + sent.append(message) + + async def run(): + middleware = RuntimeHttpTimingMiddleware(app, window=window) + with pytest.raises(RuntimeError, match="private-failure"): + await middleware({"type": "http", "method": "GET"}, None, sink) + row = window.snapshot()[-1] + assert not row["complete"] and row["bytes"] == 3 + assert "private" not in str(row) + await middleware({"type": "websocket"}, None, sink) + assert len(window.snapshot()) == 1 + assert sent[-1] == {"type": "websocket.close"} + + asyncio.run(run()) diff --git a/tests/fleet/test_sensor_transient.py b/tests/fleet/test_sensor_transient.py new file mode 100644 index 00000000..c403c659 --- /dev/null +++ b/tests/fleet/test_sensor_transient.py @@ -0,0 +1,68 @@ +import copy +import json + +from k1link.fleet.sensor_transient import SensorTransient + + +def test_queued_and_completed_payloads_are_ram_only_and_restart_never_requeues(): + cache = SensorTransient() + row = { + "id": "vehicle", + "sensor_commands": { + "op": { + "command": { + "operation_id": "op", + "action_id": "vesc.qml.chunk", + "parameters": {"data": "PRIVATE_SOURCE"}, + }, + "state": "queued", + "updated_at": 1, + } + }, + } + persisted = cache.persist(row) + assert "PRIVATE_SOURCE" not in json.dumps(persisted) + assert persisted["sensor_commands"]["op"]["state"] == "unknown" + assert cache.hydrate(copy.deepcopy(persisted)) == row + assert SensorTransient().hydrate(copy.deepcopy(persisted)) == persisted + row["sensor_commands"]["op"]["state"] = "complete" + row["sensor_commands"]["op"]["result"] = {"rows": "PRIVATE_SAMPLE", "png": "PRIVATE_FRAME"} + persisted = cache.persist(row) + assert "PRIVATE_" not in json.dumps(persisted) + assert cache.hydrate(copy.deepcopy(persisted)) == row + + +def test_expiry_daily_reset_and_budget_are_bounded_without_touching_durable_actions(): + clock = [0] + day = [1] + cache = SensorTransient(clock=lambda: clock[0], day=lambda: day[0]) + row = { + "id": "vehicle", + "sensor_commands": { + "normal": {"command": {"action_id": "vesc.configuration.apply"}, "state": "complete"} + }, + } + assert cache.persist(row) == row + for n in range(70): + row = { + "id": "vehicle", + "sensor_commands": { + str(n): { + "command": {"action_id": "vesc.samples.read", "parameters": {}}, + "state": "complete", + "result": {"rows": "x" * 150000}, + "updated_at": 1, + } + }, + } + saved = cache.persist(row) + assert ( + len(cache.entries) <= 64 and sum(len(v[2]) for v in cache.entries.values()) <= 8 * 1024**2 + ) + clock[0] = 301 + assert cache.hydrate(copy.deepcopy(saved)) == saved and not cache.entries + clock[0] = 400 + cache.persist(row) + day[0] = 2 + cache.prune() + assert not cache.entries diff --git a/tests/qualification/link_budget_load_test.go b/tests/qualification/link_budget_load_test.go new file mode 100644 index 00000000..aa282862 --- /dev/null +++ b/tests/qualification/link_budget_load_test.go @@ -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()) +} diff --git a/tests/qualification/rover_connect_test.go b/tests/qualification/rover_connect_test.go new file mode 100644 index 00000000..d361bb62 --- /dev/null +++ b/tests/qualification/rover_connect_test.go @@ -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()) +} diff --git a/tests/qualification/rover_contention_test.go b/tests/qualification/rover_contention_test.go new file mode 100644 index 00000000..89cb17b9 --- /dev/null +++ b/tests/qualification/rover_contention_test.go @@ -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)) +} diff --git a/tests/qualification/rover_datagram_test.go b/tests/qualification/rover_datagram_test.go new file mode 100644 index 00000000..87cc5b0b --- /dev/null +++ b/tests/qualification/rover_datagram_test.go @@ -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 +} diff --git a/tests/qualification/rover_python_interop_test.go b/tests/qualification/rover_python_interop_test.go new file mode 100644 index 00000000..efdac73c --- /dev/null +++ b/tests/qualification/rover_python_interop_test.go @@ -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") +} diff --git a/tests/qualification/rover_transport_test.go b/tests/qualification/rover_transport_test.go new file mode 100644 index 00000000..c2fecac3 --- /dev/null +++ b/tests/qualification/rover_transport_test.go @@ -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 +}