r3_safety_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package device_test
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "google.golang.org/protobuf/types/known/timestamppb"
  7. "hth/internal/backend"
  8. "hth/internal/config"
  9. "hth/internal/device"
  10. hthv1 "hth/internal/gen/hth/api/v1"
  11. "hth/internal/ids"
  12. "hth/internal/profile"
  13. "hth/internal/testutil"
  14. )
  15. func TestStartupSuppressesGetTemperature(t *testing.T) {
  16. m := backend.NewMock(1, false)
  17. m.StartupDelay = 11 * time.Second
  18. d := testDevNoWait(t, m)
  19. deadline := time.Now().Add(10 * time.Second)
  20. for time.Now().Before(deadline) {
  21. if m.TempGetCount() != 0 {
  22. t.Fatalf("GET_TEMPERATURE sent during startup: %d", m.TempGetCount())
  23. }
  24. if m.MotorGetCount() == 0 {
  25. time.Sleep(20 * time.Millisecond)
  26. continue
  27. }
  28. time.Sleep(50 * time.Millisecond)
  29. }
  30. if m.TempGetCount() != 0 {
  31. t.Fatalf("GET_TEMPERATURE during first 10s startup: %d", m.TempGetCount())
  32. }
  33. if m.MotorGetCount() == 0 {
  34. t.Fatal("expected MOTOR_STATUS polling during startup")
  35. }
  36. if d.Snapshot().GetDeviceEpoch() != 1 {
  37. t.Fatalf("epoch changed during delayed startup: %d", d.Snapshot().GetDeviceEpoch())
  38. }
  39. waitReady(t, d)
  40. deadline = time.Now().Add(3 * time.Second)
  41. for time.Now().Before(deadline) {
  42. if m.TempGetCount() > 0 {
  43. return
  44. }
  45. time.Sleep(20 * time.Millisecond)
  46. }
  47. t.Fatal("expected GET_TEMPERATURE after startup_complete")
  48. }
  49. func testDevNoWait(t *testing.T, mock *backend.Mock) *device.Device {
  50. t.Helper()
  51. p, err := profile.Load(testutil.ProfilePath(t))
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. fan, ptc, door := 10, 0, 0
  56. dir := t.TempDir()
  57. cfg := &config.Config{
  58. APIVersion: "hth.api.v1",
  59. DeviceID: "prod2u-0",
  60. Backend: config.BackendMock,
  61. Profile: testutil.ProfilePath(t),
  62. RuntimeRoot: dir,
  63. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  64. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  65. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  66. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  67. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  68. RingBufferSize: 32,
  69. SubscriberBufferSize: 64,
  70. CommandCacheSize: 16,
  71. AllowUnboundActions: true,
  72. Mock: config.Mock{Seed: 1, StartupComplete: false},
  73. }
  74. if err := cfg.Validate(p); err != nil {
  75. t.Fatal(err)
  76. }
  77. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  78. ctx, cancel := context.WithCancel(context.Background())
  79. t.Cleanup(func() { cancel(); d.Stop() })
  80. d.Start(ctx)
  81. return d
  82. }
  83. func TestSafeModeRejectsOrdinaryApplyUntilResume(t *testing.T) {
  84. d := testDev(t, backend.NewMock(1, true))
  85. l := acquire(t, d)
  86. ctx := context.Background()
  87. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  88. if !res.Accepted {
  89. t.Fatalf("enter safe: %+v", res)
  90. }
  91. if res.GetDispatched() != nil && res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCHED {
  92. t.Fatal("EnterSafeMode must not claim DISPATCHED before the write completes")
  93. }
  94. deadline := time.Now().Add(2 * time.Second)
  95. for time.Now().Before(deadline) {
  96. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  97. break
  98. }
  99. time.Sleep(10 * time.Millisecond)
  100. }
  101. l2, err := d.AcquireLease(ctx, "after-safe", 400*time.Millisecond)
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. batch := &hthv1.ActionBatch{
  106. DeviceId: "prod2u-0", CommandId: "after-safe-apply",
  107. LeaseId: l2.LeaseId, LeaseEpoch: l2.LeaseEpoch,
  108. ValidUntil: timestamppb.New(time.Now().Add(time.Second)),
  109. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 20}},
  110. }
  111. out := d.ApplyAction(ctx, batch)
  112. if out.Accepted || out.RejectReason != hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE {
  113. t.Fatalf("ordinary apply must be rejected in SAFE: %+v", out)
  114. }
  115. }
  116. func TestSlewFloorNeverExceedsRateTimesElapsed(t *testing.T) {
  117. // Delegated to safety package property test; keep a host-level smoke here.
  118. d := testDev(t, backend.NewMock(1, true))
  119. if d.Capabilities().GetTiming() == nil || d.Capabilities().GetTiming().GetRecommendedRpcDeadlineMs() < 3000 {
  120. t.Fatalf("timing capabilities missing: %+v", d.Capabilities().GetTiming())
  121. }
  122. if d.Capabilities().GetDeviceFaultQuerySupported() {
  123. t.Fatal("must not claim device native fault query")
  124. }
  125. }
  126. func TestResumeFromSafeStateMachine(t *testing.T) {
  127. m := backend.NewMock(1, true)
  128. d := testDev(t, m)
  129. ctx := context.Background()
  130. l := acquire(t, d)
  131. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  132. if !res.Accepted {
  133. t.Fatalf("enter safe: %+v", res)
  134. }
  135. if res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCHED && res.GetDispatched() != nil {
  136. t.Fatal("EnterSafeMode must not report DISPATCHED before the serial write finishes")
  137. }
  138. deadline := time.Now().Add(2 * time.Second)
  139. for time.Now().Before(deadline) {
  140. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  141. break
  142. }
  143. time.Sleep(10 * time.Millisecond)
  144. }
  145. if d.Snapshot().GetSafetyControlMode() != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  146. t.Fatal("expected latched SAFE after complete safe write")
  147. }
  148. l2, err := d.AcquireLease(ctx, "resume-holder", 800*time.Millisecond)
  149. if err != nil {
  150. t.Fatal(err)
  151. }
  152. denied := d.ApplyAction(ctx, batch(d, l2, "still-safe", 0))
  153. if denied.RejectReason != hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE {
  154. t.Fatalf("ordinary apply after new lease must stay SAFE: %+v", denied)
  155. }
  156. time.Sleep(150 * time.Millisecond)
  157. out := d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, batch(d, l2, "resume-full", 0))
  158. if !out.Accepted && out.RejectReason != 0 {
  159. t.Fatalf("resume: %+v", out)
  160. }
  161. deadline = time.Now().Add(2 * time.Second)
  162. for time.Now().Before(deadline) {
  163. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL {
  164. return
  165. }
  166. time.Sleep(10 * time.Millisecond)
  167. }
  168. t.Fatalf("expected NORMAL after resume, got %v", d.Snapshot().GetSafetyControlMode())
  169. }
  170. func TestHangGetInterruptedByCloseBumpsEpoch(t *testing.T) {
  171. m := backend.NewMock(1, true)
  172. d := testDev(t, m)
  173. epoch0 := d.Snapshot().GetDeviceEpoch()
  174. d.TestingSetMaxSerialTxn(300 * time.Millisecond)
  175. m.SetHangGetOnce()
  176. deadline := time.Now().Add(4 * time.Second)
  177. for time.Now().Before(deadline) {
  178. if d.Snapshot().GetDeviceEpoch() > epoch0 {
  179. snap := d.Snapshot()
  180. if snap == nil {
  181. t.Fatal("actor stopped responding after hang interrupt")
  182. }
  183. return
  184. }
  185. _ = d.Snapshot()
  186. time.Sleep(20 * time.Millisecond)
  187. }
  188. t.Fatalf("expected epoch bump after hung GET; epoch=%d busy=%s", d.Snapshot().GetDeviceEpoch(), d.SerialBusy())
  189. }
  190. func TestShutdownSafeGoesThroughWorker(t *testing.T) {
  191. m := backend.NewMock(1, true)
  192. d := testDev(t, m)
  193. l := acquire(t, d)
  194. ctx := context.Background()
  195. res := d.ApplyAction(ctx, batch(d, l, "pre-stop", 40))
  196. if !res.Accepted {
  197. t.Fatalf("apply: %+v", res)
  198. }
  199. d.Stop()
  200. sr := d.TestingShutdownSafeResult()
  201. if sr == nil {
  202. t.Fatal("expected shutdown safe result")
  203. }
  204. writes := m.Writes()
  205. if len(writes) == 0 {
  206. t.Fatal("expected at least the shutdown SET_ALL")
  207. }
  208. last := writes[len(writes)-1]
  209. if last.Fan[0] != 10 || last.PTC[0] != 0 || last.DoorX != 0 || last.DoorY != 0 || last.DoorZ != 0 {
  210. t.Fatalf("last frame must be safe baseline, got %+v", last)
  211. }
  212. }
  213. func TestStartupRestartsSuppressTemperature(t *testing.T) {
  214. m := backend.NewMock(1, true)
  215. d := testDev(t, m)
  216. deadline := time.Now().Add(2 * time.Second)
  217. for time.Now().Before(deadline) && m.TempGetCount() == 0 {
  218. time.Sleep(20 * time.Millisecond)
  219. }
  220. if m.TempGetCount() == 0 {
  221. t.Fatal("expected temperature after first startup")
  222. }
  223. m.SetStartupComplete(false)
  224. m.StartupDelay = 3 * time.Second
  225. m.SetDisconnected(true)
  226. time.Sleep(200 * time.Millisecond)
  227. afterDrop := m.TempGetCount()
  228. m.SetDisconnected(false)
  229. hold := time.Now().Add(2 * time.Second)
  230. for time.Now().Before(hold) {
  231. if m.TempGetCount() > afterDrop+1 {
  232. t.Fatalf("GET_TEMPERATURE during re-startup: before=%d now=%d", afterDrop, m.TempGetCount())
  233. }
  234. time.Sleep(40 * time.Millisecond)
  235. }
  236. _ = d
  237. }
  238. func testDevLongTTL(t *testing.T, mock *backend.Mock) *device.Device {
  239. t.Helper()
  240. p, err := profile.Load(testutil.ProfilePath(t))
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. fan, ptc, door := 10, 0, 0
  245. dir := t.TempDir()
  246. cfg := &config.Config{
  247. APIVersion: "hth.api.v1",
  248. DeviceID: "prod2u-0",
  249. Backend: config.BackendMock,
  250. Profile: testutil.ProfilePath(t),
  251. RuntimeRoot: dir,
  252. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  253. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  254. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  255. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 20000},
  256. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  257. RingBufferSize: 32,
  258. SubscriberBufferSize: 64,
  259. CommandCacheSize: 16,
  260. AllowUnboundActions: true,
  261. Mock: config.Mock{Seed: 1, StartupComplete: true},
  262. }
  263. if err := cfg.Validate(p); err != nil {
  264. t.Fatal(err)
  265. }
  266. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  267. ctx, cancel := context.WithCancel(context.Background())
  268. t.Cleanup(func() { cancel(); d.Stop() })
  269. d.Start(ctx)
  270. waitReady(t, d)
  271. return d
  272. }
  273. func waitSlowGetInflight(t *testing.T, d *device.Device, m *backend.Mock) {
  274. t.Helper()
  275. deadline := time.Now().Add(3 * time.Second)
  276. for time.Now().Before(deadline) {
  277. if m.TempGetCount() >= 1 && d.SerialBusy() > 80*time.Millisecond {
  278. return
  279. }
  280. time.Sleep(10 * time.Millisecond)
  281. }
  282. t.Fatalf("GET_TEMPERATURE never went inflight: gets=%d busy=%s", m.TempGetCount(), d.SerialBusy())
  283. }
  284. func TestOldDeadlineRejectedDuringFiveSecondScan(t *testing.T) {
  285. m := backend.NewMock(1, true)
  286. d := testDevLongTTL(t, m)
  287. ctx := context.Background()
  288. l, err := d.AcquireLease(ctx, "deadline-old", 15*time.Second)
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. m.SetSlowGet(5 * time.Second)
  293. waitSlowGetInflight(t, d, m)
  294. epoch0 := d.Snapshot().GetDeviceEpoch()
  295. b := batch(d, l, "too-short-ttl", 0)
  296. b.ValidUntil = timestamppb.New(time.Now().Add(2 * time.Second))
  297. start := time.Now()
  298. out := d.ApplyAction(ctx, b)
  299. if time.Since(start) > 300*time.Millisecond {
  300. t.Fatalf("2s deadline must be rejected before waiting out the 5s scan: %s", time.Since(start))
  301. }
  302. if out.Accepted || out.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE {
  303. t.Fatalf("expected EXPIRED_DEADLINE for 2s TTL during 5s GET: %+v", out)
  304. }
  305. if d.Snapshot().GetDeviceEpoch() != epoch0 {
  306. t.Fatalf("rejecting unmeetable deadline must not bump epoch: %d -> %d", epoch0, d.Snapshot().GetDeviceEpoch())
  307. }
  308. }
  309. func TestRecommendedDeadlineSucceedsDuringFiveSecondScan(t *testing.T) {
  310. m := backend.NewMock(1, true)
  311. d := testDevLongTTL(t, m)
  312. ctx := context.Background()
  313. l, err := d.AcquireLease(ctx, "deadline-rec", 18*time.Second)
  314. if err != nil {
  315. t.Fatal(err)
  316. }
  317. timing := d.Capabilities().GetTiming()
  318. if timing == nil || timing.GetRecommendedActionTtlMs() < 7000 {
  319. t.Fatalf("recommended TTL too small: %+v", timing)
  320. }
  321. m.SetSlowGet(5 * time.Second)
  322. waitSlowGetInflight(t, d, m)
  323. b := batch(d, l, "recommended-ttl", 0)
  324. b.ValidUntil = timestamppb.New(time.Now().Add(time.Duration(timing.GetRecommendedActionTtlMs()) * time.Millisecond))
  325. start := time.Now()
  326. out := d.ApplyAction(ctx, b)
  327. elapsed := time.Since(start)
  328. if !out.Accepted {
  329. t.Fatalf("recommended TTL must dispatch after the 5s scan: %+v after %s", out, elapsed)
  330. }
  331. if elapsed < 4*time.Second {
  332. t.Fatalf("expected to wait for in-flight GET_TEMPERATURE, finished in %s", elapsed)
  333. }
  334. if elapsed > 12*time.Second {
  335. t.Fatalf("control dispatch after 5s scan took too long: %s", elapsed)
  336. }
  337. }