-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathreconciler.go
More file actions
2411 lines (2281 loc) · 88.3 KB
/
Copy pathreconciler.go
File metadata and controls
2411 lines (2281 loc) · 88.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package reconciler drives non-terminal curtailment events: dispatches
// Curtail commands for pending targets, watches telemetry for drift on
// confirmed targets, and retries within a bounded budget.
package reconciler
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math"
"sync"
"time"
"connectrpc.com/authn"
"github.com/google/uuid"
commonpb "github.com/block/proto-fleet/server/generated/grpc/common/v1"
pb "github.com/block/proto-fleet/server/generated/grpc/minercommand/v1"
"github.com/block/proto-fleet/server/internal/domain/command"
"github.com/block/proto-fleet/server/internal/domain/curtailment"
"github.com/block/proto-fleet/server/internal/domain/curtailment/models"
"github.com/block/proto-fleet/server/internal/domain/infrastructure/driver"
"github.com/block/proto-fleet/server/internal/domain/session"
"github.com/block/proto-fleet/server/internal/domain/stores/interfaces"
"github.com/block/proto-fleet/server/internal/runtimejobs"
sdk "github.com/block/proto-fleet/server/sdk/v1"
)
const (
// reconcilerActorName tags the synthetic dispatch ctx so audit + filter
// bypass recognize reconciler self-traffic.
reconcilerActorName = "curtailment-reconciler"
defaultTickInterval = 30 * time.Second
defaultMaxRetries int32 = 10
defaultCurtailMaxRetries int32 = 50
// 0.5: power_w > baseline*factor is drifted; catches partial restore.
defaultDriftThresholdFactor = 0.5
// Per-target telemetry confirmation timeouts; both burn retry budget.
defaultCurtailDispatchTimeoutSec = 5
defaultRestoreDispatchTimeoutSec = 30
)
const (
skipPendingDispatchClock = false
recordPendingDispatchClock = true
)
// CommandDispatcher is the subset of command.Service the reconciler needs;
// keeps tests free of the full command-service graph.
type CommandDispatcher interface {
Curtail(ctx context.Context, selector *pb.DeviceSelector, level sdk.CurtailLevel) (*command.CommandResult, error)
Uncurtail(ctx context.Context, selector *pb.DeviceSelector) (*command.CommandResult, error)
}
// Config carries runtime tunables. Zero-valued fields use defaults.
type Config struct {
TickInterval time.Duration `help:"Interval between curtailment reconciler ticks. Zero uses the default; values below 1s are rejected." default:"0s" env:"TICK_INTERVAL"`
MaxRetries int32
CurtailMaxRetries int32
DriftThresholdFactor float64
// CurtailDispatchTimeoutSec ages out curtail-phase targets stuck in
// Dispatched without confirming telemetry (burns retry budget).
CurtailDispatchTimeoutSec int `help:"Seconds a curtail target may stay dispatched without telemetry confirmation before consuming retry budget. Zero uses the default; positive values must be at least 1." default:"0" env:"CURTAIL_DISPATCH_TIMEOUT_SEC"`
// RestoreDispatchTimeoutSec ages out restore-phase targets stuck in
// Dispatched without confirming telemetry (burns retry budget).
RestoreDispatchTimeoutSec int `help:"Seconds a restore target may stay dispatched without telemetry confirmation before consuming retry budget. Zero uses the default." default:"0" env:"RESTORE_DISPATCH_TIMEOUT_SEC"`
// ConfirmationFastPathEnabled turns on the wake-driven confirmation
// pulse (see confirmation_fast_path.go). Disabled restores exact
// tick-only confirmation semantics and starts no pulse goroutine.
ConfirmationFastPathEnabled bool `help:"Enable the curtailment confirmation fast path: a wake-driven pulse that confirms dispatched targets from fresh telemetry between full reconciler ticks." default:"true" env:"CONFIRMATION_FAST_PATH_ENABLED"`
}
func (c Config) withDefaults() Config {
if c.TickInterval <= 0 {
c.TickInterval = defaultTickInterval
}
if c.MaxRetries <= 0 {
c.MaxRetries = defaultMaxRetries
}
if c.CurtailMaxRetries <= 0 {
c.CurtailMaxRetries = defaultCurtailMaxRetries
}
if c.DriftThresholdFactor <= 0 {
c.DriftThresholdFactor = defaultDriftThresholdFactor
}
if c.CurtailDispatchTimeoutSec == 0 {
c.CurtailDispatchTimeoutSec = defaultCurtailDispatchTimeoutSec
}
if c.RestoreDispatchTimeoutSec <= 0 {
c.RestoreDispatchTimeoutSec = defaultRestoreDispatchTimeoutSec
}
return c
}
// Reconciler is a singleton goroutine ticking every config.TickInterval.
// Each tick reads non-terminal events, dispatches/observes per event with
// per-event panic isolation, then upserts the heartbeat.
type Reconciler struct {
cfg Config
store interfaces.CurtailmentStore
fanStore interfaces.CurtailmentFanStateStore
cmd CommandDispatcher
metrics curtailment.Metrics
fans curtailment.FacilityFanController
fanAlert FacilityFanAlertEmitter
now func() time.Time
// sampler backs the confirmation fast path (see
// confirmation_fast_path.go); required only when
// cfg.ConfirmationFastPathEnabled.
sampler ConfirmationSampler
confirmationStore interfaces.CurtailmentConfirmationStore
// confirmationWake coalesces pulse wakes; buffered size 1.
confirmationWake chan struct{}
// confirmationPulse is the between-pass cadence while eligible work
// exists. Defaults to confirmationPulseInterval; tests shorten it.
confirmationPulse time.Duration
// confirmationPassTimeout bounds the sampling half of one pulse pass
// (eligibility read + batch sampling). Defaults to the
// confirmationPassTimeout constant; tests shorten it to force the
// split-budget path where sampling exhausts the pass budget while the
// separate write budget stays live.
confirmationPassTimeout time.Duration
// confirmationCursor is activation-owned keyset state. Each successful
// eligibility read advances it even when no target promotes, preventing
// a nonconfirming page from monopolizing the active pulse.
confirmationCursor interfaces.ConfirmationPageCursor
loopCancel context.CancelFunc
workCancel context.CancelFunc
runCanceled <-chan struct{}
runDone <-chan struct{}
lifecycleMu sync.Mutex
mu sync.Mutex
}
var _ runtimejobs.Lifecycle = (*Reconciler)(nil)
var _ runtimejobs.Aborter = (*Reconciler)(nil)
// Option configures a Reconciler at construction time.
type Option func(*Reconciler)
// WithMetrics injects the operational metrics recorder; nil keeps the
// NoOpMetrics default.
func WithMetrics(m curtailment.Metrics) Option {
return func(r *Reconciler) {
if m != nil {
r.metrics = m
}
}
}
func WithFacilityFanController(controller curtailment.FacilityFanController) Option {
return func(r *Reconciler) { r.fans = controller }
}
// FacilityFanAlertEmitter is implemented by the metrics provider. The
// reconciler emits a per-event state gauge when failed fan-ON commands reach
// the point where miner restoration is allowed to proceed.
type FacilityFanAlertEmitter interface {
EmitCurtailmentFanRestoreFailure(ctx context.Context, orgID int64, eventUUID string, failed bool)
}
func WithFacilityFanAlertEmitter(emitter FacilityFanAlertEmitter) Option {
return func(r *Reconciler) { r.fanAlert = emitter }
}
// New builds a Reconciler. nil store/dispatcher is rejected at Start, not
// here, so a misconfigured fleetd surfaces during lifecycle bring-up.
func New(cfg Config, store interfaces.CurtailmentStore, cmd CommandDispatcher, opts ...Option) *Reconciler {
r := &Reconciler{
cfg: cfg.withDefaults(),
store: store,
cmd: cmd,
metrics: curtailment.NoOpMetrics{},
now: time.Now,
confirmationWake: make(chan struct{}, 1),
confirmationPulse: confirmationPulseInterval,
confirmationPassTimeout: confirmationPassTimeout,
}
if fanStore, ok := store.(interfaces.CurtailmentFanStateStore); ok {
r.fanStore = fanStore
}
if confirmationStore, ok := store.(interfaces.CurtailmentConfirmationStore); ok {
r.confirmationStore = confirmationStore
}
for _, opt := range opts {
opt(r)
}
return r
}
// Start spins up the tick loop for the lifetime of ctx. Repeat Starts without
// an intervening Stop are no-ops so misbehaving wiring cannot fork two
// reconcilers.
func (r *Reconciler) Start(ctx context.Context) error {
if r.store == nil {
return fmt.Errorf("curtailment reconciler: store is required")
}
if r.cmd == nil {
return fmt.Errorf("curtailment reconciler: command dispatcher is required")
}
if r.cfg.TickInterval < time.Second {
return fmt.Errorf("curtailment reconciler: tick_interval must be at least 1s, got %s", r.cfg.TickInterval)
}
if r.cfg.CurtailDispatchTimeoutSec < 1 {
return fmt.Errorf("curtailment reconciler: curtail_dispatch_timeout_sec must be at least 1, got %d", r.cfg.CurtailDispatchTimeoutSec)
}
if r.cfg.ConfirmationFastPathEnabled && r.sampler == nil {
return fmt.Errorf("curtailment reconciler: confirmation fast path is enabled but no sampler is configured (WithConfirmationSampler)")
}
if r.cfg.ConfirmationFastPathEnabled && r.confirmationStore == nil {
return fmt.Errorf("curtailment reconciler: confirmation fast path is enabled but the store does not support bulk confirmation")
}
r.lifecycleMu.Lock()
defer r.lifecycleMu.Unlock()
r.mu.Lock()
if r.runDone != nil {
stopping := channelClosed(r.runCanceled)
r.mu.Unlock()
if stopping {
return errors.New("curtailment reconciler: previous activation is still stopping")
}
return nil
}
workCtx, workCancel := context.WithCancel(context.WithoutCancel(ctx))
loopCtx, loopCancel := context.WithCancel(ctx)
runDone := make(chan struct{})
r.loopCancel = loopCancel
r.workCancel = workCancel
r.runCanceled = loopCtx.Done()
r.runDone = runDone
r.confirmationCursor = interfaces.ConfirmationPageCursor{}
r.mu.Unlock()
go r.tickLoop(loopCtx, workCtx, runDone)
slog.Debug("configured curtailment reconciler",
"tick_interval", r.cfg.TickInterval,
"confirmation_fast_path_enabled", r.cfg.ConfirmationFastPathEnabled)
return nil
}
// Stop cancels the activation and waits for it to drain within ctx. A timed-out
// activation retains ownership until its goroutine actually exits, so Start can
// never overlap it.
func (r *Reconciler) Stop(ctx context.Context) error {
r.lifecycleMu.Lock()
defer r.lifecycleMu.Unlock()
r.mu.Lock()
if r.runDone == nil {
r.mu.Unlock()
return nil
}
loopCancel := r.loopCancel
workCancel := r.workCancel
runDone := r.runDone
r.mu.Unlock()
if loopCancel != nil {
loopCancel()
}
select {
case <-runDone:
if workCancel != nil {
workCancel()
}
return nil
case <-ctx.Done():
if workCancel != nil {
workCancel()
}
return fmt.Errorf("curtailment reconciler: stop: %w", ctx.Err())
}
}
// Abort immediately cancels admission and detached work before a fatal exit.
func (r *Reconciler) Abort() {
r.mu.Lock()
loopCancel := r.loopCancel
workCancel := r.workCancel
r.mu.Unlock()
if loopCancel != nil {
loopCancel()
}
if workCancel != nil {
workCancel()
}
}
func (r *Reconciler) tickLoop(loopCtx, workCtx context.Context, runDone chan<- struct{}) {
defer close(runDone)
defer r.finishActivation()
reportProgress := runtimejobs.TrackProgress(loopCtx, r.cfg.TickInterval)
var confirmationDone <-chan struct{}
if r.cfg.ConfirmationFastPathEnabled {
done := make(chan struct{})
confirmationDone = done
go func() {
defer close(done)
// The confirmation pulse is an acceleration only, so Stop may
// cancel an active pass immediately. Full ticks keep using the
// detached work context so their existing drain semantics remain
// unchanged.
r.confirmationLoop(loopCtx, loopCtx)
}()
// Startup recovery: rows may already sit in dispatched from a
// previous process; run one pass immediately rather than waiting
// for the first full tick's wake.
r.wakeConfirmation()
}
if confirmationDone != nil {
defer func() { <-confirmationDone }()
}
ticker := time.NewTicker(r.cfg.TickInterval)
defer ticker.Stop()
for {
select {
case <-loopCtx.Done():
return
case <-ticker.C:
r.safeTick(workCtx)
if loopCtx.Err() != nil {
return
}
reportProgress()
}
}
}
func (r *Reconciler) finishActivation() {
r.mu.Lock()
defer r.mu.Unlock()
r.loopCancel = nil
r.workCancel = nil
r.runCanceled = nil
r.runDone = nil
}
func channelClosed(done <-chan struct{}) bool {
if done == nil {
return false
}
select {
case <-done:
return true
default:
return false
}
}
// safeTick recovers panics in tick-level infra so the goroutine survives;
// per-event isolation lives in processEvent.
func (r *Reconciler) safeTick(ctx context.Context) {
tickStart := r.now()
defer func() {
r.metrics.ObserveTickDuration(r.now().Sub(tickStart))
}()
defer func() {
if rec := recover(); rec != nil {
r.metrics.IncTickFailure()
slog.Error("curtailment reconciler: recovered panic in tick", "panic", rec)
}
}()
r.runTick(ctx)
}
// runTick is one reconciliation pass. Heartbeat upsert always fires so a
// bad event can't blind liveness; per-event deadlines stop one slow event
// from spending the whole tick's context budget.
func (r *Reconciler) runTick(ctx context.Context) {
tickStart := r.now()
tickUUID := uuid.New()
tickCtx, cancel := context.WithTimeout(ctx, 2*r.cfg.TickInterval)
defer cancel()
events, err := r.store.ListNonTerminalEvents(tickCtx)
if err != nil {
slog.Error("curtailment reconciler: failed to list non-terminal events", "error", err)
r.metrics.IncTickFailure()
// Heartbeat advances on tick freshness, not query health. The SQL
// staleness alert thus distinguishes "reconciler dead" (no upsert)
// from "DB read path degraded" (upsert advances, IncTickFailure
// rises).
r.upsertHeartbeat(ctx, tickStart, tickUUID, 0)
return
}
for index, ev := range events {
if tickCtx.Err() != nil {
break
}
deadline, ok := tickCtx.Deadline()
if !ok {
break
}
remaining := time.Until(deadline)
if remaining <= 0 {
break
}
// Divide the remaining tick budget across the remaining events. An
// unreachable fan set or another slow boundary on an earlier event can
// consume its share, but cannot starve every later event in ID order.
remainingEvents := len(events) - index
eventCtx, eventCancel := context.WithTimeout(tickCtx, remaining/time.Duration(remainingEvents))
r.processEvent(eventCtx, ev)
eventCancel()
}
r.upsertHeartbeat(ctx, tickStart, tickUUID, int32(len(events))) //nolint:gosec // bounded by org event count
}
func (r *Reconciler) upsertHeartbeat(_ context.Context, tickStart time.Time, tickUUID uuid.UUID, activeCount int32) {
durationMS := int32(r.now().Sub(tickStart).Milliseconds()) //nolint:gosec // tick durations fit in int32
// Detached ctx so shutdown-watchdog cancellation cannot drop the final
// heartbeat; 5s bounds a stuck DB.
hbCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := r.store.UpsertHeartbeat(hbCtx, interfaces.UpsertCurtailmentHeartbeatParams{
LastTickAt: tickStart,
LastTickUUID: tickUUID,
LastTickDurationMS: &durationMS,
ActiveEventCount: activeCount,
}); err != nil {
slog.Error("curtailment reconciler: heartbeat upsert failed", "error", err)
}
}
// processEvent dispatches per-state work for one event; recover keeps
// a per-event panic from aborting the rest of the tick.
func (r *Reconciler) processEvent(ctx context.Context, ev *models.Event) {
defer func() {
if rec := recover(); rec != nil {
r.metrics.IncTickFailure()
slog.Error("curtailment reconciler: recovered panic processing event",
"event_id", ev.ID, "event_uuid", ev.EventUUID, "panic", rec)
}
}()
switch ev.State { //nolint:exhaustive // Terminal states are filtered upstream by ListNonTerminalEvents; default logs if one slips through.
case models.EventStatePending:
r.dispatchPending(ctx, ev)
case models.EventStateActive:
r.observeActive(ctx, ev)
case models.EventStateRestoring:
r.observeRestoring(ctx, ev)
default:
slog.Warn("curtailment reconciler: unexpected event state",
"event_id", ev.ID, "state", ev.State)
}
}
// dispatchPending dispatches Curtail per pending target, confirms
// already-dispatched targets via telemetry, then flips the event to
// active once every target is confirmed or terminally failed.
func (r *Reconciler) dispatchPending(ctx context.Context, ev *models.Event) {
targets, err := r.store.ListTargetsByEvent(ctx, ev.OrgID, ev.EventUUID)
if err != nil {
slog.Error("curtailment reconciler: list targets failed",
"event_id", ev.ID, "error", err)
return
}
// Deferred so both fresh dispatches from this pass and rows already
// dispatched (recovery) wake the confirmation fast path.
defer func() { r.wakeIfDispatchedWork(targets) }()
if !r.reconcilePendingFans(ctx, ev) {
return
}
if len(targets) == 0 {
if isClosedLoopFullFleet(ev) {
now := r.now()
if err := r.store.UpdateEventState(ctx, ev.ID, ev.State, models.EventStateActive, &now, nil); err != nil {
r.logEventStateUpdateError(ev, "pending→active(empty closed-loop)", err)
}
return
}
// Service.Start rejects empty open-loop plans; zero targets is a
// contract violation needing manual recovery.
slog.Error("curtailment reconciler: pending event has no targets",
"event_id", ev.ID, "event_uuid", ev.EventUUID)
return
}
// Liveness check; per-target race-closure happens in dispatchCurtailBatch.
// DISPATCHING is included alongside PENDING because ticks are serial,
// so any DISPATCHING seen here is from an interrupted prior tick — safe
// to redispatch (Curtail is device-idempotent).
if !r.eventStillDispatchable(ctx, ev) {
return
}
cmdCtx := reconcilerCommandContext(ctx, ev.OrgID, ev.CreatedByUserID)
if isAllPairedPolicyEvent(ev) {
deviceIDs := allPairedPolicyRefreshDeviceIdentifiers(targets)
if len(deviceIDs) > 0 {
cands, err := r.store.ListCandidates(ctx, interfaces.ListCandidatesParams{
OrgID: ev.OrgID,
DeviceIdentifiers: deviceIDs,
})
if err != nil {
slog.Error("curtailment reconciler: list candidates (all-paired pending refresh) failed",
"event_id", ev.ID, "error", err)
} else {
r.refreshAllPairedPolicyTargets(cmdCtx, ev, targets, candidatesByDeviceID(cands))
}
}
}
r.dispatchPendingCurtailBatches(cmdCtx, ev, targets)
// Confirm just-dispatched targets via current telemetry before deciding
// whether the event itself can flip to active.
r.confirmDispatched(ctx, ev, targets)
r.maybeMarkActive(ctx, ev, targets)
// Durable ownership must not pause while the event is pending: recurtail
// (restoring -> pending) leaves released policy rows dormant for the
// multi-tick re-confirmation window unless admission also runs here.
// Claimed/reopened rows enter as pending/unavailable and dispatch on the
// next tick's pending pass, mirroring the observeActive claim ordering.
if isAllPairedPolicyEvent(ev) {
claimed := r.claimClosedLoopFullFleetTargets(ctx, ev, targets)
r.dispatchClaimedCurtailTargets(cmdCtx, ev, claimed)
// Claimed rows are a separate slice the deferred wakeIfDispatchedWork
// (which only sees `targets`) never covers, so a dynamically-admitted
// miner would miss the pulse when it is parked. Wake for them too.
r.wakeIfDispatchedWork(claimed)
}
}
func (r *Reconciler) reconcilePendingFans(ctx context.Context, ev *models.Event) bool {
if ev == nil || ev.FanOffSentAt == nil || ev.FanLastError == nil {
return true
}
if r.fans == nil || r.fanStore == nil || len(ev.FacilityFanDeviceIDs) == 0 {
return false
}
now := r.now()
params := interfaces.UpdateCurtailmentFanStateParams{
ExpectedEventState: models.EventStatePending,
}
if ev.FanAirflowReopenedAt == nil {
params.FanAirflowReopenedAt = &now
}
params.FanAirflowReopenedAtOnSuccess = &now
lastError, err := r.commandAndPersistFanState(ctx, ev, params, driver.PowerOn)
if err != nil {
if !errors.Is(err, interfaces.ErrCurtailmentEventStateRaceLoss) {
slog.Error("curtailment reconciler: pending facility fan ON failed", "event_id", ev.ID, "error", err)
}
return false
}
if lastError == nil {
ev.FanAirflowReopenedAt = params.FanAirflowReopenedAtOnSuccess
} else if params.FanAirflowReopenedAt != nil {
ev.FanAirflowReopenedAt = params.FanAirflowReopenedAt
}
ev.FanLastError = lastError
if lastError == nil && r.fanAlert != nil {
r.fanAlert.EmitCurtailmentFanRestoreFailure(ctx, ev.OrgID, ev.EventUUID.String(), false)
}
return lastError == nil
}
// dispatchPendingCurtailBatches drains retryable Curtail work in command
// batches. Orphaned DISPATCHING rows from an interrupted prior tick are
// recovered before fresh PENDING rows. curtail_batch_size=NULL dispatches all
// remaining targets; a positive interval paces fresh pending batches.
func (r *Reconciler) dispatchPendingCurtailBatches(ctx context.Context, ev *models.Event, targets []*models.Target) {
batchSize := curtailBatchSizeForEvent(ev, len(targets))
dispatchByState := func(state models.TargetState, dispatchSingleBatch bool, recordPendingDispatch bool) bool {
dispatchClaim := func(claim []*models.Target) bool {
recordClaimDispatch := recordPendingDispatch
if state == models.TargetStateDispatching {
recordClaimDispatch = recordPendingDispatch && hasUnrecordedCurtailDispatch(claim)
}
return r.dispatchCurtailBatch(ctx, ev, claim, state, recordClaimDispatch)
}
claim := make([]*models.Target, 0, batchSize)
for _, t := range targets {
if t.State != state {
continue
}
claim = append(claim, t)
if int32(len(claim)) >= batchSize { //nolint:gosec // batchSize already bounded
if !dispatchClaim(claim) {
return false
}
if dispatchSingleBatch {
return true
}
claim = make([]*models.Target, 0, batchSize)
}
}
if len(claim) == 0 {
return true
}
return dispatchClaim(claim)
}
intervalActive := curtailBatchIntervalActive(ev)
// A DISPATCHING row without a durable curtail-phase result may have been
// stranded before its command was enqueued. Treat that recovery as a fresh
// wave so its physical send is paced. Rows with a durable prior enqueue are
// retries and deliberately leave the pending-wave clock alone.
if !dispatchByState(models.TargetStateDispatching, intervalActive, intervalActive) {
return
}
if intervalActive && !r.curtailBatchIntervalElapsed(ev) {
return
}
_ = dispatchByState(models.TargetStatePending, intervalActive, recordPendingDispatchClock)
}
// confirmDispatched promotes Dispatched → Confirmed when telemetry
// shows the device is curtailed.
func (r *Reconciler) confirmDispatched(ctx context.Context, ev *models.Event, targets []*models.Target) {
deviceIDs := make([]string, 0, len(targets))
for _, t := range targets {
if t.State == models.TargetStateDispatched {
deviceIDs = append(deviceIDs, t.DeviceIdentifier)
}
}
if len(deviceIDs) == 0 {
return
}
cands, err := r.store.ListCandidates(ctx, interfaces.ListCandidatesParams{
OrgID: ev.OrgID,
DeviceIdentifiers: deviceIDs,
})
if err != nil {
slog.Error("curtailment reconciler: list candidates (confirm) failed",
"event_id", ev.ID, "error", err)
return
}
candByID := candidatesByDeviceID(cands)
for _, t := range targets {
if t.State != models.TargetStateDispatched {
continue
}
r.confirmOneDispatched(ctx, ev, t, candByID[t.DeviceIdentifier], models.TargetStateDispatched)
}
}
// dispatchOneCurtail issues one Curtail and records the outcome.
// nonTerminalFailureState is where the target lands on a non-terminal
// failure (Pending or Drifted, per caller).
//
// Race-closure: the DISPATCHING pre-write makes a concurrent
// AdminTerminate see an in-flight target and reject as Stop-first; its
// EXISTS guard against the parent event state catches a terminate that
// committed between the per-tick liveness check and this write.
// Restart-safety: a crash between pre-write and command leaves the
// target in DISPATCHING; the next tick redispatches via
// nonTerminalFailureState (Curtail is device-idempotent).
func (r *Reconciler) dispatchOneCurtail(ctx context.Context, ev *models.Event, t *models.Target, nonTerminalFailureState models.TargetState) {
_ = r.dispatchCurtailBatch(ctx, ev, []*models.Target{t}, nonTerminalFailureState, skipPendingDispatchClock)
}
// dispatchCurtailBatch issues one Curtail command for every device in claim and
// records per-target dispatched/skipped/failed outcomes.
func (r *Reconciler) dispatchCurtailBatch(ctx context.Context, ev *models.Event, claim []*models.Target, nonTerminalFailureState models.TargetState, recordPendingDispatch bool) bool {
if len(claim) == 0 {
return true
}
if !r.eventStillDispatchable(ctx, ev) {
return false
}
if recordPendingDispatch && !r.recordCurtailPendingDispatch(ctx, ev, r.now()) {
// Fail closed before either the DISPATCHING pre-write or the physical
// command. A successful command must never outrun a stale durable clock.
return false
}
// last_dispatched_at is *not* stamped here — only successful enqueues
// advance it (used by the restore-batch interval gate).
dispatchSet := make([]*models.Target, 0, len(claim))
for _, t := range claim {
dispatchingParams := interfaces.UpdateCurtailmentTargetStateParams{
State: models.TargetStateDispatching,
}
if err := r.writeTargetState(ctx, ev, t.DeviceIdentifier, dispatchingParams); err != nil {
if errors.Is(err, interfaces.ErrCurtailmentEventStateRaceLoss) {
return false
}
slog.Error("curtailment reconciler: dispatching pre-write failed",
"event_id", ev.ID, "device", t.DeviceIdentifier, "error", err)
// Symmetric to dispatchRestoreBatch: burn one retry slot so a
// row-specific persistent write failure escalates to terminal
// after MaxRetries instead of stalling the event indefinitely.
r.recordDispatchFailure(ctx, ev, t, err.Error(), nonTerminalFailureState)
continue
}
t.State = models.TargetStateDispatching
dispatchSet = append(dispatchSet, t)
}
if len(dispatchSet) == 0 {
return true
}
if !r.eventStillDispatchable(ctx, ev) {
return false
}
deviceIDs := make([]string, 0, len(dispatchSet))
for _, t := range dispatchSet {
deviceIDs = append(deviceIDs, t.DeviceIdentifier)
}
selector := &pb.DeviceSelector{
SelectionType: &pb.DeviceSelector_IncludeDevices{
IncludeDevices: &commonpb.DeviceIdentifierList{
DeviceIdentifiers: deviceIDs,
},
},
}
result, dispatchErr := r.cmd.Curtail(ctx, selector, sdk.CurtailLevelFull)
if dispatchErr != nil {
errMsg := dispatchErr.Error()
slog.Error("curtailment reconciler: curtail batch dispatch failed",
"event_id", ev.ID, "batch_size", len(dispatchSet), "error", dispatchErr)
for _, t := range dispatchSet {
r.recordDispatchFailure(ctx, ev, t, errMsg, nonTerminalFailureState)
}
return true
}
skippedSet := make(map[string]string)
if result != nil {
skippedSet = make(map[string]string, len(result.Skipped))
for _, s := range result.Skipped {
skippedSet[s.DeviceIdentifier] = skippedDeviceReason(s)
}
}
if result == nil || result.BatchIdentifier == "" {
const reason = "command produced no batch (no live devices to dispatch)"
slog.Warn("curtailment reconciler: curtail batch produced empty result",
"event_id", ev.ID, "batch_size", len(dispatchSet))
for _, t := range dispatchSet {
if skipReason, skipped := skippedSet[t.DeviceIdentifier]; skipped {
r.recordDispatchFailure(ctx, ev, t, skipReason, nonTerminalFailureState)
continue
}
r.recordDispatchFailure(ctx, ev, t, reason, nonTerminalFailureState)
}
return true
}
dispatchedSet := make(map[string]struct{}, len(result.DispatchedDeviceIdentifiers))
for _, deviceID := range result.DispatchedDeviceIdentifiers {
dispatchedSet[deviceID] = struct{}{}
}
now := r.now()
emptyErr := ""
batchID := result.BatchIdentifier
desiredCurtailed := models.DesiredStateCurtailed
for _, t := range dispatchSet {
if skipReason, skipped := skippedSet[t.DeviceIdentifier]; skipped {
slog.Warn("curtailment reconciler: dispatch filter-skipped",
"event_id", ev.ID, "device", t.DeviceIdentifier, "reason", skipReason)
r.recordDispatchFailure(ctx, ev, t, skipReason, nonTerminalFailureState)
continue
}
if _, dispatched := dispatchedSet[t.DeviceIdentifier]; !dispatched {
const reason = "curtail command did not enqueue device"
slog.Warn("curtailment reconciler: curtail device not dispatched",
"event_id", ev.ID, "device", t.DeviceIdentifier)
r.recordDispatchFailure(ctx, ev, t, reason, nonTerminalFailureState)
continue
}
// Explicit dispatch direction at the call site; writeTargetState's
// auto-fill would derive the same value from ev.State.
params := interfaces.UpdateCurtailmentTargetStateParams{
State: models.TargetStateDispatched,
LastDispatchedAt: &now,
LastError: &emptyErr,
LastBatchUUID: &batchID,
ExpectedDesiredState: &desiredCurtailed,
}
if err := r.writeTargetState(ctx, ev, t.DeviceIdentifier, params); err != nil {
if !errors.Is(err, interfaces.ErrCurtailmentEventStateRaceLoss) {
slog.Error("curtailment reconciler: target dispatch update failed",
"event_id", ev.ID, "device", t.DeviceIdentifier, "error", err)
r.recordDispatchFailure(ctx, ev, t, err.Error(), nonTerminalFailureState)
}
continue
}
// Mirror to the in-memory row for this tick's downstream phases.
t.State = models.TargetStateDispatched
t.LastDispatchedAt = &now
t.LastError = nil
t.LastBatchUUID = &batchID
t.CurtailPhase.State = models.TargetStateDispatched
t.CurtailPhase.DispatchedAt = &now
t.CurtailPhase.BatchUUID = &batchID
}
return true
}
type dispatchFailureGuard struct {
expectedState models.TargetState
expectedBatchUUID *string
}
func loadedDispatchBatchUUID(t *models.Target) *string {
if t.DesiredState == models.DesiredStateActive {
if t.RestorePhase == nil {
return nil
}
return t.RestorePhase.BatchUUID
}
return t.CurtailPhase.BatchUUID
}
// recordDispatchFailure bumps retry_count. Restore targets transition to
// RestoreFailed at MaxRetries so the event can complete; curtail targets stay
// retryable while OFF remains asserted, with retry_count surfacing the alert.
func (r *Reconciler) recordDispatchFailure(ctx context.Context, ev *models.Event, t *models.Target, errMsg string, nonTerminalFailureState models.TargetState) {
r.recordDispatchFailureGuarded(ctx, ev, t, errMsg, nonTerminalFailureState, nil)
}
// recordDispatchedObservationFailure guards failure writes derived from a
// loaded dispatched target on both its state and dispatch batch. The batch
// token closes the ABA window where another fleetd confirms and redispatches
// the row before this stale snapshot writes. Legacy dispatched rows without a
// batch token retain the state guard so they can still age normally.
func (r *Reconciler) recordDispatchedObservationFailure(ctx context.Context, ev *models.Event, t *models.Target, errMsg string, nonTerminalFailureState models.TargetState) {
r.recordDispatchFailureGuarded(ctx, ev, t, errMsg, nonTerminalFailureState, &dispatchFailureGuard{
expectedState: models.TargetStateDispatched,
expectedBatchUUID: loadedDispatchBatchUUID(t),
})
}
func (r *Reconciler) recordDispatchFailureGuarded(ctx context.Context, ev *models.Event, t *models.Target, errMsg string, nonTerminalFailureState models.TargetState, guard *dispatchFailureGuard) {
newRetry := t.RetryCount + 1
state := nonTerminalFailureState
if r.retryBudgetTerminalizes(t, newRetry) {
state = models.TargetStateRestoreFailed
}
params := interfaces.UpdateCurtailmentTargetStateParams{
State: state,
LastError: &errMsg,
RetryCount: &newRetry,
}
if guard != nil {
params.ExpectedState = &guard.expectedState
params.ExpectedDispatchBatchUUID = guard.expectedBatchUUID
}
err := r.writeTargetState(ctx, ev, t.DeviceIdentifier, params)
if err == nil {
t.State = state
t.RetryCount = newRetry
t.LastError = &errMsg
return
}
if errors.Is(err, interfaces.ErrCurtailmentEventStateRaceLoss) {
return
}
slog.Error("curtailment reconciler: target update after dispatch failure failed",
"event_id", ev.ID, "device", t.DeviceIdentifier, "error", err)
if guard != nil {
// BumpTargetRetry cannot carry the dispatched-state and phase-batch
// guards. Falling back here could consume retry budget on a target the
// pulse already confirmed or on a replacement dispatch batch.
return
}
// Fallback: advance retry budget only. State stays at the prior value;
// terminal restore escalation lands on the next successful UpdateTargetState.
if bumpErr := r.store.BumpTargetRetry(ctx, ev.ID, t.DeviceIdentifier); bumpErr != nil {
if !errors.Is(bumpErr, interfaces.ErrCurtailmentEventStateRaceLoss) {
r.metrics.IncTargetWriteFailure()
slog.Error("curtailment reconciler: retry-budget bump fallback failed",
"event_id", ev.ID, "device", t.DeviceIdentifier, "error", bumpErr)
}
return
}
t.RetryCount = newRetry
}
func (r *Reconciler) maxRetriesForTarget(t *models.Target) int32 {
if isCurtailRetryTarget(t) {
return r.cfg.CurtailMaxRetries
}
return r.cfg.MaxRetries
}
func (r *Reconciler) retryBudgetTerminalizes(t *models.Target, retryCount int32) bool {
return t == nil || (!isCurtailRetryTarget(t) && retryCount >= r.maxRetriesForTarget(t))
}
func isCurtailRetryTarget(t *models.Target) bool {
return t != nil && (t.DesiredState == "" || t.DesiredState == models.DesiredStateCurtailed)
}
// candidatesByDeviceID indexes a candidate slice by device identifier for
// the per-tick observe loops that join targets against telemetry.
func candidatesByDeviceID(cands []*models.Candidate) map[string]*models.Candidate {
out := make(map[string]*models.Candidate, len(cands))
for _, c := range cands {
out[c.DeviceIdentifier] = c
}
return out
}
// skippedDeviceReason renders the priority-ordered reason string for a
// filter-skipped device: explicit reason first, filter name next, generic
// fallback last. Shared by the single-device and batch dispatch paths so
// both produce the same audit string.
func skippedDeviceReason(s command.SkippedDevice) string {
switch {
case s.Reason != "":
return s.Reason
case s.FilterName != "":
return "filtered by " + s.FilterName
default:
return "filtered by command preflight"
}
}
// observeActive checks drift on confirmed targets and re-dispatches drifted
// targets up to MaxRetries. ListCandidates over-fetches columns the drift
// check ignores; acceptable at the per-tick fanout scale.
func (r *Reconciler) observeActive(ctx context.Context, ev *models.Event) {
targets, err := r.store.ListTargetsByEvent(ctx, ev.OrgID, ev.EventUUID)
if err != nil {
slog.Error("curtailment reconciler: list targets (active) failed",
"event_id", ev.ID, "error", err)
return
}
// Deferred confirmation fast-path wake; see dispatchPending.
defer func() { r.wakeIfDispatchedWork(targets) }()
if r.enforceMaxDuration(ctx, ev, targets) {
return
}
// Per-tick liveness check; per-target race closure is in dispatchOneCurtail.
if !r.eventStillDispatchable(ctx, ev) {
return
}
cmdCtx := reconcilerCommandContext(ctx, ev.OrgID, ev.CreatedByUserID)
airflowReopened := false
deferredDrifted := make([]*models.Target, 0)
if len(targets) > 0 {
deviceIDs := make([]string, 0, len(targets))
for _, t := range targets {
deviceIDs = append(deviceIDs, t.DeviceIdentifier)
}
cands, err := r.store.ListCandidates(ctx, interfaces.ListCandidatesParams{
OrgID: ev.OrgID,
DeviceIdentifiers: deviceIDs,
})
if err != nil {
slog.Error("curtailment reconciler: list candidates (drift) failed",
"event_id", ev.ID, "error", err)
if ev.FanOffSentAt != nil && len(ev.FacilityFanDeviceIDs) > 0 {
if !r.reopenActiveFans(ctx, ev) {
return
}
airflowReopened = true
}
} else {
candByID := candidatesByDeviceID(cands)
if isAllPairedPolicyEvent(ev) {
r.refreshAllPairedPolicyTargets(cmdCtx, ev, targets, candByID)
}
for _, t := range targets {
switch t.State {
case models.TargetStateConfirmed:
if ev.FanOffSentAt != nil &&
!hasFreshTelemetry(candByID[t.DeviceIdentifier]) {
if !airflowReopened {
if !r.reopenActiveFans(ctx, ev) {
return
}
airflowReopened = true
}
continue
}
r.checkDrift(cmdCtx, ev, t, candByID[t.DeviceIdentifier])
if t.State == models.TargetStateDrifted && ev.FanOffSentAt != nil {
deferredDrifted = append(deferredDrifted, t)
}
case models.TargetStateDispatched:
// Re-entry: drifted-then-redispatched, waiting on confirmation.
r.confirmOneDispatched(cmdCtx, ev, t, candByID[t.DeviceIdentifier], models.TargetStateDispatched)
case models.TargetStateDispatching:
// Orphan from an interrupted prior tick; redispatched after
// observation in batch-aware order.
if r.retryBudgetTerminalizes(t, t.RetryCount) {
// Escalate restore targets instead of leaving the row pinned
// in DISPATCHING after retry_count passes MaxRetries.
r.recordDispatchFailure(cmdCtx, ev, t,
"retry budget exhausted from interrupted dispatch",
models.TargetStateDispatching)
continue
}
case models.TargetStateDrifted:
if r.retryBudgetTerminalizes(t, t.RetryCount) {