device_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. package device_test
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "testing"
  8. "time"
  9. "google.golang.org/protobuf/types/known/durationpb"
  10. "google.golang.org/protobuf/types/known/timestamppb"
  11. "hth/internal/backend"
  12. "hth/internal/clock"
  13. "hth/internal/config"
  14. "hth/internal/control"
  15. "hth/internal/device"
  16. hthv1 "hth/internal/gen/hth/api/v1"
  17. "hth/internal/ids"
  18. "hth/internal/profile"
  19. "hth/internal/protocol"
  20. "hth/internal/testutil"
  21. )
  22. func testDev(t *testing.T, mock *backend.Mock) *device.Device {
  23. t.Helper()
  24. p, err := profile.Load(testutil.ProfilePath(t))
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. fan, ptc, door := 10, 0, 0
  29. dir := t.TempDir()
  30. cfg := &config.Config{
  31. APIVersion: "hth.api.v1",
  32. DeviceID: "prod2u-0",
  33. Backend: config.BackendMock,
  34. Profile: testutil.ProfilePath(t),
  35. RuntimeRoot: dir,
  36. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  37. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  38. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  39. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  40. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  41. RingBufferSize: 32,
  42. SubscriberBufferSize: 64,
  43. CommandCacheSize: 16,
  44. AllowUnboundActions: true,
  45. Mock: config.Mock{Seed: 1, StartupComplete: true},
  46. }
  47. if err := cfg.Validate(p); err != nil {
  48. t.Fatal(err)
  49. }
  50. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  51. ctx, cancel := context.WithCancel(context.Background())
  52. t.Cleanup(func() { cancel(); d.Stop() })
  53. d.Start(ctx)
  54. waitReady(t, d)
  55. return d
  56. }
  57. func waitReady(t *testing.T, d *device.Device) {
  58. t.Helper()
  59. deadline := time.Now().Add(3 * time.Second)
  60. for time.Now().Before(deadline) {
  61. s := d.Snapshot()
  62. if s != nil && (s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY ||
  63. s.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED) {
  64. // Allow slew budget from the epoch Safe Baseline (100%/s) before tests dispatch.
  65. time.Sleep(time.Second)
  66. return
  67. }
  68. time.Sleep(10 * time.Millisecond)
  69. }
  70. s := d.Snapshot()
  71. t.Fatalf("not ready: %+v", s.GetLifecycle())
  72. }
  73. func acquire(t *testing.T, d *device.Device) *hthv1.ControlLease {
  74. t.Helper()
  75. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  76. defer cancel()
  77. l, err := d.AcquireLease(ctx, "tester", 400*time.Millisecond)
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. return l
  82. }
  83. func batch(d *device.Device, l *hthv1.ControlLease, id string, doors uint8) *hthv1.ActionBatch {
  84. s := d.Snapshot()
  85. return &hthv1.ActionBatch{
  86. DeviceId: d.ID(), CommandId: id, LeaseId: l.LeaseId, LeaseEpoch: l.LeaseEpoch,
  87. BasedOnSnapshotSeq: s.SnapshotSeq, ExpectedControlRevision: s.ControlRevision,
  88. ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
  89. ClientId: "test",
  90. ContinuousTargets: []*hthv1.ContinuousTarget{
  91. {Id: ids.Fan1, Value: 20}, {Id: ids.Fan2, Value: 20}, {Id: ids.Fan3, Value: 20}, {Id: ids.Fan4, Value: 20},
  92. {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
  93. {Id: ids.DoorX, Value: float64(doors)}, {Id: ids.DoorY, Value: float64(doors)}, {Id: ids.DoorZ, Value: float64(doors)},
  94. },
  95. }
  96. }
  97. func TestNoConfirmedOnSetAll(t *testing.T) {
  98. m := backend.NewMock(1, true)
  99. d := testDev(t, m)
  100. l := acquire(t, d)
  101. ctx := context.Background()
  102. res := d.ApplyAction(ctx, batch(d, l, "c1", 50))
  103. if !res.Accepted {
  104. t.Fatal(res.Message, res.RejectReason)
  105. }
  106. if res.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
  107. t.Fatal("SET_ALL must never be CONFIRMED")
  108. }
  109. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED {
  110. t.Fatalf("got %v", res.Confirmation)
  111. }
  112. }
  113. func TestCommandIDCacheNoSecondWrite(t *testing.T) {
  114. m := backend.NewMock(1, true)
  115. d := testDev(t, m)
  116. l := acquire(t, d)
  117. ctx := context.Background()
  118. b := batch(d, l, "same", 40)
  119. n0 := m.WriteCount()
  120. r1 := d.ApplyAction(ctx, b)
  121. r2 := d.ApplyAction(ctx, b)
  122. if !r2.ReplayedFromCache {
  123. t.Fatal("expected cache replay")
  124. }
  125. if m.WriteCount()-n0 != 1 {
  126. t.Fatalf("writes %d", m.WriteCount()-n0)
  127. }
  128. if r1.Confirmation != r2.Confirmation {
  129. t.Fatal("replay result mismatch")
  130. }
  131. }
  132. func TestCommandIDConflict(t *testing.T) {
  133. m := backend.NewMock(1, true)
  134. d := testDev(t, m)
  135. l := acquire(t, d)
  136. ctx := context.Background()
  137. b := batch(d, l, "cid", 10)
  138. d.ApplyAction(ctx, b)
  139. b2 := batch(d, l, "cid", 20)
  140. r := d.ApplyAction(ctx, b2)
  141. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_IDEMPOTENCY_CONFLICT {
  142. t.Fatalf("got %v %s", r.RejectReason, r.Message)
  143. }
  144. }
  145. func TestHeartbeatKeepsDoorPercents(t *testing.T) {
  146. m := backend.NewMock(1, true)
  147. p, err := profile.Load(testutil.ProfilePath(t))
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. fan, ptc, door := 10, 0, 0
  152. dir := t.TempDir()
  153. cfg := &config.Config{
  154. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  155. Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
  156. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  157. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  158. Watchdog: config.Watchdog{HeartbeatPeriodMS: 80},
  159. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  160. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  161. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  162. AllowUnboundActions: true,
  163. Mock: config.Mock{Seed: 1, StartupComplete: true},
  164. }
  165. if err := cfg.Validate(p); err != nil {
  166. t.Fatal(err)
  167. }
  168. d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, InstanceID: "hb"})
  169. ctx, cancel := context.WithCancel(context.Background())
  170. t.Cleanup(func() { cancel(); d.Stop() })
  171. d.Start(ctx)
  172. waitReady(t, d)
  173. l := acquire(t, d)
  174. res := d.ApplyAction(context.Background(), batch(d, l, "doors50", 50))
  175. if !res.Accepted {
  176. t.Fatal(res)
  177. }
  178. time.Sleep(200 * time.Millisecond)
  179. writes := m.Writes()
  180. seen := false
  181. for _, w := range writes {
  182. if w.DoorX == 50 && w.DoorY == 50 && w.DoorZ == 50 {
  183. seen = true
  184. continue
  185. }
  186. if seen && (w.DoorX != 50 || w.DoorY != 50 || w.DoorZ != 50) {
  187. t.Fatalf("heartbeat rewrote doors to %+v", w)
  188. }
  189. }
  190. if !seen {
  191. t.Fatalf("never dispatched doors=50, writes=%d", len(writes))
  192. }
  193. }
  194. func TestNoAutoRetryUnknownDoorDispatch(t *testing.T) {
  195. m := backend.NewMock(1, true)
  196. d := testDev(t, m)
  197. l := acquire(t, d)
  198. m.ForceShortWrite()
  199. ctx := context.Background()
  200. res := d.ApplyAction(ctx, batch(d, l, "unk", 70))
  201. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  202. t.Fatalf("got %v", res.Confirmation)
  203. }
  204. time.Sleep(150 * time.Millisecond)
  205. for _, w := range m.Writes() {
  206. if w.DoorX == 70 || w.DoorY == 70 || w.DoorZ == 70 {
  207. t.Fatal("must not auto-retry unknown door percent change")
  208. }
  209. }
  210. }
  211. func TestLeaseExpireAndReconnectInvalidate(t *testing.T) {
  212. m := backend.NewMock(1, true)
  213. d := testDev(t, m)
  214. l := acquire(t, d)
  215. time.Sleep(600 * time.Millisecond)
  216. ctx := context.Background()
  217. res := d.ApplyAction(ctx, batch(d, l, "late", 10))
  218. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED {
  219. t.Fatalf("expire got %v %s", res.RejectReason, res.Message)
  220. }
  221. l2 := acquire(t, d)
  222. e0 := d.Snapshot().DeviceEpoch
  223. m.SetDisconnected(true)
  224. deadline := time.Now().Add(2 * time.Second)
  225. for time.Now().Before(deadline) {
  226. if d.Snapshot().DeviceEpoch > e0 {
  227. break
  228. }
  229. time.Sleep(20 * time.Millisecond)
  230. }
  231. if d.Snapshot().DeviceEpoch <= e0 {
  232. t.Fatal("epoch should bump on disconnect")
  233. }
  234. res = d.ApplyAction(ctx, batch(d, l2, "after-drop", 10))
  235. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  236. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  237. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  238. t.Fatalf("reconnect must invalidate lease or refuse until baseline, got %v %s", res.RejectReason, res.Message)
  239. }
  240. }
  241. func TestClampVsRejectWholeBatch(t *testing.T) {
  242. m := backend.NewMock(1, true)
  243. d := testDev(t, m)
  244. ctx := context.Background()
  245. bad := &hthv1.ActionBatch{
  246. DeviceId: d.ID(), CommandId: "bad",
  247. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 5}, {Id: ids.DoorX, Value: 200}},
  248. }
  249. r := d.ValidateAction(ctx, bad)
  250. if r.Accepted {
  251. t.Fatal("must reject whole batch")
  252. }
  253. bad.AllowClamp = true
  254. r = d.ValidateAction(ctx, bad)
  255. if !r.Accepted || len(r.Clamps) == 0 {
  256. t.Fatalf("clamp %+v", r)
  257. }
  258. }
  259. func TestSnapshotSeqMonotonic(t *testing.T) {
  260. m := backend.NewMock(1, true)
  261. d := testDev(t, m)
  262. var last uint64
  263. for i := 0; i < 5; i++ {
  264. s := d.Snapshot()
  265. if s.SnapshotSeq < last {
  266. t.Fatal("seq decreased")
  267. }
  268. last = s.SnapshotSeq
  269. time.Sleep(40 * time.Millisecond)
  270. }
  271. if last < 2 {
  272. t.Fatal("expected polls to advance seq")
  273. }
  274. }
  275. func TestGetSnapshotIsCache(t *testing.T) {
  276. m := backend.NewMock(1, true)
  277. m.SetSlow(80 * time.Millisecond)
  278. d := testDev(t, m)
  279. start := time.Now()
  280. _ = d.Snapshot()
  281. if time.Since(start) > 40*time.Millisecond {
  282. t.Fatal("GetSnapshot must not wait on serial/GET_TEMP")
  283. }
  284. }
  285. func TestStaleSnapshotRejected(t *testing.T) {
  286. m := backend.NewMock(1, true)
  287. d := testDev(t, m)
  288. l := acquire(t, d)
  289. deadline := time.Now().Add(3 * time.Second)
  290. for time.Now().Before(deadline) && d.Snapshot().SnapshotSeq <= control.StaleSnapshotSlack+2 {
  291. time.Sleep(20 * time.Millisecond)
  292. }
  293. b := batch(d, l, "stale", 10)
  294. b.BasedOnSnapshotSeq = 1
  295. r := d.ApplyAction(context.Background(), b)
  296. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT {
  297. t.Fatalf("got %v seq=%d", r.RejectReason, d.Snapshot().SnapshotSeq)
  298. }
  299. }
  300. func TestExpiredDeadline(t *testing.T) {
  301. m := backend.NewMock(1, true)
  302. d := testDev(t, m)
  303. l := acquire(t, d)
  304. b := batch(d, l, "dead", 10)
  305. b.ValidUntil = timestamppb.New(time.Now().Add(-time.Second))
  306. r := d.ApplyAction(context.Background(), b)
  307. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE {
  308. t.Fatalf("got %v", r.RejectReason)
  309. }
  310. }
  311. func TestInvalidTempNot255C(t *testing.T) {
  312. m := backend.NewMock(1, true)
  313. m.SetInvalidChannel(0, true)
  314. d := testDev(t, m)
  315. deadline := time.Now().Add(2 * time.Second)
  316. for time.Now().Before(deadline) {
  317. s := d.Snapshot()
  318. for _, m := range s.Measurements {
  319. if m.Id == ids.TempChannel(0) && m.Quality == hthv1.DataQuality_DATA_QUALITY_INVALID {
  320. if m.Value == 255 {
  321. t.Fatal("must not report 255C")
  322. }
  323. if m.QualityReason != "DEVICE_REPORTED_INVALID" {
  324. t.Fatalf("reason %s", m.QualityReason)
  325. }
  326. return
  327. }
  328. }
  329. time.Sleep(20 * time.Millisecond)
  330. }
  331. t.Fatal("invalid temp not observed")
  332. }
  333. func TestCapabilitiesHonesty(t *testing.T) {
  334. m := backend.NewMock(1, true)
  335. d := testDev(t, m)
  336. c := d.Capabilities()
  337. if c.AckSupported || c.RpmFeedbackSupported || c.PositionFeedbackSupported {
  338. t.Fatal("ack/rpm/actual-position must be false")
  339. }
  340. if c.FirmwareVersionQuality != hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED {
  341. t.Fatal("firmware")
  342. }
  343. if c.ReadinessProbe != "motor_status_startup_complete" {
  344. t.Fatal(c.ReadinessProbe)
  345. }
  346. if c.Timing == nil || c.Timing.RecommendedSamplePeriodMs < 1000 {
  347. t.Fatalf("recommended_sample_period_ms must be the physical scan, not 50ms poll: %+v", c.Timing)
  348. }
  349. if c.Timing.PhysicalTemperatureUpdatePeriodMs < 1000 {
  350. t.Fatal("physical_temperature_update_period_ms must not look like a 50ms ADC")
  351. }
  352. if c.Timing.RecommendedSnapshotSubscriptionPeriodMs == c.Timing.PhysicalTemperatureUpdatePeriodMs {
  353. t.Fatal("snapshot subscription period must be distinct from physical temperature scan")
  354. }
  355. _ = durationpb.New(0)
  356. _ = protocol.SetAll{}
  357. }
  358. func TestNilBatchDoesNotPanic(t *testing.T) {
  359. m := backend.NewMock(1, true)
  360. d := testDev(t, m)
  361. ctx := context.Background()
  362. r := d.ApplyAction(ctx, nil)
  363. if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  364. t.Fatalf("apply nil: %+v", r)
  365. }
  366. r = d.ValidateAction(ctx, nil)
  367. if r == nil || r.RejectReason != hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT {
  368. t.Fatalf("validate nil: %+v", r)
  369. }
  370. }
  371. func TestRawRequestedKeepsOriginalFloat(t *testing.T) {
  372. m := backend.NewMock(1, true)
  373. d := testDev(t, m)
  374. l := acquire(t, d)
  375. b := batch(d, l, "raw40", 0)
  376. b.AllowClamp = true
  377. b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 40.4}}
  378. r := d.ApplyAction(context.Background(), b)
  379. if !r.Accepted {
  380. t.Fatal(r.Message, r.RejectReason)
  381. }
  382. if r.Requested == nil || len(r.Requested.Actuators) != 1 || r.Requested.Actuators[0].CommandedTarget != 40.4 {
  383. t.Fatalf("raw requested lost: %+v", r.Requested)
  384. }
  385. if r.NormalizedRequested == nil {
  386. t.Fatal("missing normalized")
  387. }
  388. }
  389. func TestStartupRejectsDoorChange(t *testing.T) {
  390. m := backend.NewMock(1, false)
  391. d := testDevNotReady(t, m)
  392. l := acquire(t, d)
  393. var r *hthv1.ActionResult
  394. for i := 0; i < 30; i++ {
  395. r = d.ApplyAction(context.Background(), batch(d, l, fmt.Sprintf("door-startup-%d", i), 40))
  396. if r.RejectReason == hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  397. return
  398. }
  399. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION &&
  400. r.RejectReason != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT {
  401. t.Fatalf("got %v %s", r.RejectReason, r.Message)
  402. }
  403. time.Sleep(5 * time.Millisecond)
  404. }
  405. t.Fatalf("got %v %s", r.RejectReason, r.Message)
  406. }
  407. func testDevNotReady(t *testing.T, mock *backend.Mock) *device.Device {
  408. t.Helper()
  409. p, err := profile.Load(testutil.ProfilePath(t))
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. fan, ptc, door := 10, 0, 0
  414. dir := t.TempDir()
  415. cfg := &config.Config{
  416. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  417. Profile: testutil.ProfilePath(t),
  418. RuntimeRoot: dir,
  419. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
  420. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  421. Watchdog: config.Watchdog{HeartbeatPeriodMS: 60},
  422. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
  423. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  424. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  425. AllowUnboundActions: true,
  426. Mock: config.Mock{Seed: 1, StartupComplete: false},
  427. }
  428. if err := cfg.Validate(p); err != nil {
  429. t.Fatal(err)
  430. }
  431. d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
  432. ctx, cancel := context.WithCancel(context.Background())
  433. t.Cleanup(func() { cancel(); d.Stop() })
  434. d.Start(ctx)
  435. deadline := time.Now().Add(2 * time.Second)
  436. for time.Now().Before(deadline) {
  437. if d.Snapshot() != nil {
  438. return d
  439. }
  440. time.Sleep(10 * time.Millisecond)
  441. }
  442. return d
  443. }
  444. func TestShortWriteBumpsEpochAndKillsLease(t *testing.T) {
  445. m := backend.NewMock(1, true)
  446. d := testDev(t, m)
  447. l := acquire(t, d)
  448. e0 := d.Snapshot().DeviceEpoch
  449. m.ForceShortWrite()
  450. res := d.ApplyAction(context.Background(), batch(d, l, "short", 70))
  451. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  452. t.Fatalf("got %v", res.Confirmation)
  453. }
  454. deadline := time.Now().Add(2 * time.Second)
  455. for time.Now().Before(deadline) {
  456. if d.Snapshot().DeviceEpoch > e0 {
  457. break
  458. }
  459. time.Sleep(10 * time.Millisecond)
  460. }
  461. if d.Snapshot().DeviceEpoch <= e0 {
  462. t.Fatal("epoch must bump after short write")
  463. }
  464. res = d.ApplyAction(context.Background(), batch(d, l, "after-short", 10))
  465. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  466. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  467. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  468. t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
  469. }
  470. }
  471. func TestAmbiguousFullWriteBumpsEpochAndKillsLease(t *testing.T) {
  472. m := backend.NewMock(1, true)
  473. d := testDev(t, m)
  474. l := acquire(t, d)
  475. e0 := d.Snapshot().DeviceEpoch
  476. m.ForceAmbiguousWrite()
  477. res := d.ApplyAction(context.Background(), batch(d, l, "ambig", 70))
  478. if res.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN {
  479. t.Fatalf("got %v", res.Confirmation)
  480. }
  481. deadline := time.Now().Add(2 * time.Second)
  482. for time.Now().Before(deadline) {
  483. if d.Snapshot().DeviceEpoch > e0 {
  484. break
  485. }
  486. time.Sleep(10 * time.Millisecond)
  487. }
  488. if d.Snapshot().DeviceEpoch <= e0 {
  489. t.Fatal("epoch must bump after ambiguous write")
  490. }
  491. res = d.ApplyAction(context.Background(), batch(d, l, "after-ambig", 10))
  492. if res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED &&
  493. res.RejectReason != hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH &&
  494. res.RejectReason != hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  495. t.Fatalf("old lease must die, got %v %s", res.RejectReason, res.Message)
  496. }
  497. }
  498. func TestCancelledQueuedApplyDoesNotWrite(t *testing.T) {
  499. m := backend.NewMock(1, true)
  500. d := testDev(t, m)
  501. l := acquire(t, d)
  502. m.SetSlow(250 * time.Millisecond)
  503. n0 := m.WriteCount()
  504. ctx1, cancel1 := context.WithTimeout(context.Background(), 2*time.Second)
  505. defer cancel1()
  506. done := make(chan *hthv1.ActionResult, 1)
  507. go func() { done <- d.ApplyAction(ctx1, batch(d, l, "slow", 10)) }()
  508. time.Sleep(40 * time.Millisecond)
  509. ctx2, cancel2 := context.WithTimeout(context.Background(), 20*time.Millisecond)
  510. defer cancel2()
  511. r2 := d.ApplyAction(ctx2, batch(d, l, "cancelled", 80))
  512. if r2.RejectReason != hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE && r2.RejectReason != hthv1.RejectReason_REJECT_REASON_QUEUE_FULL {
  513. t.Fatalf("expected cancel/queue, got %v %s", r2.RejectReason, r2.Message)
  514. }
  515. <-done
  516. for _, w := range m.Writes()[n0:] {
  517. if w.DoorX == 80 {
  518. t.Fatal("cancelled action must not be written")
  519. }
  520. }
  521. }
  522. func TestSlewRateWithFakeClock(t *testing.T) {
  523. m := backend.NewMock(1, true)
  524. p, err := profile.Load(testutil.ProfilePath(t))
  525. if err != nil {
  526. t.Fatal(err)
  527. }
  528. clk := clock.NewFake(time.Unix(1000, 0).UTC())
  529. fan, ptc, door := 10, 0, 0
  530. dir := t.TempDir()
  531. cfg := &config.Config{
  532. APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
  533. Profile: testutil.ProfilePath(t),
  534. RuntimeRoot: dir,
  535. Sockets: config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock"},
  536. Poll: config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
  537. Watchdog: config.Watchdog{HeartbeatPeriodMS: 5000},
  538. Lease: config.Lease{MinTTLMS: 40, MaxTTLMS: 5000},
  539. Safety: config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
  540. RingBufferSize: 32, SubscriberBufferSize: 64, CommandCacheSize: 16,
  541. AllowUnboundActions: true,
  542. Mock: config.Mock{Seed: 1, StartupComplete: true},
  543. }
  544. if err := cfg.Validate(p); err != nil {
  545. t.Fatal(err)
  546. }
  547. d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, Clock: clk, InstanceID: "slew"})
  548. ctx, cancel := context.WithCancel(context.Background())
  549. t.Cleanup(func() { cancel(); d.Stop() })
  550. d.Start(ctx)
  551. waitReady(t, d)
  552. clk.Advance(time.Second)
  553. l := acquire(t, d)
  554. first := batch(d, l, "slew1", 0)
  555. r := d.ApplyAction(context.Background(), first)
  556. if !r.Accepted {
  557. t.Fatal(r.Message)
  558. }
  559. clk.Advance(100 * time.Millisecond)
  560. second := batch(d, l, "slew2", 0)
  561. second.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 100}}
  562. r = d.ApplyAction(context.Background(), second)
  563. if r.RejectReason != hthv1.RejectReason_REJECT_REASON_SLEW_LIMITED {
  564. t.Fatalf("expected slew reject, got %v %s", r.RejectReason, r.Message)
  565. }
  566. second.AllowClamp = true
  567. second.CommandId = "slew2b"
  568. r = d.ApplyAction(context.Background(), second)
  569. if !r.Accepted {
  570. t.Fatal(r.Message)
  571. }
  572. }
  573. func TestLeaseSafeConcurrent(t *testing.T) {
  574. m := backend.NewMock(1, true)
  575. d := testDev(t, m)
  576. ctx := context.Background()
  577. var wg sync.WaitGroup
  578. for i := 0; i < 8; i++ {
  579. wg.Add(1)
  580. go func(i int) {
  581. defer wg.Done()
  582. l, err := d.AcquireLease(ctx, "c-"+string(rune('a'+i)), 200*time.Millisecond)
  583. if err != nil {
  584. return
  585. }
  586. _, _ = d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 200*time.Millisecond)
  587. _ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "concurrent")
  588. }(i)
  589. }
  590. wg.Wait()
  591. }
  592. func TestFairScheduleRenewWhileApplyFlood(t *testing.T) {
  593. m := backend.NewMock(1, true)
  594. d := testDev(t, m)
  595. l := acquire(t, d)
  596. m.SetSlow(20 * time.Millisecond)
  597. ctx := context.Background()
  598. var wg sync.WaitGroup
  599. for i := 0; i < 8; i++ {
  600. wg.Add(1)
  601. go func(i int) {
  602. defer wg.Done()
  603. b := batch(d, l, "flood-"+string(rune('a'+i)), 10)
  604. _ = d.ApplyAction(ctx, b)
  605. }(i)
  606. }
  607. time.Sleep(40 * time.Millisecond)
  608. start := time.Now()
  609. _, err := d.RenewLease(ctx, l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
  610. if err != nil {
  611. t.Fatal(err)
  612. }
  613. if time.Since(start) > 400*time.Millisecond {
  614. t.Fatalf("renew delayed %s", time.Since(start))
  615. }
  616. wg.Wait()
  617. }
  618. func TestSlowTemperatureScanDoesNotBlockLease(t *testing.T) {
  619. m := backend.NewMock(1, true)
  620. d := testDev(t, m)
  621. l := acquire(t, d)
  622. m.SetSlowGet(400 * time.Millisecond)
  623. time.Sleep(80 * time.Millisecond)
  624. start := time.Now()
  625. _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond)
  626. if err != nil {
  627. t.Fatal(err)
  628. }
  629. if time.Since(start) > 150*time.Millisecond {
  630. t.Fatalf("lease renew blocked by temperature scan: %s", time.Since(start))
  631. }
  632. safeStart := time.Now()
  633. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-scan")
  634. if time.Since(safeStart) > 150*time.Millisecond {
  635. t.Fatalf("EnterSafeMode blocked by scan: %s", time.Since(safeStart))
  636. }
  637. if res == nil || !res.Accepted {
  638. t.Fatalf("safe during scan: %+v", res)
  639. }
  640. }
  641. func TestReconnectDoesNotRestoreOldPTC(t *testing.T) {
  642. m := backend.NewMock(1, true)
  643. d := testDev(t, m)
  644. l := acquire(t, d)
  645. full := batch(d, l, "full-ptc", 0)
  646. for _, tgt := range full.ContinuousTargets {
  647. if len(tgt.Id) >= 4 && tgt.Id[:4] == "ptc." {
  648. tgt.Value = 80
  649. }
  650. }
  651. res := d.ApplyAction(context.Background(), full)
  652. if !res.Accepted {
  653. t.Fatal(res.Message)
  654. }
  655. e0 := d.Snapshot().DeviceEpoch
  656. m.ForceShortWrite()
  657. _ = d.ApplyAction(context.Background(), batch(d, l, "drop", 10))
  658. deadline := time.Now().Add(2 * time.Second)
  659. for time.Now().Before(deadline) {
  660. if d.Snapshot().DeviceEpoch > e0 {
  661. break
  662. }
  663. time.Sleep(10 * time.Millisecond)
  664. }
  665. deadline = time.Now().Add(2 * time.Second)
  666. var l2 *hthv1.ControlLease
  667. var err error
  668. for time.Now().Before(deadline) {
  669. l2, err = d.AcquireLease(context.Background(), "after-reconnect", 400*time.Millisecond)
  670. if err == nil && l2 != nil {
  671. break
  672. }
  673. time.Sleep(20 * time.Millisecond)
  674. }
  675. if l2 == nil {
  676. t.Fatal("could not acquire lease after reconnect", err)
  677. }
  678. waitReady(t, d)
  679. partial := &hthv1.ActionBatch{
  680. DeviceId: d.ID(), CommandId: "partial-fan-only", LeaseId: l2.LeaseId, LeaseEpoch: l2.LeaseEpoch,
  681. BasedOnSnapshotSeq: d.Snapshot().SnapshotSeq, ExpectedControlRevision: d.Snapshot().ControlRevision,
  682. ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)), ClientId: "test",
  683. ContinuousTargets: []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 30}},
  684. }
  685. pr := d.ApplyAction(context.Background(), partial)
  686. if pr.RejectReason == hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY {
  687. t.Log("partial rejected until baseline, as required")
  688. }
  689. last := m.LastSetAll()
  690. if last.PTC[0] == 80 {
  691. t.Fatal("old PTC value must not be restored after epoch change")
  692. }
  693. }
  694. func TestFiveSecondScanLeaseAndSafe(t *testing.T) {
  695. m := backend.NewMock(1, true)
  696. d := testDev(t, m)
  697. l := acquire(t, d)
  698. m.SetSlowGet(5 * time.Second)
  699. time.Sleep(120 * time.Millisecond)
  700. start := time.Now()
  701. if _, err := d.RenewLease(context.Background(), l.LeaseId, l.LeaseEpoch, 400*time.Millisecond); err != nil {
  702. t.Fatal(err)
  703. }
  704. if time.Since(start) > 200*time.Millisecond {
  705. t.Fatalf("lease renew blocked by 5s scan: %s", time.Since(start))
  706. }
  707. safeStart := time.Now()
  708. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-5s-scan")
  709. if time.Since(safeStart) > 200*time.Millisecond {
  710. t.Fatalf("EnterSafeMode blocked by 5s scan: %s", time.Since(safeStart))
  711. }
  712. if res == nil || !res.Accepted {
  713. t.Fatalf("safe during 5s scan: %+v", res)
  714. }
  715. if !strings.Contains(res.Message, "queued") && !strings.Contains(res.Message, "dispatched") && !strings.Contains(res.Message, "control-plane") {
  716. t.Logf("safe message: %s", res.Message)
  717. }
  718. }
  719. func TestQueuedSafeLatchesAfterSlowGetTemp(t *testing.T) {
  720. m := backend.NewMock(1, true)
  721. d := testDev(t, m)
  722. l := acquire(t, d)
  723. m.SetSlowGet(5 * time.Second)
  724. time.Sleep(80 * time.Millisecond)
  725. res := d.EnterSafeMode(context.Background(), l.LeaseId, l.LeaseEpoch, "during-5s-scan")
  726. if res == nil || !res.Accepted {
  727. t.Fatalf("enter safe: %+v", res)
  728. }
  729. deadline := time.Now().Add(12 * time.Second)
  730. for time.Now().Before(deadline) {
  731. if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  732. return
  733. }
  734. time.Sleep(20 * time.Millisecond)
  735. }
  736. t.Fatalf("SAFE never latched after queued behind 5s GET_TEMP: %v", d.Snapshot().GetSafetyControlMode())
  737. }