pty_r4_linux_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. //go:build linux
  2. package tests
  3. import (
  4. "context"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "google.golang.org/protobuf/types/known/durationpb"
  10. "google.golang.org/protobuf/types/known/timestamppb"
  11. "hth/internal/app"
  12. "hth/internal/devsim"
  13. hthv1 "hth/internal/gen/hth/api/v1"
  14. "hth/internal/grpcserver"
  15. "hth/internal/ids"
  16. "hth/internal/protocol"
  17. "hth/internal/serialtransport"
  18. )
  19. func startSerialAppR4(t *testing.T, sim *devsim.Sim, getTempMS int) (obs, ctl string, a *app.App) {
  20. t.Helper()
  21. serialtransport.SetTestWriteCap(0)
  22. serialtransport.SetTestForceWriteError(false)
  23. dir := t.TempDir()
  24. obs = filepath.Join(dir, "observe", "o.sock")
  25. ctl = filepath.Join(dir, "control", "c.sock")
  26. prof := shortScanProfile(t, 80)
  27. yaml := `
  28. api_version: hth.api.v1
  29. device_id: prod2u-0
  30. backend: serial
  31. profile: ` + prof + `
  32. runtime_root: ` + dir + `
  33. serial:
  34. path: ` + sim.Name + `
  35. get_temp_timeout_ms: ` + itoa(getTempMS) + `
  36. get_motor_timeout_ms: 4000
  37. probe_timeout_ms: 4000
  38. sockets:
  39. observe: ` + obs + `
  40. control: ` + ctl + `
  41. observe_perm: "0660"
  42. control_perm: "0660"
  43. poll:
  44. temperature_ms: 80
  45. motor_status_ms: 60000
  46. watchdog:
  47. heartbeat_period_ms: 8000
  48. lease:
  49. min_ttl_ms: 50
  50. max_ttl_ms: 30000
  51. safety:
  52. fan: 10
  53. ptc: 0
  54. door_close_percent: 0
  55. ring_buffer_size: 64
  56. subscriber_buffer_size: 4
  57. grpc:
  58. reflection: false
  59. allow_unbound_actions: true
  60. `
  61. cfgPath := filepath.Join(dir, "hthd.yaml")
  62. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  63. t.Fatal(err)
  64. }
  65. var err error
  66. a, err = app.New(cfgPath, "serial", nil)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. ctx, cancel := context.WithCancel(context.Background())
  71. errCh := make(chan error, 1)
  72. go func() { errCh <- a.Run(ctx) }()
  73. t.Cleanup(func() {
  74. serialtransport.SetTestWriteCap(0)
  75. serialtransport.SetTestForceWriteError(false)
  76. cancel()
  77. a.Stop()
  78. <-errCh
  79. })
  80. waitUnix(t, obs, 4*time.Second)
  81. waitUnix(t, ctl, 4*time.Second)
  82. return obs, ctl, a
  83. }
  84. func itoa(n int) string {
  85. if n == 0 {
  86. return "0"
  87. }
  88. var b [16]byte
  89. i := len(b)
  90. for n > 0 {
  91. i--
  92. b[i] = byte('0' + n%10)
  93. n /= 10
  94. }
  95. return string(b[i:])
  96. }
  97. func r4Batch(lease *hthv1.LeaseResponse, snap *hthv1.Snapshot, cmd string, door float64) *hthv1.ActionBatch {
  98. return &hthv1.ActionBatch{
  99. DeviceId: "prod2u-0", CommandId: cmd, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  100. BasedOnSnapshotSeq: snap.SnapshotSeq, ExpectedControlRevision: snap.ControlRevision,
  101. ValidUntil: timestamppb.New(time.Now().Add(8 * time.Second)),
  102. ContinuousTargets: []*hthv1.ContinuousTarget{
  103. {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
  104. {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
  105. {Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},
  106. },
  107. }
  108. }
  109. func TestPTYLatestWinsDuringDelayedGET(t *testing.T) {
  110. sim, err := devsim.Start(devsim.Options{StartupDone: true})
  111. if err != nil {
  112. t.Fatal(err)
  113. }
  114. defer sim.Close()
  115. obs, ctl, _ := startSerialAppR4(t, sim, 800)
  116. waitUntilReady(t, obs, 20*time.Second)
  117. waitSlewBudget()
  118. sim.SetOptions(devsim.Options{StartupDone: true, Delay: 400 * time.Millisecond})
  119. oc, err := grpcserver.DialUnix(obs, time.Second)
  120. if err != nil {
  121. t.Fatal(err)
  122. }
  123. defer oc.Close()
  124. cc, err := grpcserver.DialUnix(ctl, time.Second)
  125. if err != nil {
  126. t.Fatal(err)
  127. }
  128. defer cc.Close()
  129. obsCli := hthv1.NewObserveServiceClient(oc)
  130. ctrl := hthv1.NewControlServiceClient(cc)
  131. ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
  132. defer cancel()
  133. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  134. DeviceId: "prod2u-0", Holder: "pty-lw", Ttl: durationpb.New(8 * time.Second),
  135. })
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. time.Sleep(60 * time.Millisecond)
  140. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. oldCh := make(chan *hthv1.ActionResult, 1)
  145. newCh := make(chan *hthv1.ActionResult, 1)
  146. go func() {
  147. r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "old-door", 30)})
  148. oldCh <- r
  149. }()
  150. time.Sleep(20 * time.Millisecond)
  151. go func() {
  152. r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "new-door", 70)})
  153. newCh <- r
  154. }()
  155. oldRes := <-oldCh
  156. newRes := <-newCh
  157. if oldRes != nil && oldRes.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED &&
  158. oldRes.RejectReason != hthv1.RejectReason_REJECT_REASON_SUPERSEDED &&
  159. oldRes.Accepted {
  160. // If GET was not inflight the old apply may have written. Latest-wins only applies to not-started writes.
  161. t.Logf("old apply completed without supersede (GET may not have been inflight): %+v", oldRes)
  162. }
  163. if newRes == nil || newRes.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
  164. t.Fatalf("new apply: %+v", newRes)
  165. }
  166. deadline := time.Now().Add(3 * time.Second)
  167. saw70 := false
  168. saw30After70 := false
  169. for time.Now().Before(deadline) {
  170. sets := sim.SetAlls()
  171. seen70 := false
  172. for _, s := range sets {
  173. if s.DoorX == 70 {
  174. seen70 = true
  175. saw70 = true
  176. }
  177. if seen70 && s.DoorX == 30 {
  178. saw30After70 = true
  179. }
  180. }
  181. if saw70 {
  182. break
  183. }
  184. time.Sleep(30 * time.Millisecond)
  185. }
  186. if saw30After70 {
  187. t.Fatal("superseded door=30 was written after latest door=70")
  188. }
  189. if !saw70 && newRes != nil && newRes.Accepted {
  190. t.Fatal("latest door=70 was not written")
  191. }
  192. }
  193. func TestPTYShutdownDoesNotWritePendingApply(t *testing.T) {
  194. sim, err := devsim.Start(devsim.Options{StartupDone: true})
  195. if err != nil {
  196. t.Fatal(err)
  197. }
  198. defer sim.Close()
  199. obs, ctl, a := startSerialAppR4(t, sim, 900)
  200. waitUntilReady(t, obs, 20*time.Second)
  201. waitSlewBudget()
  202. oc, err := grpcserver.DialUnix(obs, time.Second)
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. defer oc.Close()
  207. cc, err := grpcserver.DialUnix(ctl, time.Second)
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. defer cc.Close()
  212. obsCli := hthv1.NewObserveServiceClient(oc)
  213. ctrl := hthv1.NewControlServiceClient(cc)
  214. ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
  215. defer cancel()
  216. // Delay GET replies before taking a lease. After lease, control-window
  217. // suppresses GET_TEMP, so the in-flight GET must already be sleeping.
  218. sim.SetOptions(devsim.Options{StartupDone: true, Delay: 1500 * time.Millisecond})
  219. gets := sim.CountType(protocol.TypeGetTemperature)
  220. waitGET := time.Now().Add(2 * time.Second)
  221. for time.Now().Before(waitGET) && sim.CountType(protocol.TypeGetTemperature) <= gets {
  222. time.Sleep(5 * time.Millisecond)
  223. }
  224. if sim.CountType(protocol.TypeGetTemperature) <= gets {
  225. t.Fatal("GET_TEMPERATURE never started; cannot prove pending-apply shutdown")
  226. }
  227. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  228. DeviceId: "prod2u-0", Holder: "pty-sd", Ttl: durationpb.New(8 * time.Second),
  229. })
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. done := make(chan *hthv1.ActionResult, 1)
  238. go func() {
  239. r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "pending-sd", 40)})
  240. done <- r
  241. }()
  242. time.Sleep(30 * time.Millisecond)
  243. n0 := sim.FrameCountSETALL()
  244. a.Stop()
  245. select {
  246. case <-done:
  247. case <-time.After(4 * time.Second):
  248. }
  249. for _, s := range sim.SetAlls() {
  250. _ = n0
  251. if s.DoorX == 40 && s.DoorY == 40 && s.DoorZ == 40 {
  252. t.Fatal("pending apply was written on PTY after Stop")
  253. }
  254. }
  255. }
  256. func TestPTYSafeReconnectStaysSafe(t *testing.T) {
  257. sim, err := devsim.Start(devsim.Options{StartupDone: true})
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. defer sim.Close()
  262. obs, ctl, _ := startSerialAppR4(t, sim, 400)
  263. waitUntilReady(t, obs, 20*time.Second)
  264. waitSlewBudget()
  265. oc, err := grpcserver.DialUnix(obs, time.Second)
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. defer oc.Close()
  270. cc, err := grpcserver.DialUnix(ctl, time.Second)
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. defer cc.Close()
  275. obsCli := hthv1.NewObserveServiceClient(oc)
  276. ctrl := hthv1.NewControlServiceClient(cc)
  277. ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
  278. defer cancel()
  279. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  280. DeviceId: "prod2u-0", Holder: "pty-safe", Ttl: durationpb.New(8 * time.Second),
  281. })
  282. if err != nil {
  283. t.Fatal(err)
  284. }
  285. if _, err := ctrl.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
  286. DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "pty",
  287. }); err != nil {
  288. t.Fatal(err)
  289. }
  290. deadline := time.Now().Add(3 * time.Second)
  291. for time.Now().Before(deadline) {
  292. s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  293. if err == nil && s.Snapshot.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  294. break
  295. }
  296. time.Sleep(20 * time.Millisecond)
  297. }
  298. e0 := waitEpoch(t, obs, 1)
  299. pg0 := uint64(0)
  300. if s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"}); err == nil {
  301. pg0 = s.Snapshot.GetPortGeneration()
  302. }
  303. sim.Disconnect()
  304. serialtransport.SetTestForceWriteError(true)
  305. _ = waitEpoch(t, obs, e0+1)
  306. serialtransport.SetTestForceWriteError(false)
  307. deadline = time.Now().Add(6 * time.Second)
  308. for time.Now().Before(deadline) {
  309. s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  310. if err != nil || s.Snapshot == nil {
  311. time.Sleep(30 * time.Millisecond)
  312. continue
  313. }
  314. if s.Snapshot.GetPortGeneration() < pg0 {
  315. t.Fatal("port generation went backwards")
  316. }
  317. mode := s.Snapshot.GetSafetyControlMode()
  318. if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL && s.Snapshot.GetDeviceEpoch() > e0 {
  319. t.Fatal("SAFE latch cleared by reconnect")
  320. }
  321. if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
  322. mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
  323. if s.Snapshot.GetDeviceEpoch() > e0 {
  324. return
  325. }
  326. }
  327. time.Sleep(30 * time.Millisecond)
  328. }
  329. t.Fatalf("want SAFE after PTY reconnect, last mode unknown")
  330. }
  331. func TestPTYHeartbeatFailureDoesNotRewriteDoors(t *testing.T) {
  332. sim, err := devsim.Start(devsim.Options{StartupDone: true})
  333. if err != nil {
  334. t.Fatal(err)
  335. }
  336. defer sim.Close()
  337. obs, ctl, _ := startSerialAppR4(t, sim, 400)
  338. waitUntilReady(t, obs, 20*time.Second)
  339. waitSlewBudget()
  340. oc, err := grpcserver.DialUnix(obs, time.Second)
  341. if err != nil {
  342. t.Fatal(err)
  343. }
  344. defer oc.Close()
  345. cc, err := grpcserver.DialUnix(ctl, time.Second)
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. defer cc.Close()
  350. obsCli := hthv1.NewObserveServiceClient(oc)
  351. ctrl := hthv1.NewControlServiceClient(cc)
  352. ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
  353. defer cancel()
  354. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  355. DeviceId: "prod2u-0", Holder: "pty-hb", Ttl: durationpb.New(8 * time.Second),
  356. })
  357. if err != nil {
  358. t.Fatal(err)
  359. }
  360. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  361. if err != nil {
  362. t.Fatal(err)
  363. }
  364. res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "doors55", 55)})
  365. if err != nil || !res.Accepted {
  366. t.Fatalf("apply: %v %+v", err, res)
  367. }
  368. deadline := time.Now().Add(2 * time.Second)
  369. for time.Now().Before(deadline) {
  370. for _, s := range sim.SetAlls() {
  371. if s.DoorX == 55 {
  372. serialtransport.SetTestWriteCap(1)
  373. time.Sleep(200 * time.Millisecond)
  374. for _, w := range sim.SetAlls() {
  375. if w.DoorX == 0 && w.DoorY == 0 && w.DoorZ == 0 && w.Fan[0] != 10 {
  376. t.Fatalf("failed heartbeat rewrote doors to %+v", w)
  377. }
  378. }
  379. return
  380. }
  381. }
  382. time.Sleep(20 * time.Millisecond)
  383. }
  384. t.Fatal("door 55 never written before heartbeat-failure probe")
  385. }