pty_r4_linux_test.go 11 KB

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