r5_safety_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package device_test
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "testing"
  7. "time"
  8. "hth/internal/backend"
  9. "hth/internal/config"
  10. "hth/internal/device"
  11. hthv1 "hth/internal/gen/hth/api/v1"
  12. "hth/internal/profile"
  13. "hth/internal/testutil"
  14. )
  15. func drainActionResults(subC <-chan *hthv1.Event) (<-chan *hthv1.ActionResult, context.CancelFunc) {
  16. ctx, cancel := context.WithCancel(context.Background())
  17. out := make(chan *hthv1.ActionResult, 64)
  18. go func() {
  19. defer close(out)
  20. for {
  21. select {
  22. case <-ctx.Done():
  23. return
  24. case ev, ok := <-subC:
  25. if !ok {
  26. return
  27. }
  28. if ev != nil && ev.ActionResult != nil {
  29. select {
  30. case out <- ev.ActionResult:
  31. case <-ctx.Done():
  32. return
  33. }
  34. }
  35. }
  36. }
  37. }()
  38. return out, cancel
  39. }
  40. func waitAR(t *testing.T, ch <-chan *hthv1.ActionResult, timeout time.Duration, pred func(*hthv1.ActionResult) bool) *hthv1.ActionResult {
  41. t.Helper()
  42. deadline := time.Now().Add(timeout)
  43. for time.Now().Before(deadline) {
  44. remain := time.Until(deadline)
  45. if remain <= 0 {
  46. break
  47. }
  48. select {
  49. case ar, ok := <-ch:
  50. if !ok {
  51. t.Fatal("action result stream closed")
  52. }
  53. if pred == nil || pred(ar) {
  54. return ar
  55. }
  56. case <-time.After(remain):
  57. }
  58. }
  59. t.Fatal("timed out waiting for ActionResult")
  60. return nil
  61. }
  62. func TestManualSafeWriteDisconnectedDropsTransport(t *testing.T) {
  63. m := backend.NewMock(1, true)
  64. d := testDevSafety(t, m, 10, 0, 0)
  65. sub, _, _, err := d.SubscribeEvents(0, "r5-disc")
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. defer sub.Cancel()
  70. ars, stop := drainActionResults(sub.C)
  71. defer stop()
  72. epoch := d.Snapshot().DeviceEpoch
  73. m.ForceDisconnectOnce()
  74. ctx := context.Background()
  75. l := acquire(t, d)
  76. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  77. if !res.Accepted {
  78. t.Fatalf("enter accepted=%v %s", res.Accepted, res.Message)
  79. }
  80. ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
  81. return a.CommandId == res.CommandId && (a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED ||
  82. a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN)
  83. })
  84. if ar.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED {
  85. t.Fatal("disconnected Safe must not be UNCONFIRMED success")
  86. }
  87. deadline := time.Now().Add(3 * time.Second)
  88. for time.Now().Before(deadline) {
  89. s := d.Snapshot()
  90. if s.DeviceEpoch > epoch && s.GetTransportState() != hthv1.TransportState_TRANSPORT_STATE_CONNECTED {
  91. return
  92. }
  93. time.Sleep(20 * time.Millisecond)
  94. }
  95. s := d.Snapshot()
  96. t.Fatalf("want epoch bump and not connected: epoch %d->%d transport %v", epoch, s.DeviceEpoch, s.GetTransportState())
  97. }
  98. func startMockNoWait(t *testing.T, mock *backend.Mock) *device.Device {
  99. t.Helper()
  100. p, err := profile.Load(testutil.ProfilePath(t))
  101. if err != nil {
  102. t.Fatal(err)
  103. }
  104. fan, ptc, door := 10, 0, 0
  105. dir := t.TempDir()
  106. cfg := &config.Config{
  107. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  108. Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
  109. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  110. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  111. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  112. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  113. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  114. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  115. AllowUnboundActions: true, Mock: config.Mock{Seed: 1, StartupComplete: true},
  116. }
  117. if err := cfg.Validate(p); err != nil {
  118. t.Fatal(err)
  119. }
  120. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  121. ctx, cancel := context.WithCancel(context.Background())
  122. t.Cleanup(func() { cancel(); d.Stop() })
  123. d.Start(ctx)
  124. return d
  125. }
  126. func TestEpochBaselineWriteDisconnectedDrops(t *testing.T) {
  127. m := backend.NewMock(1, true)
  128. m.ForceDisconnectOnce()
  129. d := startMockNoWait(t, m)
  130. deadline := time.Now().Add(4 * time.Second)
  131. saw := false
  132. for time.Now().Before(deadline) {
  133. s := d.Snapshot()
  134. if s.DeviceEpoch > 1 && s.GetTransportState() != hthv1.TransportState_TRANSPORT_STATE_CONNECTED {
  135. saw = true
  136. break
  137. }
  138. time.Sleep(20 * time.Millisecond)
  139. }
  140. if !saw {
  141. t.Fatalf("epoch baseline disconnect did not drop: epoch=%d transport=%v", d.Snapshot().DeviceEpoch, d.Snapshot().GetTransportState())
  142. }
  143. }
  144. func TestManualSafeNotStartedThenSuccessKeepsCommandID(t *testing.T) {
  145. m := backend.NewMock(1, true)
  146. d := testDevSafety(t, m, 10, 0, 0)
  147. sub, _, _, err := d.SubscribeEvents(0, "r5-ns")
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. defer sub.Cancel()
  152. ars, stop := drainActionResults(sub.C)
  153. defer stop()
  154. m.ForceZeroByteWrite()
  155. ctx := context.Background()
  156. l := acquire(t, d)
  157. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  158. ar := waitAR(t, ars, 5*time.Second, func(a *hthv1.ActionResult) bool {
  159. return a.CommandId == res.CommandId && (a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED ||
  160. a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  161. })
  162. if ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED {
  163. t.Fatalf("expected NotStarted then success, got %v %s", ar.DispatchState, ar.Message)
  164. }
  165. if ar.CommandId != res.CommandId {
  166. t.Fatalf("command id changed %q -> %q", res.CommandId, ar.CommandId)
  167. }
  168. waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
  169. }
  170. func TestEpochBaselineNotStartedThenSuccess(t *testing.T) {
  171. m := backend.NewMock(1, true)
  172. m.ForceZeroByteWrite()
  173. d := testDev(t, m)
  174. waitReady(t, d)
  175. if d.Snapshot().GetContinuousTargets() == nil {
  176. t.Fatal("baseline should publish commanded targets after retry")
  177. }
  178. }
  179. func TestSafeNotStartedUntilDeadlineEmitsTerminal(t *testing.T) {
  180. m := backend.NewMock(1, true)
  181. d := testDevSafety(t, m, 10, 0, 0)
  182. sub, _, _, err := d.SubscribeEvents(0, "r5-dead")
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. defer sub.Cancel()
  187. ars, stop := drainActionResults(sub.C)
  188. defer stop()
  189. m.ForceZeroByteWrites(64)
  190. ctx := context.Background()
  191. l := acquire(t, d)
  192. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  193. start := time.Now()
  194. ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
  195. return a.CommandId == res.CommandId && a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  196. })
  197. if ar.CommandId != res.CommandId {
  198. t.Fatalf("retry chain changed command id")
  199. }
  200. if time.Since(start) < 40*time.Millisecond {
  201. t.Fatalf("retries completed too fast (%s); busy-loop?", time.Since(start))
  202. }
  203. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_UNSPECIFIED {
  204. t.Fatal("mode unset")
  205. }
  206. }
  207. func TestSafeRetryDoesNotBusyLoop(t *testing.T) {
  208. m := backend.NewMock(1, true)
  209. d := testDevSafety(t, m, 10, 0, 0)
  210. before := m.WriteCount()
  211. m.ForceZeroByteWrites(32)
  212. ctx := context.Background()
  213. l := acquire(t, d)
  214. _ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  215. time.Sleep(180 * time.Millisecond)
  216. after := m.WriteCount()
  217. delta := after - before
  218. if delta > 8 {
  219. t.Fatalf("too many SET_ALL attempts in 180ms: %d (busy loop)", delta)
  220. }
  221. }
  222. func TestEverySETALLHasActionResultIncludingHeartbeat(t *testing.T) {
  223. m := backend.NewMock(1, true)
  224. d := testDevSafety(t, m, 10, 0, 0)
  225. sub, _, _, err := d.SubscribeEvents(0, "r5-all")
  226. if err != nil {
  227. t.Fatal(err)
  228. }
  229. defer sub.Cancel()
  230. ars, stop := drainActionResults(sub.C)
  231. defer stop()
  232. ctx := context.Background()
  233. l := acquire(t, d)
  234. rev0 := d.Snapshot().ControlRevision
  235. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  236. ar := waitAR(t, ars, 5*time.Second, func(a *hthv1.ActionResult) bool {
  237. return a.CommandId == res.CommandId && a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  238. })
  239. waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
  240. if ar.Dispatched == nil || ar.Dispatched.ActionEpoch == 0 || ar.Dispatched.PortGeneration == 0 {
  241. t.Fatal("safe dispatched record missing epoch/port")
  242. }
  243. rev1 := d.Snapshot().ControlRevision
  244. if rev1 <= rev0 {
  245. t.Fatalf("safe write should bump control_revision %d -> %d", rev0, rev1)
  246. }
  247. for _, tgt := range d.Snapshot().ContinuousTargets {
  248. if tgt.TargetQuality != hthv1.DataQuality_DATA_QUALITY_VALID {
  249. t.Fatalf("target quality %v want VALID", tgt.TargetQuality)
  250. }
  251. if tgt.TargetEpoch == 0 {
  252. t.Fatal("target epoch 0")
  253. }
  254. if tgt.ActualQuality != hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED {
  255. t.Fatal("actual must stay NOT_SUPPORTED")
  256. }
  257. }
  258. }
  259. func TestHeartbeatDoesNotBumpRevision(t *testing.T) {
  260. m := backend.NewMock(1, true)
  261. d := testDevSafety(t, m, 10, 0, 0)
  262. waitReady(t, d)
  263. rev := d.Snapshot().ControlRevision
  264. time.Sleep(200 * time.Millisecond)
  265. if d.Snapshot().ControlRevision != rev {
  266. t.Fatalf("revision changed without a committed new target: %d -> %d", rev, d.Snapshot().ControlRevision)
  267. }
  268. }
  269. func TestCancelledLeaseOpsHaveNoSideEffects(t *testing.T) {
  270. m := backend.NewMock(1, true)
  271. d := testDevSafety(t, m, 10, 0, 0)
  272. ctx, cancel := context.WithCancel(context.Background())
  273. cancel()
  274. lease, err := d.AcquireLease(ctx, "ghost", time.Second)
  275. if lease != nil && lease.LeaseId != "" && err == nil {
  276. t.Fatal("cancelled acquire must not return a live lease")
  277. }
  278. time.Sleep(80 * time.Millisecond)
  279. s := d.Snapshot()
  280. if s.Lease != nil && s.Lease.Active {
  281. t.Fatal("cancelled acquire mutated lease")
  282. }
  283. live := acquire(t, d)
  284. ctx2, cancel2 := context.WithCancel(context.Background())
  285. cancel2()
  286. _ = d.ReleaseLease(ctx2, live.LeaseId, live.LeaseEpoch)
  287. time.Sleep(80 * time.Millisecond)
  288. s = d.Snapshot()
  289. if s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
  290. s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
  291. t.Fatal("cancelled release must not enter Safe")
  292. }
  293. ctx3, cancel3 := context.WithCancel(context.Background())
  294. cancel3()
  295. _, _ = d.RenewLease(ctx3, live.LeaseId, live.LeaseEpoch, time.Second)
  296. time.Sleep(50 * time.Millisecond)
  297. }
  298. func TestSafeEventNotPublishedBeforeDispatch(t *testing.T) {
  299. m := backend.NewMock(1, true)
  300. d := testDevSafety(t, m, 10, 0, 0)
  301. sub, _, _, err := d.SubscribeEvents(0, "r5-evt")
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. defer sub.Cancel()
  306. m.SetSlow(400 * time.Millisecond)
  307. ctx := context.Background()
  308. l := acquire(t, d)
  309. res := d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual")
  310. if res.GetDispatchState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED {
  311. t.Fatal("RPC return must not claim physical SAFE write complete")
  312. }
  313. deadline := time.Now().Add(300 * time.Millisecond)
  314. for time.Now().Before(deadline) {
  315. select {
  316. case ev := <-sub.C:
  317. if ev != nil && ev.Kind == hthv1.EventKind_EVENT_KIND_SAFE_MODE_ENTERED {
  318. t.Fatal("SAFE_MODE_ENTERED published before write completed")
  319. }
  320. default:
  321. time.Sleep(10 * time.Millisecond)
  322. }
  323. }
  324. }
  325. func TestIngressLatestWinsDoesNotBacklog(t *testing.T) {
  326. m := backend.NewMock(1, true)
  327. d := testDevSafety(t, m, 10, 0, 0)
  328. l := acquire(t, d)
  329. m.SetSlow(80 * time.Millisecond)
  330. n := 12
  331. done := make(chan *hthv1.ActionResult, n)
  332. for i := 0; i < n; i++ {
  333. b := batch(d, l, fmt.Sprintf("lw-%d", i), uint8(10+i%5))
  334. go func(b *hthv1.ActionBatch) { done <- d.ApplyAction(context.Background(), b) }(b)
  335. }
  336. superseded := 0
  337. queueFull := 0
  338. accepted := 0
  339. deadline := time.Now().Add(8 * time.Second)
  340. for i := 0; i < n; i++ {
  341. remain := time.Until(deadline)
  342. if remain <= 0 {
  343. t.Fatal("timeout waiting apply results")
  344. }
  345. select {
  346. case r := <-done:
  347. if r.RejectReason == hthv1.RejectReason_REJECT_REASON_QUEUE_FULL {
  348. queueFull++
  349. }
  350. if r.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED ||
  351. r.RejectReason == hthv1.RejectReason_REJECT_REASON_SUPERSEDED {
  352. superseded++
  353. }
  354. if r.Accepted {
  355. accepted++
  356. }
  357. case <-time.After(remain):
  358. t.Fatal("timeout")
  359. }
  360. }
  361. if queueFull != 0 {
  362. t.Fatalf("ingress must latest-wins not QUEUE_FULL, got %d queue-full", queueFull)
  363. }
  364. if accepted+superseded == 0 {
  365. t.Fatal("expected accepted and/or superseded outcomes")
  366. }
  367. }
  368. func testDevLongLease(t *testing.T, mock *backend.Mock, fan, ptc, door int) *device.Device {
  369. t.Helper()
  370. p, err := profile.Load(testutil.ProfilePath(t))
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. dir := t.TempDir()
  375. cfg := &config.Config{
  376. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  377. Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
  378. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  379. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  380. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  381. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 20000},
  382. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  383. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  384. AllowUnboundActions: true,
  385. Mock: config.Mock{Seed: 1, StartupComplete: true},
  386. }
  387. if err := cfg.Validate(p); err != nil {
  388. t.Fatal(err)
  389. }
  390. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  391. ctx, cancel := context.WithCancel(context.Background())
  392. t.Cleanup(func() { cancel(); d.Stop() })
  393. d.Start(ctx)
  394. waitReady(t, d)
  395. return d
  396. }
  397. func TestControlRevisionOnlyAtCommitPoints(t *testing.T) {
  398. m := backend.NewMock(1, true)
  399. d := testDevLongLease(t, m, 10, 0, 0)
  400. l, err := d.AcquireLease(context.Background(), "rev", 8*time.Second)
  401. if err != nil {
  402. t.Fatal(err)
  403. }
  404. seen := []uint64{d.Snapshot().ControlRevision}
  405. for i, duty := range []uint8{20, 30, 40} {
  406. res := d.ApplyAction(context.Background(), batch(d, l, fmt.Sprintf("rev-%d", i), duty))
  407. if !res.Accepted {
  408. t.Fatalf("apply %d rejected %s", i, res.Message)
  409. }
  410. time.Sleep(250 * time.Millisecond)
  411. deadline := time.Now().Add(2 * time.Second)
  412. for time.Now().Before(deadline) {
  413. rev := d.Snapshot().ControlRevision
  414. if rev > seen[len(seen)-1] {
  415. seen = append(seen, rev)
  416. break
  417. }
  418. time.Sleep(10 * time.Millisecond)
  419. }
  420. }
  421. if len(seen) < 4 {
  422. t.Fatalf("revision should advance on each committed apply, got %v", seen)
  423. }
  424. for i := 1; i < len(seen); i++ {
  425. if seen[i] <= seen[i-1] {
  426. t.Fatalf("control_revision not strictly monotonic: %v", seen)
  427. }
  428. }
  429. beforeHB := d.Snapshot().ControlRevision
  430. time.Sleep(50 * time.Millisecond)
  431. if d.Snapshot().ControlRevision != beforeHB {
  432. t.Fatal("idle wait must not bump revision")
  433. }
  434. }
  435. func testDevHB(t *testing.T, mock *backend.Mock) *device.Device {
  436. t.Helper()
  437. p, err := profile.Load(testutil.ProfilePath(t))
  438. if err != nil {
  439. t.Fatal(err)
  440. }
  441. dir := t.TempDir()
  442. fan, ptc, door := 10, 0, 0
  443. cfg := &config.Config{
  444. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  445. Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
  446. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  447. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  448. Watchdog: config.Watchdog{HeartbeatPeriodMS: 80},
  449. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 20000},
  450. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  451. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  452. AllowUnboundActions: true,
  453. Mock: config.Mock{Seed: 1, StartupComplete: true},
  454. }
  455. if err := cfg.Validate(p); err != nil {
  456. t.Fatal(err)
  457. }
  458. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  459. ctx, cancel := context.WithCancel(context.Background())
  460. t.Cleanup(func() { cancel(); d.Stop() })
  461. d.Start(ctx)
  462. waitReady(t, d)
  463. return d
  464. }
  465. func TestHeartbeatStructuredResultDoesNotBumpRevision(t *testing.T) {
  466. m := backend.NewMock(1, true)
  467. d := testDevHB(t, m)
  468. sub, _, _, err := d.SubscribeEvents(0, "r5-hb")
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. defer sub.Cancel()
  473. ars, stop := drainActionResults(sub.C)
  474. defer stop()
  475. rev := d.Snapshot().ControlRevision
  476. ar := waitAR(t, ars, 3*time.Second, func(a *hthv1.ActionResult) bool {
  477. return a != nil && strings.Contains(a.ActionOrigin, "heartbeat") && a.CommandId != ""
  478. })
  479. if ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED &&
  480. ar.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED {
  481. t.Fatalf("heartbeat dispatch %v", ar.DispatchState)
  482. }
  483. if d.Snapshot().ControlRevision != rev {
  484. t.Fatalf("heartbeat must not bump control_revision %d -> %d", rev, d.Snapshot().ControlRevision)
  485. }
  486. }
  487. func TestSafeNotStartedRetriesWithoutSubscriber(t *testing.T) {
  488. m := backend.NewMock(1, true)
  489. d := testDevSafety(t, m, 10, 0, 0)
  490. m.ForceZeroByteWrites(64)
  491. l := acquire(t, d)
  492. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "manual")
  493. if res.CommandId == "" {
  494. t.Fatal("missing command id")
  495. }
  496. deadline := time.Now().Add(3 * time.Second)
  497. for time.Now().Before(deadline) {
  498. for _, f := range d.Snapshot().GetActiveFaults() {
  499. if f.GetType() == hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED {
  500. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  501. t.Fatal("must not latch SAFE without a complete write")
  502. }
  503. return
  504. }
  505. }
  506. time.Sleep(20 * time.Millisecond)
  507. }
  508. t.Fatalf("expected NOT_DELIVERED fault without event subscriber, mode=%v faults=%v",
  509. d.Snapshot().GetSafetyControlMode(), d.Snapshot().GetActiveFaults())
  510. }
  511. func TestQueuedCancelledLeaseOps(t *testing.T) {
  512. m := backend.NewMock(1, true)
  513. d := testDevLongLease(t, m, 10, 0, 0)
  514. d.TestingHoldActor(true)
  515. time.Sleep(30 * time.Millisecond)
  516. ctx, cancel := context.WithCancel(context.Background())
  517. done := make(chan error, 1)
  518. go func() {
  519. l, err := d.AcquireLease(ctx, "queued-cancel", 2*time.Second)
  520. if l != nil && l.LeaseId != "" && err == nil {
  521. done <- fmt.Errorf("cancelled queued acquire returned live lease")
  522. return
  523. }
  524. done <- nil
  525. }()
  526. time.Sleep(25 * time.Millisecond)
  527. cancel()
  528. d.TestingHoldActor(false)
  529. select {
  530. case err := <-done:
  531. if err != nil {
  532. t.Fatal(err)
  533. }
  534. case <-time.After(2 * time.Second):
  535. d.TestingHoldActor(false)
  536. t.Fatal("acquire did not return")
  537. }
  538. if s := d.Snapshot(); s.Lease != nil && s.Lease.Active {
  539. t.Fatal("queued-cancelled acquire mutated lease")
  540. }
  541. live, err := d.AcquireLease(context.Background(), "keeper", 8*time.Second)
  542. if err != nil {
  543. t.Fatal(err)
  544. }
  545. d.TestingHoldActor(true)
  546. time.Sleep(20 * time.Millisecond)
  547. ctxR, cancelR := context.WithCancel(context.Background())
  548. doneR := make(chan error, 1)
  549. go func() { doneR <- d.ReleaseLease(ctxR, live.LeaseId, live.LeaseEpoch) }()
  550. time.Sleep(20 * time.Millisecond)
  551. cancelR()
  552. d.TestingHoldActor(false)
  553. select {
  554. case <-doneR:
  555. case <-time.After(2 * time.Second):
  556. d.TestingHoldActor(false)
  557. t.Fatal("release did not return")
  558. }
  559. s := d.Snapshot()
  560. if s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
  561. s.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
  562. t.Fatal("cancelled queued release must not enter Safe")
  563. }
  564. if s.Lease == nil || !s.Lease.Active || s.Lease.LeaseId != live.LeaseId {
  565. t.Fatal("cancelled queued release must keep lease")
  566. }
  567. epoch := live.LeaseEpoch
  568. d.TestingHoldActor(true)
  569. time.Sleep(20 * time.Millisecond)
  570. ctxN, cancelN := context.WithCancel(context.Background())
  571. doneN := make(chan struct{})
  572. go func() {
  573. _, _ = d.RenewLease(ctxN, live.LeaseId, live.LeaseEpoch, 8*time.Second)
  574. close(doneN)
  575. }()
  576. time.Sleep(20 * time.Millisecond)
  577. cancelN()
  578. d.TestingHoldActor(false)
  579. select {
  580. case <-doneN:
  581. case <-time.After(2 * time.Second):
  582. d.TestingHoldActor(false)
  583. t.Fatal("renew did not return")
  584. }
  585. s2 := d.Snapshot()
  586. if s2.Lease == nil || s2.Lease.LeaseEpoch != epoch {
  587. t.Fatal("cancelled queued renew must not change lease epoch")
  588. }
  589. }