-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathbroker.go
More file actions
1820 lines (1587 loc) · 58.8 KB
/
Copy pathbroker.go
File metadata and controls
1820 lines (1587 loc) · 58.8 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 broker
import (
"context"
"decentralized-api/apiconfig"
"decentralized-api/chainphase"
"decentralized-api/cosmosclient"
"decentralized-api/logging"
"decentralized-api/mlnodeclient"
"decentralized-api/participant"
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/productscience/inference/x/inference/types"
)
/*
enum HardwareNodeStatus {
UNKNOWN = 0;
INFERENCE = 1;
POC = 2;
TRAINING = 3;
}
*/
// BrokerChainBridge defines the interface for the broker to interact with the blockchain.
// This abstraction allows for easier testing and isolates the broker from the specifics
// of the cosmos client implementation.
type BrokerChainBridge interface {
GetHardwareNodes() (*types.QueryHardwareNodesResponse, error)
SubmitHardwareDiff(diff *types.MsgSubmitHardwareDiff) error
GetBlockHash(height int64) (string, error)
GetGovernanceModels() (*types.QueryModelsAllResponse, error)
GetCurrentEpochGroupData() (*types.QueryCurrentEpochGroupDataResponse, error)
GetEpochGroupDataByModelId(pocHeight uint64, modelId string) (*types.QueryGetEpochGroupDataResponse, error)
GetPreservedNodesSnapshot() (*types.QueryPreservedNodesSnapshotResponse, error)
GetParams() (*types.QueryParamsResponse, error)
}
type BrokerChainBridgeImpl struct {
client cosmosclient.CosmosMessageClient
chainNodeUrl string
}
func NewBrokerChainBridgeImpl(client cosmosclient.CosmosMessageClient, chainNodeUrl string) BrokerChainBridge {
return &BrokerChainBridgeImpl{client: client, chainNodeUrl: chainNodeUrl}
}
func (b *BrokerChainBridgeImpl) GetHardwareNodes() (*types.QueryHardwareNodesResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
req := &types.QueryHardwareNodesRequest{
Participant: b.client.GetAccountAddress(),
}
return queryClient.HardwareNodes(b.client.GetContext(), req)
}
func (b *BrokerChainBridgeImpl) SubmitHardwareDiff(diff *types.MsgSubmitHardwareDiff) error {
_, err := b.client.SendTransactionAsyncNoRetry(diff)
return err
}
func (b *BrokerChainBridgeImpl) GetBlockHash(height int64) (string, error) {
client, err := cosmosclient.NewRpcClient(b.chainNodeUrl)
if err != nil {
return "", err
}
block, err := client.Block(context.Background(), &height)
if err != nil {
return "", err
}
return block.Block.Hash().String(), err
}
func (b *BrokerChainBridgeImpl) GetGovernanceModels() (*types.QueryModelsAllResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
req := &types.QueryModelsAllRequest{}
return queryClient.ModelsAll(b.client.GetContext(), req)
}
func (b *BrokerChainBridgeImpl) GetCurrentEpochGroupData() (*types.QueryCurrentEpochGroupDataResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
req := &types.QueryCurrentEpochGroupDataRequest{}
return queryClient.CurrentEpochGroupData(b.client.GetContext(), req)
}
func (b *BrokerChainBridgeImpl) GetEpochGroupDataByModelId(epochIndex uint64, modelId string) (*types.QueryGetEpochGroupDataResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
req := &types.QueryGetEpochGroupDataRequest{
EpochIndex: epochIndex,
ModelId: modelId,
}
return queryClient.EpochGroupData(b.client.GetContext(), req)
}
func (b *BrokerChainBridgeImpl) GetPreservedNodesSnapshot() (*types.QueryPreservedNodesSnapshotResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
return queryClient.PreservedNodesSnapshot(b.client.GetContext(), &types.QueryPreservedNodesSnapshotRequest{})
}
func (b *BrokerChainBridgeImpl) GetParams() (*types.QueryParamsResponse, error) {
queryClient := b.client.NewInferenceQueryClient()
return queryClient.Params(b.client.GetContext(), &types.QueryParamsRequest{})
}
type Broker struct {
highPriorityCommands chan Command
lowPriorityCommands chan Command
nodes map[string]*NodeWithState
mu sync.RWMutex
curMaxNodesNum atomic.Uint64
chainBridge BrokerChainBridge
nodeWorkGroup *NodeWorkGroup
phaseTracker *chainphase.ChainPhaseTracker
participantInfo participant.CurrenParticipantInfo
callbackUrl string
mlNodeClientFactory mlnodeclient.ClientFactory
reconcileTrigger chan struct{}
lastEpochIndex uint64
lastEpochPhase types.EpochPhase
statusQueryTrigger chan statusQuerySignal
configManager *apiconfig.ConfigManager
lockMap map[string]lockEntry
lockMapMu sync.Mutex
}
type lockEntry struct {
nodeID string
createdAt time.Time
}
// GetParticipantAddress returns the current participant's address if available.
func (b *Broker) GetParticipantAddress() string {
if b == nil || b.participantInfo == nil {
return ""
}
return b.participantInfo.GetAddress()
}
const PoCBatchesBasePathV2 = "/v2/poc-batches"
func GetPoCCallbackBaseURLV2(callbackUrl string) string {
return fmt.Sprintf("%s%s", callbackUrl, PoCBatchesBasePathV2)
}
type ModelArgs struct {
Args []string `json:"args"`
}
type Node struct {
Host string `json:"host"`
InferenceSegment string `json:"inference_segment"`
InferencePort int `json:"inference_port"`
PoCSegment string `json:"poc_segment"`
PoCPort int `json:"poc_port"`
Models map[string]ModelArgs `json:"models"`
Id string `json:"id"`
MaxConcurrent int `json:"max_concurrent"`
NodeNum uint64 `json:"node_num"`
Hardware []apiconfig.Hardware `json:"hardware"`
}
func (n *Node) InferenceUrl() string {
return n.inferenceUrlWithScheme("http", "")
}
func (n *Node) InferenceUrlWithVersion(version string) string {
return n.inferenceUrlWithScheme("http", version)
}
func (n *Node) inferenceUrlWithScheme(scheme, version string) string {
if version == "" {
return fmt.Sprintf("%s://%s:%d%s", scheme, n.Host, n.InferencePort, n.InferenceSegment)
}
return fmt.Sprintf("%s://%s:%d/%s%s", scheme, n.Host, n.InferencePort, version, n.InferenceSegment)
}
func (n *Node) PoCUrl() string {
return n.pocUrlWithScheme("http", "")
}
func (n *Node) PoCUrlWithVersion(version string) string {
return n.pocUrlWithScheme("http", version)
}
func (n *Node) pocUrlWithScheme(scheme, version string) string {
if version == "" {
return fmt.Sprintf("%s://%s:%d%s", scheme, n.Host, n.PoCPort, n.PoCSegment)
}
return fmt.Sprintf("%s://%s:%d/%s%s", scheme, n.Host, n.PoCPort, version, n.PoCSegment)
}
type NodeWithState struct {
Node Node
State NodeState
}
// AdminState tracks administrative enable/disable status
type AdminState struct {
Enabled bool `json:"enabled"`
Epoch uint64 `json:"epoch"`
}
type NodeState struct {
IntendedStatus types.HardwareNodeStatus `json:"intended_status"`
CurrentStatus types.HardwareNodeStatus `json:"current_status"`
ReconcileInfo *ReconcileInfo `json:"reconcile_info,omitempty"`
cancelInFlightTask func()
PocIntendedStatus PocStatus `json:"poc_intended_status"`
PocCurrentStatus PocStatus `json:"poc_current_status"`
LockCount int `json:"lock_count"`
FailureReason string `json:"failure_reason"`
StatusTimestamp time.Time `json:"status_timestamp"`
AdminState AdminState `json:"admin_state"`
// Self-reported by the node. Informational only — do not use for authorization or capability gating.
MlNodeVersion string `json:"ml_node_version"`
// Epoch data for this node, keyed by model_id.
// We currently expect one item in each map.
// EpochMLNodes stores this node's own MLNodeInfo, not all epoch ML nodes.
EpochModels map[string]types.Model `json:"epoch_models"`
EpochMLNodes map[string]types.MLNodeInfo `json:"epoch_ml_nodes"`
PreservedModels map[string]bool `json:"preserved_models"`
}
func (s NodeState) MarshalJSON() ([]byte, error) {
type Alias NodeState
return json.Marshal(&struct {
IntendedStatus string `json:"intended_status"`
CurrentStatus string `json:"current_status"`
Alias
}{
IntendedStatus: s.IntendedStatus.String(),
CurrentStatus: s.CurrentStatus.String(),
Alias: (Alias)(s),
})
}
type ReconcileInfo struct {
Status types.HardwareNodeStatus `json:"status"`
PocStatus PocStatus `json:"poc_status"`
}
func (s *NodeState) UpdateStatusAt(time time.Time, status types.HardwareNodeStatus) {
s.CurrentStatus = status
s.StatusTimestamp = time
}
func (s *NodeState) UpdateStatusWithPocStatusNow(status types.HardwareNodeStatus, pocStatus PocStatus) {
s.UpdateStatusWithPocStatusAt(time.Now(), status, pocStatus)
}
func (s *NodeState) UpdateStatusWithPocStatusAt(time time.Time, status types.HardwareNodeStatus, pocStatus PocStatus) {
s.CurrentStatus = status
s.PocCurrentStatus = pocStatus
s.StatusTimestamp = time
}
func (s *NodeState) UpdateStatusNow(status types.HardwareNodeStatus) {
s.CurrentStatus = status
s.StatusTimestamp = time.Now()
}
func (s *NodeState) Failure(reason string) {
s.FailureReason = reason
s.UpdateStatusNow(types.HardwareNodeStatus_FAILED)
}
func (s *NodeState) IsOperational() bool {
return s.CurrentStatus != types.HardwareNodeStatus_FAILED
}
// ShouldBeOperational checks if node should be operational based on admin state and current epoch
func (s *NodeState) ShouldBeOperational(latestEpoch uint64, currentPhase types.EpochPhase) bool {
return ShouldBeOperational(s.AdminState, latestEpoch, currentPhase)
}
// ShouldContinueInference reports whether this node is in the active preserved
// snapshot for any of its models and should keep serving inference.
func (s *NodeState) ShouldContinueInference() bool {
return len(s.PreservedModels) > 0
}
func ShouldBeOperational(adminState AdminState, latestEpoch uint64, currentPhase types.EpochPhase) bool {
if adminState.Enabled {
if latestEpoch > adminState.Epoch {
return true
} else { // latestEpoch == adminState.Epoch
return currentPhase == types.InferencePhase
}
} else {
return adminState.Epoch >= latestEpoch
}
}
type NodeResponse struct {
Node Node `json:"node"`
State NodeState `json:"state"`
}
func NewBroker(chainBridge BrokerChainBridge, phaseTracker *chainphase.ChainPhaseTracker, participantInfo participant.CurrenParticipantInfo, callbackUrl string, clientFactory mlnodeclient.ClientFactory, configManager *apiconfig.ConfigManager) *Broker {
broker := &Broker{
highPriorityCommands: make(chan Command, 100),
lowPriorityCommands: make(chan Command, 10000),
nodes: make(map[string]*NodeWithState),
chainBridge: chainBridge,
phaseTracker: phaseTracker,
participantInfo: participantInfo,
callbackUrl: callbackUrl,
mlNodeClientFactory: clientFactory,
reconcileTrigger: make(chan struct{}, 1),
statusQueryTrigger: make(chan statusQuerySignal, 1),
configManager: configManager,
lockMap: make(map[string]lockEntry),
}
// Initialize NodeWorkGroup
broker.nodeWorkGroup = NewNodeWorkGroup()
go broker.processCommands()
go nodeSyncWorker(broker)
// Reconciliation is now triggered by OnNewBlockDispatcher
// go nodeReconciliationWorker(broker)
go nodeStatusQueryWorker(broker)
go broker.reconcilerLoop()
return broker
}
type statusQuerySignal struct {
BypassDebounce bool
}
func (b *Broker) TriggerStatusQuery(bypassDebounce bool) {
select {
case b.statusQueryTrigger <- statusQuerySignal{BypassDebounce: bypassDebounce}:
default: // Non-blocking send
}
}
func (b *Broker) GetChainBridge() BrokerChainBridge {
return b.chainBridge
}
func (b *Broker) GetPhaseTracker() *chainphase.ChainPhaseTracker {
return b.phaseTracker
}
func (b *Broker) LoadNodeToBroker(node *apiconfig.InferenceNodeConfig) chan NodeCommandResponse {
if node == nil {
return nil
}
cmd := NewRegisterNodeCommand(*node)
err := b.QueueMessage(cmd)
if err != nil {
logging.Error("Error loading node to broker", types.Nodes, "error", err)
panic(err)
// return nil
}
return cmd.Response
}
func nodeSyncWorker(broker *Broker) {
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
for range ticker.C {
logging.Debug("Syncing nodes", types.Nodes)
if err := broker.QueueMessage(NewSyncNodesCommand()); err != nil {
logging.Error("Error syncing nodes", types.Nodes, "error", err)
}
}
}
func (b *Broker) processCommands() {
for {
select {
case command := <-b.highPriorityCommands:
b.executeCommand(command)
default:
select {
case command := <-b.highPriorityCommands:
b.executeCommand(command)
case command := <-b.lowPriorityCommands:
b.executeCommand(command)
}
}
}
}
func (b *Broker) executeCommand(command Command) {
logging.Debug("Processing command", types.Nodes, "type", reflect.TypeOf(command).String())
switch command := command.(type) {
case LockAvailableNode:
b.lockAvailableNode(command)
case ReleaseNode:
b.releaseNode(command)
case RegisterNode:
command.Execute(b)
case RemoveNode:
command.Execute(b)
case UpdateNode:
command.Execute(b)
case GetNodesCommand:
command.Execute(b)
case SyncNodesCommand:
b.syncNodes()
case SetNodesActualStatusCommand:
command.Execute(b)
case SetNodeAdminStateCommand:
command.Execute(b)
case UpdateNodeHardwareCommand:
command.Execute(b)
case InferenceUpAllCommand:
command.Execute(b)
case StartPocCommand:
command.Execute(b)
case InitValidateCommand:
command.Execute(b)
case UpdateNodeResultCommand:
command.Execute(b)
default:
logging.Error("Unregistered command type", types.Nodes, "type", reflect.TypeOf(command).String())
}
}
type InvalidCommandError struct {
Message string
}
func (b *Broker) QueueMessage(command Command) error {
// Check validity of command. Primarily check all `Response` channels to make sure they
// support buffering, or else we could end up blocking the broker.
if command.GetResponseChannelCapacity() == 0 {
logging.Error("Message queued with unbuffered channel", types.Nodes, "command", reflect.TypeOf(command).String())
return errors.New("response channel must support buffering")
}
switch command.(type) {
case StartPocCommand, InitValidateCommand, InferenceUpAllCommand, UpdateNodeResultCommand, SetNodesActualStatusCommand, SetNodeAdminStateCommand, RegisterNode, RemoveNode, SyncNodesCommand:
b.highPriorityCommands <- command
default:
b.lowPriorityCommands <- command
}
return nil
}
func (b *Broker) NewNodeClient(node *Node) mlnodeclient.MLNodeClient {
version := b.configManager.GetCurrentNodeVersion()
return b.mlNodeClientFactory.CreateClient(b.pocUrlForNode(node, version), b.InferenceUrlForNode(node, version))
}
func (b *Broker) NewMLNodeHTTPClient(timeout time.Duration) *http.Client {
return b.mlNodeClientFactory.NewHTTPClient(timeout)
}
func (b *Broker) mlNodeScheme() string {
if b.configManager != nil {
return b.configManager.GetApiConfig().MLNodeTLS.Scheme()
}
return "http"
}
func (b *Broker) pocUrlForNode(node *Node, version string) string {
return node.pocUrlWithScheme(b.mlNodeScheme(), version)
}
func (b *Broker) InferenceUrlForNode(node *Node, version string) string {
return node.inferenceUrlWithScheme(b.mlNodeScheme(), version)
}
func (b *Broker) lockAvailableNode(command LockAvailableNode) {
leastBusyNode := b.getLeastBusyNode(command)
if leastBusyNode != nil {
b.mu.Lock()
leastBusyNode.State.LockCount++
b.mu.Unlock()
}
logging.Debug("Locked node", types.Nodes, "node", leastBusyNode)
if leastBusyNode == nil {
command.Response <- nil
} else {
command.Response <- &leastBusyNode.Node
}
}
func (b *Broker) getLeastBusyNode(command LockAvailableNode) *NodeWithState {
epochState := b.phaseTracker.GetCurrentEpochState()
if epochState.IsNilOrNotSynced() {
logging.Error("getLeastBusyNode. Cannot get least busy node, epoch state is empty", types.Nodes)
return nil
}
b.mu.RLock()
defer b.mu.RUnlock()
// Build skip set
skip := make(map[string]struct{}, len(command.SkipNodeIDs))
for _, id := range command.SkipNodeIDs {
if id != "" {
skip[id] = struct{}{}
}
}
var leastBusyNode *NodeWithState = nil
for _, node := range b.nodes {
if _, shouldSkip := skip[node.Node.Id]; shouldSkip {
logging.Info("Node skipped by LockAvailableNode skip list", types.Nodes, "node_id", node.Node.Id)
continue
}
// TODO: log some kind of a reason as to why the node is not available
if available, reason := b.nodeAvailable(node, command.Model, epochState.LatestEpoch.EpochIndex, epochState.CurrentPhase); available {
if leastBusyNode == nil || node.State.LockCount < leastBusyNode.State.LockCount {
leastBusyNode = node
}
} else {
logging.Info("Node not available", types.Nodes, "node_id", node.Node.Id, "reason", reason)
}
}
return leastBusyNode
}
type NodeNotAvailableReason = string
func (b *Broker) nodeAvailable(node *NodeWithState, neededModel string, currentEpoch uint64, currentPhase types.EpochPhase) (bool, NodeNotAvailableReason) {
if node.State.IntendedStatus != types.HardwareNodeStatus_INFERENCE {
return false, fmt.Sprintf("Node is not intended for INFERENCE at the moment: %s", node.State.IntendedStatus)
}
logging.Info("nodeAvailable. Node is intended for INFERENCE", types.Nodes, "nodeId", node.Node.Id, "intendedStatus", node.State.IntendedStatus)
if node.State.CurrentStatus != types.HardwareNodeStatus_INFERENCE {
return false, fmt.Sprintf("Node is not in INFERENCE state: %s", node.State.CurrentStatus)
}
logging.Info("nodeAvailable. Node is in INFERENCE state", types.Nodes, "nodeId", node.Node.Id)
if node.State.ReconcileInfo != nil {
return false, fmt.Sprintf("Node is currently reconciling: %s", node.State.ReconcileInfo.Status)
}
logging.Info("nodeAvailable. Node is not being reconciled, ReconcileInfo == nil", types.Nodes, "nodeId", node.Node.Id)
if node.State.LockCount >= node.Node.MaxConcurrent {
return false, fmt.Sprintf("Node is locked too many times: lockCount=%d, maxConcurrent=%d", node.State.LockCount, node.Node.MaxConcurrent)
}
logging.Info("nodeAvailable. Node is not locked too many times", types.Nodes, "nodeId", node.Node.Id, "lockCount", node.State.LockCount, "maxConcurrent", node.Node.MaxConcurrent)
// Check admin state using provided epoch and phase
if !node.State.ShouldBeOperational(currentEpoch, currentPhase) {
return false, fmt.Sprintf("Node is administratively disabled: currentEpoch=%v, currentPhase=%s, adminState = %v", currentEpoch, currentPhase, node.State.AdminState)
}
logging.Info("nodeAvailable. Node is not administratively enabled", types.Nodes, "nodeId", node.Node.Id, "adminState", node.State.AdminState)
_, found := node.State.EpochModels[neededModel]
if !found {
logging.Info("Node does not have neededModel", types.Nodes, "node_id", node.Node.Id, "neededModel", neededModel)
return false, fmt.Sprintf("Node does not have model %s", neededModel)
} else {
logging.Info("Node has neededModel", types.Nodes, "node_id", node.Node.Id, "neededModel", neededModel)
return true, ""
}
}
func (b *Broker) releaseNode(command ReleaseNode) {
b.mu.Lock()
node, ok := b.nodes[command.NodeId]
if ok {
node.State.LockCount--
}
b.mu.Unlock()
if !ok {
command.Response <- false
return
}
if !command.Outcome.IsSuccess() {
logging.Error("Node failed", types.Nodes, "node_id", command.NodeId, "reason", command.Outcome.GetMessage())
}
logging.Debug("Released node", types.Nodes, "node_id", command.NodeId)
command.Response <- true
}
var ErrNoNodesAvailable = errors.New("no nodes available for inference")
func LockNode[T any](
b *Broker,
model string,
action func(node *Node) (T, error),
) (T, error) {
var zero T
nodeChan := make(chan *Node, 2)
err := b.QueueMessage(LockAvailableNode{
Model: model,
Response: nodeChan,
})
if err != nil {
return zero, err
}
node := <-nodeChan
if node == nil {
return zero, ErrNoNodesAvailable
}
defer func() {
queueError := b.QueueMessage(ReleaseNode{
NodeId: node.Id,
Outcome: InferenceSuccess{},
Response: make(chan bool, 2),
})
if queueError != nil {
logging.Error("Error releasing node", types.Nodes, "error", queueError)
}
}()
return action(node)
}
// FIXME: Should return a copy! To avoid modifying state outside of the broker
func (b *Broker) GetNodes() ([]NodeResponse, error) {
command := NewGetNodesCommand()
err := b.QueueMessage(command)
if err != nil {
return nil, err
}
nodes := <-command.Response
if nodes == nil {
return nil, errors.New("Error getting nodes")
}
logging.Debug("Got nodes", types.Nodes, "size", len(nodes))
return nodes, nil
}
func (b *Broker) GetNodeByNodeNum(nodeNum uint64) (*Node, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
for _, nodeWithState := range b.nodes {
if nodeWithState.Node.NodeNum == nodeNum {
return &nodeWithState.Node, true
}
}
return nil, false
}
func (b *Broker) syncNodes() {
resp, err := b.chainBridge.GetHardwareNodes()
if err != nil {
logging.Error("[sync nodes]. Error getting nodes", types.Nodes, "error", err)
return
}
logging.Info("[sync nodes] Fetched chain nodes", types.Nodes, "size", len(resp.Nodes.HardwareNodes))
chainNodesMap := make(map[string]*types.HardwareNode)
for _, node := range resp.Nodes.HardwareNodes {
chainNodesMap[node.LocalId] = node
}
b.mu.RLock()
nodesCopy := make(map[string]*NodeWithState, len(b.nodes))
for id, node := range b.nodes {
nodesCopy[id] = node
}
b.mu.RUnlock()
logging.Info("[sync nodes] Local nodes", types.Nodes, "size", len(nodesCopy))
diff := b.calculateNodesDiff(chainNodesMap, nodesCopy)
logging.Info("[sync nodes] Hardware diff computed", types.Nodes, "diff", diff)
if len(diff.Removed) == 0 && len(diff.NewOrModified) == 0 {
logging.Info("[sync nodes] No diff to submit", types.Nodes)
} else {
logging.Info("[sync nodes] Submitting diff", types.Nodes)
if err = b.chainBridge.SubmitHardwareDiff(&diff); err != nil {
logging.Error("[sync nodes] Error submitting diff", types.Nodes, "error", err)
}
}
}
func (b *Broker) calculateNodesDiff(chainNodesMap map[string]*types.HardwareNode, localNodes map[string]*NodeWithState) types.MsgSubmitHardwareDiff {
var diff types.MsgSubmitHardwareDiff
diff.Creator = b.participantInfo.GetAddress()
for id, localNode := range localNodes {
localHWNode := convertInferenceNodeToHardwareNode(localNode, b.supportedNodeModels(localNode.Node.Models))
chainNode, exists := chainNodesMap[id]
if !exists {
diff.NewOrModified = append(diff.NewOrModified, localHWNode)
} else if !areHardwareNodesEqual(localHWNode, chainNode) {
diff.NewOrModified = append(diff.NewOrModified, localHWNode)
}
}
for id, chainNode := range chainNodesMap {
if _, exists := localNodes[id]; !exists {
diff.Removed = append(diff.Removed, chainNode)
}
}
return diff
}
// convertInferenceNodeToHardwareNode converts a local InferenceNode into a HardwareNode.
func convertInferenceNodeToHardwareNode(in *NodeWithState, nodeModels map[string]ModelArgs) *types.HardwareNode {
node := in.Node
hardware := make([]*types.Hardware, 0, len(node.Hardware))
for _, hw := range node.Hardware {
hardware = append(hardware, &types.Hardware{
Type: hw.Type,
Count: hw.Count,
})
}
modelNames := make([]string, 0)
for model := range nodeModels {
modelNames = append(modelNames, model)
}
// sort models names to make sure they will be in same order every time
sort.Strings(modelNames)
return &types.HardwareNode{
LocalId: node.Id,
Status: in.State.CurrentStatus,
Hardware: hardware,
Models: modelNames,
Host: node.Host,
Port: strconv.Itoa(node.PoCPort),
Version: in.State.MlNodeVersion,
}
}
// areHardwareNodesEqual performs a field-by-field comparison between two HardwareNodes.
func areHardwareNodesEqual(a, b *types.HardwareNode) bool {
// Compare each field that determines whether the node has changed.
if a.LocalId != b.LocalId {
return false
}
if a.Status != b.Status {
return false
}
if len(a.Hardware) != len(b.Hardware) {
return false
}
if !hardwareEquals(a, b) {
return false
}
if a.Version != b.Version {
return false
}
return true
}
func hardwareEquals(a *types.HardwareNode, b *types.HardwareNode) bool {
if len(a.Models) != len(b.Models) {
return false
}
aModels := make([]string, len(a.Models))
bModels := make([]string, len(b.Models))
copy(aModels, a.Models)
copy(bModels, b.Models)
sort.Strings(aModels)
sort.Strings(bModels)
for i := range aModels {
if aModels[i] != bModels[i] {
return false
}
}
aHardware := make([]*types.Hardware, len(a.Hardware))
bHardware := make([]*types.Hardware, len(b.Hardware))
copy(aHardware, a.Hardware)
copy(bHardware, b.Hardware)
sort.Slice(aHardware, func(i, j int) bool {
if aHardware[i].Type == aHardware[j].Type {
return aHardware[i].Count < aHardware[j].Count
}
return aHardware[i].Type < aHardware[j].Type
})
sort.Slice(bHardware, func(i, j int) bool {
if bHardware[i].Type == bHardware[j].Type {
return bHardware[i].Count < bHardware[j].Count
}
return bHardware[i].Type < bHardware[j].Type
})
for i := range aHardware {
if aHardware[i].Type != bHardware[i].Type || aHardware[i].Count != bHardware[i].Count {
return false
}
}
return true
}
type pocParams struct {
startPoCBlockHeight int64
startPoCBlockHash string
models map[string]apiconfig.PoCModelConfigCache
pocStrongerRng bool
}
const reconciliationInterval = 30 * time.Second
// Timeouts for node health checks used in queryNodeStatus
const (
nodeStatusRequestTimeout = 5 * time.Second
inferenceHealthRequestTimeout = 5 * time.Second
// statusScanMinInterval enforces a minimal delay between consecutive full scans
// in nodeStatusQueryWorker, covering both manual and timer triggers.
statusScanMinInterval = 2 * time.Second
)
func (b *Broker) TriggerReconciliation() {
select {
case b.reconcileTrigger <- struct{}{}:
default:
}
}
func (b *Broker) reconcilerLoop() {
ticker := time.NewTicker(reconciliationInterval)
defer ticker.Stop()
for {
select {
case <-b.reconcileTrigger:
b.reconcileIfSynced("Reconciliation triggered manually")
case <-ticker.C:
b.reconcileIfSynced("Reconciliation triggered by timer")
// Check for version changes and refresh clients if needed
b.checkAndRefreshClientsIfNeeded()
b.evictExpiredLocks()
}
}
}
type VersionHealthReport struct {
IsAlive bool `json:"is_alive"`
Error string `json:"error,omitempty"`
}
func (b *Broker) CheckVersionHealth(version string) map[string]VersionHealthReport {
b.mu.RLock()
nodeIds := make([]string, 0, len(b.nodes))
for nodeId := range b.nodes {
nodeIds = append(nodeIds, nodeId)
}
b.mu.RUnlock()
reports := make(map[string]VersionHealthReport)
var wg sync.WaitGroup
var reportsMu sync.Mutex
for _, nodeId := range nodeIds {
wg.Add(1)
go func(nodeId string) {
defer wg.Done()
worker, exists := b.nodeWorkGroup.GetWorker(nodeId)
report := VersionHealthReport{}
if !exists {
report.Error = "worker not found"
} else {
alive, err := worker.CheckClientVersionAlive(version, b.mlNodeClientFactory)
report.IsAlive = alive
if err != nil {
report.Error = err.Error()
}
}
reportsMu.Lock()
reports[nodeId] = report
reportsMu.Unlock()
}(nodeId)
}
wg.Wait()
return reports
}
// checkAndRefreshClientsIfNeeded checks if the MLNode version has changed and refreshes all clients if needed
func (b *Broker) checkAndRefreshClientsIfNeeded() {
if b.configManager.ShouldRefreshClients() {
currentVersion := b.configManager.GetCurrentNodeVersion()
lastUsedVersion := b.configManager.GetLastUsedVersion()
logging.Info("MLNode version change detected - immediately refreshing all clients", types.Nodes,
"oldVersion", lastUsedVersion, "newVersion", currentVersion)
// Immediately refresh all worker clients (no queuing delay)
b.mu.RLock()
workerIds := make([]string, 0, len(b.nodes))
for nodeId := range b.nodes {
workerIds = append(workerIds, nodeId)
}
b.mu.RUnlock()
// Immediately refresh all workers
refreshedCount := 0
for _, nodeId := range workerIds {
worker, exists := b.nodeWorkGroup.GetWorker(nodeId)
if exists {
worker.RefreshClientImmediate(lastUsedVersion, currentVersion)
refreshedCount++
}
}
logging.Info("Immediately refreshed all MLNode clients", types.Nodes,
"oldVersion", lastUsedVersion, "newVersion", currentVersion, "count", refreshedCount)
// Update last used version (fire and forget - if this fails, we'll retry next cycle)
if err := b.configManager.SetLastUsedVersion(currentVersion); err != nil {
logging.Warn("Failed to update last used version", types.Config, "error", err)
}
} else {
// Ensure lastUsedVersion is set if it's empty (first time initialization)
if b.configManager.GetLastUsedVersion() == "" {
currentVersion := b.configManager.GetCurrentNodeVersion()
if currentVersion != "" {
if err := b.configManager.SetLastUsedVersion(currentVersion); err != nil {
logging.Warn("Failed to initialize last used version", types.Config, "error", err)
}
}
}
}
upgradeVersion := b.configManager.GetUpgradePlan().NodeVersion
if upgradeVersion != "" {
reports := b.CheckVersionHealth(upgradeVersion)
for nodeId, report := range reports {
if report.Error != "" {
logging.Warn("Failed to check MLNode version in upgrade plan", types.Nodes, "node_id", nodeId, "error", report.Error)
} else if !report.IsAlive {
logging.Warn("MLNode version in upgrade plan is not alive", types.Nodes, "node_id", nodeId)
} else {
logging.Debug("MLNode version in upgrade plan is alive", types.Nodes, "node_id", nodeId)
}
}
}
}
func (b *Broker) reconcileIfSynced(triggerMsg string) {
epochPhaseInfo := b.phaseTracker.GetCurrentEpochState()
if epochPhaseInfo.IsNilOrNotSynced() {
logging.Warn("Reconciliation triggered while epoch phase info is not synced. Skipping", types.Nodes)
return
}
logging.Info(triggerMsg, types.Nodes, "blockHeight", epochPhaseInfo.CurrentBlock.Height)
b.reconcile(*epochPhaseInfo)
}
func (b *Broker) reconcile(epochState chainphase.EpochState) {
blockHeight := epochState.CurrentBlock.Height
// Phase 1: Cancel outdated tasks
nodesToCancel := make(map[string]func())
b.mu.RLock()
for id, node := range b.nodes {
if node.State.ReconcileInfo != nil &&
(node.State.ReconcileInfo.Status != node.State.IntendedStatus ||
node.State.ReconcileInfo.PocStatus != node.State.PocIntendedStatus) {
if node.State.cancelInFlightTask != nil {
nodesToCancel[id] = node.State.cancelInFlightTask
}
}
}
b.mu.RUnlock()
for id, cancel := range nodesToCancel {
logging.Info("Cancelling outdated task for node", types.Nodes, "node_id", id, "blockHeight", blockHeight)
cancel()
b.mu.Lock()
if node, ok := b.nodes[id]; ok {
node.State.ReconcileInfo = nil
node.State.cancelInFlightTask = nil
}
b.mu.Unlock()