net-mesh 0.21.0

High-performance, schema-agnostic, backend-agnostic event bus
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
//! Daemon placement scheduler.
//!
//! Connects `CapabilityFilter` requirements to `CapabilityIndex` queries
//! to decide where to run a daemon. Prefers local placement, falls back
//! to the least-loaded candidate.

use std::cmp::Ordering;
use std::sync::Arc;

use crate::adapter::net::behavior::capability::{CapabilityFilter, CapabilityIndex, CapabilitySet};
use crate::adapter::net::behavior::placement::{
    tie_break_compare, Artifact, LegacyPlacement, PlacementFilter, ResourceAxis, TieBreakContext,
};
use crate::adapter::net::subprotocol::SubprotocolRegistry;

/// Why a particular node was chosen for placement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlacementReason {
    /// Only node matching the filter.
    OnlyCandidate,
    /// Preferred because it's the local node.
    LocalPreferred,
    /// First candidate from the index (tie-breaking).
    FirstMatch,
    /// Explicitly pinned to a specific node.
    Pinned,
    /// Highest-scoring candidate from a `&dyn PlacementFilter`,
    /// ties broken by the §7-LOCKED RTT → free-resource → lex-NodeId
    /// chain. Stamped by `Scheduler::select_*` callers (Phase G).
    BestScore,
}

/// Result of a placement decision.
#[derive(Debug, Clone)]
pub struct PlacementDecision {
    /// Selected node ID.
    pub node_id: u64,
    /// Why this node was chosen.
    pub reason: PlacementReason,
}

/// Errors from scheduling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchedulerError {
    /// No nodes match the capability filter.
    NoCandidate,
    /// Capability index unavailable.
    IndexUnavailable,
}

impl std::fmt::Display for SchedulerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoCandidate => write!(f, "no nodes match capability requirements"),
            Self::IndexUnavailable => write!(f, "capability index unavailable"),
        }
    }
}

impl std::error::Error for SchedulerError {}

/// Daemon placement scheduler.
///
/// Queries the `CapabilityIndex` to find nodes matching a daemon's
/// requirements. Prefers local placement when possible.
pub struct Scheduler {
    /// Reference to the shared capability index.
    capability_index: Arc<CapabilityIndex>,
    /// This node's ID (for local preference).
    local_node_id: u64,
    /// This node's capabilities (for fast local check).
    local_caps: CapabilitySet,
}

impl Scheduler {
    /// Create a new scheduler.
    pub fn new(
        capability_index: Arc<CapabilityIndex>,
        local_node_id: u64,
        local_caps: CapabilitySet,
    ) -> Self {
        Self {
            capability_index,
            local_node_id,
            local_caps,
        }
    }

    /// Check if a daemon can run locally.
    #[inline]
    pub fn can_run_locally(&self, filter: &CapabilityFilter) -> bool {
        filter.matches(&self.local_caps)
    }

    /// Place a daemon given its capability requirements.
    ///
    /// Forwarder over [`Self::place_with_locality`] with
    /// `local_drained = false`. Callers that know the local
    /// node's drain state should call `place_with_locality`
    /// directly so the LocalPreferred fast-path can be gated.
    pub fn place(&self, filter: &CapabilityFilter) -> Result<PlacementDecision, SchedulerError> {
        self.place_with_locality(filter, false)
    }

    /// Like [`Self::place`], but accepts an explicit
    /// `local_drained` signal. The LocalPreferred fast-path is
    /// gated on `!local_drained` so a caller in mid-shutdown or
    /// operator-drained state can route fresh placements off the
    /// local node instead of piling them on a node that's about
    /// to disappear. The scheduler stays stateless w.r.t.
    /// node-lifecycle — the caller (which knows about maintenance
    /// state, drain status, and process lifecycle) supplies the
    /// bit.
    ///
    /// Strategy:
    /// 1. If local node matches AND `!local_drained`, prefer local
    ///    (zero network hop).
    /// 2. Otherwise, query the capability index for candidates.
    /// 3. Return the first match (future: least-loaded via LoadBalancer).
    pub fn place_with_locality(
        &self,
        filter: &CapabilityFilter,
        local_drained: bool,
    ) -> Result<PlacementDecision, SchedulerError> {
        // Fast path: try local only when not drained.
        if !local_drained && self.can_run_locally(filter) {
            return Ok(PlacementDecision {
                node_id: self.local_node_id,
                reason: PlacementReason::LocalPreferred,
            });
        }

        // Query the index for matching nodes. When drained, also
        // strip the local node from the candidate pool — a drained
        // node shouldn't receive work via either path; skipping the
        // fast-path alone would let the index query surface local
        // anyway when it's also published there.
        let candidates: Vec<u64> = if local_drained {
            self.capability_index
                .query(filter)
                .into_iter()
                .filter(|&id| id != self.local_node_id)
                .collect()
        } else {
            self.capability_index.query(filter)
        };

        if candidates.is_empty() {
            return Err(SchedulerError::NoCandidate);
        }

        if candidates.len() == 1 {
            return Ok(PlacementDecision {
                node_id: candidates[0],
                reason: PlacementReason::OnlyCandidate,
            });
        }

        // Multiple candidates — pick first (future: load-aware)
        Ok(PlacementDecision {
            node_id: candidates[0],
            reason: PlacementReason::FirstMatch,
        })
    }

    /// Query candidate node IDs matching a capability filter.
    pub fn query_candidates(&self, filter: &CapabilityFilter) -> Vec<u64> {
        self.capability_index.query(filter)
    }

    /// Place a daemon on a specific node (pinning).
    pub fn pin(&self, node_id: u64) -> PlacementDecision {
        PlacementDecision {
            node_id,
            reason: PlacementReason::Pinned,
        }
    }

    /// Find nodes that support a given subprotocol.
    ///
    /// Queries the capability index for nodes advertising the tag
    /// `subprotocol:0x{id:04x}`. Returns node IDs of all matches.
    pub fn find_subprotocol_nodes(&self, subprotocol_id: u16) -> Vec<u64> {
        let filter = SubprotocolRegistry::capability_filter_for(subprotocol_id);
        self.capability_index.query(&filter)
    }

    /// Find nodes capable of receiving a daemon migration.
    ///
    /// Queries for nodes advertising the migration subprotocol tag
    /// (`subprotocol:0x0500`), combined with the daemon's own capability
    /// requirements. Excludes the source node.
    pub fn find_migration_targets(
        &self,
        daemon_filter: &CapabilityFilter,
        source_node: u64,
    ) -> Vec<u64> {
        // Build a combined filter: must support migration AND daemon requirements.
        // The migration-subprotocol tag is constant — hoist it out of
        // the format! per-call (pre-fix this allocated a tag string
        // on every find_migration_targets invocation).
        const MIGRATION_TAG: &str = "subprotocol:0x0500";
        debug_assert_eq!(
            MIGRATION_TAG,
            format!("subprotocol:{:#06x}", super::SUBPROTOCOL_MIGRATION),
            "hoisted MIGRATION_TAG must match SUBPROTOCOL_MIGRATION format",
        );
        let combined = daemon_filter.clone().require_tag(MIGRATION_TAG.to_string());

        self.capability_index
            .query(&combined)
            .into_iter()
            .filter(|&node_id| node_id != source_node)
            .collect()
    }

    /// Place a daemon for migration — find the best target node.
    ///
    /// Combines the daemon's capability requirements with the migration
    /// subprotocol tag to find eligible target nodes. Excludes the source.
    /// Prefers local node if eligible, otherwise first match.
    pub fn place_migration(
        &self,
        daemon_filter: &CapabilityFilter,
        source_node: u64,
    ) -> Result<PlacementDecision, SchedulerError> {
        let candidates = self.find_migration_targets(daemon_filter, source_node);

        if candidates.is_empty() {
            return Err(SchedulerError::NoCandidate);
        }

        // Prefer local if it's a candidate (and not the source)
        if self.local_node_id != source_node && candidates.contains(&self.local_node_id) {
            return Ok(PlacementDecision {
                node_id: self.local_node_id,
                reason: PlacementReason::LocalPreferred,
            });
        }

        if candidates.len() == 1 {
            return Ok(PlacementDecision {
                node_id: candidates[0],
                reason: PlacementReason::OnlyCandidate,
            });
        }

        Ok(PlacementDecision {
            node_id: candidates[0],
            reason: PlacementReason::FirstMatch,
        })
    }

    /// Phase G slice 8 of `CAPABILITY_SYSTEM_PLAN.md` — v2 of
    /// [`Self::place_migration`] using the `&dyn PlacementFilter`
    /// machinery. Uses [`LegacyPlacement::permissive`] against the
    /// scheduler's own `CapabilityIndex` so observable eligibility
    /// matches v1 (any migration-capable, daemon-filter-compatible
    /// node is eligible), but ranking flows through
    /// [`Self::select_migration_target`] and the LOCKED §7
    /// tie-breaker.
    ///
    /// **Default migration path.** `Orchestrator::start_migration_auto`
    /// (in `orchestrator.rs`) calls this method, so any auto-target
    /// migration in the substrate runs through v2 plumbing. The
    /// legacy [`Self::place_migration`] is kept around for callers
    /// who explicitly want v1's `LocalPreferred` / `FirstMatch`
    /// behavior (e.g. tests pinning the legacy contract); production
    /// code should use this v2 entry point.
    ///
    /// The returned `PlacementDecision` carries
    /// [`PlacementReason::BestScore`] so observers can distinguish
    /// the v2 path in telemetry.
    ///
    /// `tie_break.rtt_lookup` is `None` here — the substrate-level
    /// scheduler has no RTT data plumbed in by default. Operators
    /// who want RTT-aware tie-breaking should call
    /// [`Self::select_migration_target`] directly with a populated
    /// `TieBreakContext`; this convenience wrapper falls through to
    /// step 3 (lex NodeId) without RTT data.
    pub fn place_migration_v2(
        &self,
        daemon_filter: &CapabilityFilter,
        source_node: u64,
    ) -> Result<PlacementDecision, SchedulerError> {
        // CR-21 + N-7: the LocalPreferred fast-path now lives inside
        // `select_migration_target` so callers feeding their own
        // `TieBreakContext` (the doc-comment directs RTT-aware
        // operators at that entry point) get the same fix.
        // `place_migration_v2` becomes a thin wrapper that derives
        // the proper `PlacementReason` from whether the chosen node
        // is the local one — keeping the v1 telemetry distinction
        // alive.
        let placement = LegacyPlacement::permissive(&self.capability_index);
        let tie_break = TieBreakContext {
            rtt_lookup: None,
            index: &self.capability_index,
            resource_axis: ResourceAxis::Compute,
        };
        // Empty required / optional caps: the migration artifact
        // carries its hard-constraint shape via `daemon_filter`
        // (which narrows the candidate pool inside
        // `find_migration_targets`). Splitting hard constraints
        // between the filter and the artifact would double-count
        // them; the artifact stays empty so the
        // `LegacyPlacement::permissive` shim's "any eligible
        // candidate scores 1.0" semantics hold.
        let empty = CapabilitySet::default();
        let artifact = Artifact::Daemon {
            daemon_id: [0u8; 32],
            required: &empty,
            optional: &empty,
        };
        let node_id = self
            .select_migration_target(
                &artifact,
                daemon_filter,
                source_node,
                &placement,
                &tie_break,
            )
            .ok_or(SchedulerError::NoCandidate)?;
        let reason = if node_id == self.local_node_id && self.local_node_id != source_node {
            PlacementReason::LocalPreferred
        } else {
            PlacementReason::BestScore
        };
        Ok(PlacementDecision { node_id, reason })
    }

    /// Phase G slice 1 of `CAPABILITY_SYSTEM_PLAN.md`. Select the
    /// best migration target for `artifact` from the candidates
    /// returned by [`Self::find_migration_targets`], scored via
    /// `&dyn PlacementFilter` with ties broken by the §7-LOCKED
    /// three-step ordering (RTT → free-resource → lex NodeId).
    ///
    /// `daemon_filter` narrows the candidate pool BEFORE scoring —
    /// it's the legacy `CapabilityFilter` plumbed through
    /// `find_migration_targets` so existing callsites keep
    /// working. `placement` runs against each surviving candidate;
    /// any candidate scoring `None` is excluded (hard veto).
    ///
    /// `tie_break` carries the inputs the comparator reads (RTT
    /// closure + capability index + resource axis). Pass a
    /// `TieBreakContext { rtt_lookup: None, ... }` to fall through
    /// to step 3 (lex NodeId) when no proximity data is available.
    ///
    /// LocalPreferred fast-path: when the scheduler's
    /// `local_node_id` is in the eligible-candidate pool AND isn't
    /// the migration source, the local node is returned without
    /// scoring. CR-21 introduced this for `place_migration_v2`;
    /// N-7 extended it here so RTT-aware operators (the
    /// doc-recommended callers of this entry point) get the same
    /// network-hop avoidance.
    ///
    /// Returns the highest-scoring candidate's node id, or `None`
    /// when every candidate is vetoed (or the candidate list was
    /// empty to begin with).
    pub fn select_migration_target(
        &self,
        artifact: &Artifact<'_>,
        daemon_filter: &CapabilityFilter,
        source_node: u64,
        placement: &dyn PlacementFilter,
        tie_break: &TieBreakContext<'_>,
    ) -> Option<u64> {
        let candidates = self.find_migration_targets(daemon_filter, source_node);
        if candidates.is_empty() {
            return None;
        }
        // N-7: LocalPreferred fast-path. CR-21 inlined this into
        // `place_migration_v2`, but the doc-comment explicitly
        // directs RTT-aware operators to call this method directly
        // — pre-fix they silently lost the fast-path and the
        // smallest-NodeId remote would beat the local on
        // `LegacyPlacement::permissive` tie-breaks. Apply the
        // short-circuit here so both entry points behave
        // identically.
        if self.local_node_id != source_node && candidates.contains(&self.local_node_id) {
            // Score local through the supplied PlacementFilter
            // FIRST so a filter that hard-vetoes local (returns
            // None for local, Some(_) only for remotes) can
            // actually veto. Pre-fix this branch short-circuited
            // unconditionally and silently ignored the filter —
            // the strict-veto operator could never keep work off
            // a local that the substrate decided to prefer. If
            // local scores Some(_), keep the fast-path; otherwise
            // fall through to the regular tie-breaker.
            if placement
                .placement_score(&self.local_node_id, artifact)
                .is_some()
            {
                return Some(self.local_node_id);
            }
        }
        Self::pick_best_candidate(candidates, artifact, placement, tie_break)
    }

    /// Phase G slice 3 of `CAPABILITY_SYSTEM_PLAN.md`. Select the
    /// best node for placing a new group member (replica / fork /
    /// standby), scored via `&dyn PlacementFilter` with the same
    /// §7-LOCKED tie-breaker as
    /// [`Self::select_migration_target`].
    ///
    /// `requirements` filters the candidate pool via the legacy
    /// `CapabilityFilter` path (matches today's
    /// `Scheduler::query_candidates` behavior); `exclude` is a
    /// set of NodeIds to skip — used by replica groups for
    /// best-effort spread (don't pick a node already running a
    /// member). `placement` scores the survivors; ties broken by
    /// `tie_break`.
    ///
    /// Returns `None` when every candidate is excluded or vetoed.
    pub fn select_member_node(
        &self,
        artifact: &Artifact<'_>,
        requirements: &CapabilityFilter,
        exclude: &std::collections::HashSet<u64>,
        placement: &dyn PlacementFilter,
        tie_break: &TieBreakContext<'_>,
    ) -> Option<u64> {
        let candidates = self
            .query_candidates(requirements)
            .into_iter()
            .filter(|n| !exclude.contains(n));
        Self::pick_best_candidate(candidates, artifact, placement, tie_break)
    }

    /// Phase G slice 3. Select the standby member that should be
    /// promoted to active. Same shape as
    /// [`Self::select_member_node`] without the exclusion-set
    /// concept (promotion is over the existing standby pool, not
    /// a fresh placement decision).
    ///
    /// `candidates` is the standby roster — typically the live
    /// `StandbyGroup`'s `members` projected to `Vec<u64>`.
    pub fn select_promotion_target(
        &self,
        candidates: Vec<u64>,
        artifact: &Artifact<'_>,
        placement: &dyn PlacementFilter,
        tie_break: &TieBreakContext<'_>,
    ) -> Option<u64> {
        Self::pick_best_candidate(candidates, artifact, placement, tie_break)
    }

    /// Shared scoring + tie-breaking core. Used by
    /// [`Self::select_migration_target`],
    /// [`Self::select_member_node`], and
    /// [`Self::select_promotion_target`].
    ///
    /// Filter-vetoed (`None`-scoring) candidates are dropped;
    /// survivors sort highest-score-first with the §7-LOCKED
    /// tie-breaker resolving equal scores. Returns the best
    /// candidate's NodeId, or `None` when every candidate vetoes /
    /// the input is empty.
    fn pick_best_candidate<I: IntoIterator<Item = u64>>(
        candidates: I,
        artifact: &Artifact<'_>,
        placement: &dyn PlacementFilter,
        tie_break: &TieBreakContext<'_>,
    ) -> Option<u64> {
        // CR-6: drop NaN scores at the boundary. `StandardPlacement`
        // clamps NaN in `compose_axis_scores`, but FFI-registered
        // filters resolved via `placement_registry` are free to
        // return raw `Some(f32::NAN)` (JS `NaN` round-trips
        // trivially through napi; Python f64 NaN through pyo3).
        // A NaN candidate compares `Equal` to everything, so
        // `Vec::sort_by` over a non-total ordering produces
        // *undefined* placement order — different runs would pick
        // different winners. Treat NaN as a hard veto (drop the
        // candidate) so the contract is enforceable at the
        // boundary, matching the StandardPlacement clamp behavior.
        // Find the max instead of sorting and taking the first
        // element — O(N) vs O(N log N) for the N=many-candidates case
        // that shows up in placement decisions over a large
        // capability index. Semantics match the previous sort: the
        // comparator returns `Greater` when `(a, sa)` should win over
        // `(b, sb)`, which is the contract `max_by` consumes.
        //
        // - Score: `sa.partial_cmp(sb)` so a's larger finite score is
        //   `Greater` and `max_by` keeps a.
        // - Tie-break: when scores are equal, `tie_break_compare(b,
        //   a, tie_break)` is inverted relative to the legacy sort's
        //   `tie_break_compare(a, b, tie_break)` because `max_by`'s
        //   "greater means winner" is the opposite of `sort_by`'s
        //   "less means earlier." NaN is no longer reachable here
        //   (filtered above) so `partial_cmp.unwrap_or(Equal)` is a
        //   safety belt only — a strict total order is in force.
        //
        // Pinned by `pick_best_candidate_drops_nan_scores` (tie-break
        // direction) and the BestScore tests in this module.
        candidates
            .into_iter()
            .filter_map(|n| placement.placement_score(&n, artifact).map(|s| (n, s)))
            .filter(|(_, s)| s.is_finite())
            .max_by(|(a, sa), (b, sb)| {
                sa.partial_cmp(sb)
                    .unwrap_or(Ordering::Equal)
                    .then_with(|| tie_break_compare(*b, *a, tie_break))
            })
            .map(|(n, _)| n)
    }
}

impl std::fmt::Debug for Scheduler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scheduler")
            .field("local_node_id", &format!("{:#x}", self.local_node_id))
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapter::net::behavior::capability::{
        CapabilityAnnouncement, GpuInfo, GpuVendor, HardwareCapabilities,
    };

    fn make_index_with_nodes(nodes: Vec<(u64, CapabilitySet)>) -> Arc<CapabilityIndex> {
        let index = CapabilityIndex::new();
        let eid = crate::adapter::net::identity::EntityId::from_bytes([0u8; 32]);
        for (node_id, caps) in nodes {
            let ad = CapabilityAnnouncement::new(node_id, eid.clone(), 1, caps);
            index.index(ad);
        }
        Arc::new(index)
    }

    fn caps_with_gpu() -> CapabilitySet {
        let gpu = GpuInfo {
            vendor: GpuVendor::Nvidia,
            model: "test".into(),
            vram_gb: 8,
            compute_units: 0,
            tensor_cores: 0,
            fp16_tflops_x10: 0,
        };
        CapabilitySet::new().with_hardware(HardwareCapabilities::new().with_gpu(gpu))
    }

    fn caps_no_gpu() -> CapabilitySet {
        CapabilitySet::new()
    }

    #[test]
    fn test_local_preferred() {
        let local_caps = caps_no_gpu();
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index, 0x1111, local_caps);

        // Empty filter = runs anywhere, including local
        let decision = scheduler.place(&CapabilityFilter::default()).unwrap();
        assert_eq!(decision.node_id, 0x1111);
        assert_eq!(decision.reason, PlacementReason::LocalPreferred);
    }

    #[test]
    fn test_remote_when_local_insufficient() {
        let local_caps = caps_no_gpu(); // no GPU
        let remote_caps = caps_with_gpu();
        let index = make_index_with_nodes(vec![(0x2222, remote_caps)]);
        let scheduler = Scheduler::new(index, 0x1111, local_caps);

        let filter = CapabilityFilter::new().require_gpu();
        let decision = scheduler.place(&filter).unwrap();
        assert_eq!(decision.node_id, 0x2222);
        assert_eq!(decision.reason, PlacementReason::OnlyCandidate);
    }

    #[test]
    fn test_no_candidate() {
        let local_caps = caps_no_gpu();
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index, 0x1111, local_caps);

        let filter = CapabilityFilter::new().require_gpu();
        assert_eq!(
            scheduler.place(&filter).unwrap_err(),
            SchedulerError::NoCandidate
        );
    }

    #[test]
    fn test_pin() {
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let decision = scheduler.pin(0x9999);
        assert_eq!(decision.node_id, 0x9999);
        assert_eq!(decision.reason, PlacementReason::Pinned);
    }

    #[test]
    fn test_can_run_locally() {
        let local_caps = caps_with_gpu();
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index, 0x1111, local_caps);

        assert!(scheduler.can_run_locally(&CapabilityFilter::new().require_gpu()));
        assert!(scheduler.can_run_locally(&CapabilityFilter::default()));
    }

    /// Local node has matching caps + a remote candidate also
    /// matches. The drained-local case skips the LocalPreferred
    /// fast-path and routes to the remote so a node mid-shutdown
    /// or operator-drained doesn't keep absorbing new daemons.
    #[test]
    fn place_with_locality_skips_local_when_drained() {
        let index =
            make_index_with_nodes(vec![(0x1111, caps_with_gpu()), (0x2222, caps_with_gpu())]);
        let scheduler = Scheduler::new(index, 0x1111, caps_with_gpu());
        let filter = CapabilityFilter::new().require_gpu();
        let decision = scheduler.place_with_locality(&filter, true).unwrap();
        assert_ne!(
            decision.node_id, 0x1111,
            "drained local must not win the placement"
        );
        assert_eq!(decision.node_id, 0x2222);
    }

    /// Baseline: non-drained local still takes the LocalPreferred
    /// fast-path. Confirms the new method's default behavior
    /// matches the existing `place()` semantics.
    #[test]
    fn place_with_locality_picks_local_when_not_drained() {
        let index =
            make_index_with_nodes(vec![(0x1111, caps_with_gpu()), (0x2222, caps_with_gpu())]);
        let scheduler = Scheduler::new(index, 0x1111, caps_with_gpu());
        let filter = CapabilityFilter::new().require_gpu();
        let decision = scheduler.place_with_locality(&filter, false).unwrap();
        assert_eq!(decision.node_id, 0x1111);
        assert_eq!(decision.reason, PlacementReason::LocalPreferred);
    }

    /// Drained-local plus no remote candidate in the capability
    /// index surfaces `NoCandidate` rather than silently
    /// returning the drained local. The local node is not in
    /// the index here — the substrate publishes its own caps
    /// separately — so skipping the fast-path leaves an empty
    /// candidate pool.
    #[test]
    fn place_with_locality_returns_no_candidate_when_drained_and_no_remote() {
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index, 0x1111, caps_with_gpu());
        let filter = CapabilityFilter::new().require_gpu();
        let err = scheduler
            .place_with_locality(&filter, true)
            .expect_err("drained local with no remote must fail closed");
        assert_eq!(err, SchedulerError::NoCandidate);
    }

    fn caps_with_migration_tag() -> CapabilitySet {
        CapabilitySet::new().add_tag("subprotocol:0x0500")
    }

    #[test]
    fn test_find_migration_targets() {
        let index = make_index_with_nodes(vec![
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
            (0x4444, caps_no_gpu()), // no migration tag
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let targets = scheduler.find_migration_targets(&CapabilityFilter::default(), 0x1111);
        assert_eq!(targets.len(), 2);
        assert!(targets.contains(&0x2222));
        assert!(targets.contains(&0x3333));
    }

    #[test]
    fn test_find_migration_targets_excludes_source() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()), // source
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let targets = scheduler.find_migration_targets(&CapabilityFilter::default(), 0x1111);
        assert_eq!(targets.len(), 1);
        assert_eq!(targets[0], 0x2222);
    }

    #[test]
    fn test_place_migration() {
        let index = make_index_with_nodes(vec![(0x2222, caps_with_migration_tag())]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let decision = scheduler
            .place_migration(&CapabilityFilter::default(), 0x1111)
            .unwrap();
        assert_eq!(decision.node_id, 0x2222);
        assert_eq!(decision.reason, PlacementReason::OnlyCandidate);
    }

    #[test]
    fn test_place_migration_no_targets() {
        let index = make_index_with_nodes(vec![
            (0x2222, caps_no_gpu()), // no migration tag
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let err = scheduler
            .place_migration(&CapabilityFilter::default(), 0x1111)
            .unwrap_err();
        assert_eq!(err, SchedulerError::NoCandidate);
    }

    #[test]
    fn test_place_migration_prefers_local() {
        let local_caps = caps_with_migration_tag();
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0x1111, local_caps);

        // Source is 0x3333, so local (0x1111) is a valid target
        let decision = scheduler
            .place_migration(&CapabilityFilter::default(), 0x3333)
            .unwrap();
        assert_eq!(decision.node_id, 0x1111);
        assert_eq!(decision.reason, PlacementReason::LocalPreferred);
    }

    #[test]
    fn test_find_subprotocol_nodes() {
        let index = make_index_with_nodes(vec![
            (0x2222, CapabilitySet::new().add_tag("subprotocol:0x0400")),
            (0x3333, CapabilitySet::new().add_tag("subprotocol:0x0500")),
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let causal_nodes = scheduler.find_subprotocol_nodes(0x0400);
        assert_eq!(causal_nodes.len(), 1);
        assert_eq!(causal_nodes[0], 0x2222);

        let migration_nodes = scheduler.find_subprotocol_nodes(0x0500);
        assert_eq!(migration_nodes.len(), 1);
        assert_eq!(migration_nodes[0], 0x3333);
    }

    // ==================================================================
    // Phase G slice 1: select_migration_target via &dyn PlacementFilter
    // ==================================================================

    use crate::adapter::net::behavior::placement::{
        Artifact, LegacyPlacement, NodeId as PlacementNodeId, PlacementFilter, ResourceAxis,
        TieBreakContext,
    };

    /// Empty capability set — placeholder for Daemon artifact's
    /// `required` / `optional` slots.
    fn empty_caps_pf() -> CapabilitySet {
        CapabilitySet::default()
    }

    /// Synthetic placement filter that returns a fixed score for
    /// every candidate, optionally vetoing specific node ids via
    /// `None`.
    struct FixedScore {
        score: f32,
        veto: Vec<u64>,
    }

    impl PlacementFilter for FixedScore {
        fn placement_score(
            &self,
            target: &PlacementNodeId,
            _artifact: &Artifact<'_>,
        ) -> Option<f32> {
            if self.veto.contains(target) {
                None
            } else {
                Some(self.score)
            }
        }
    }

    fn daemon_artifact_pf<'a>(
        required: &'a CapabilitySet,
        optional: &'a CapabilitySet,
    ) -> Artifact<'a> {
        Artifact::Daemon {
            daemon_id: [0u8; 32],
            required,
            optional,
        }
    }

    /// Single eligible candidate → `select_migration_target`
    /// returns it.
    #[test]
    fn select_migration_target_returns_only_candidate() {
        let index = make_index_with_nodes(vec![(0x2222, caps_with_migration_tag())]);
        let scheduler = Scheduler::new(index.clone(), 0x1111, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = LegacyPlacement::permissive(&index);
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0x1111,
            &placement,
            &tb,
        );
        assert_eq!(target, Some(0x2222));
    }

    /// Multiple candidates with different scores → highest wins.
    #[test]
    fn select_migration_target_picks_highest_scoring() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);

        // Synthetic filter: 0x1111 → 0.3, 0x2222 → 0.9, 0x3333 → 0.5.
        struct ScoredFilter;
        impl PlacementFilter for ScoredFilter {
            fn placement_score(&self, t: &PlacementNodeId, _: &Artifact<'_>) -> Option<f32> {
                Some(match *t {
                    0x1111 => 0.3,
                    0x2222 => 0.9,
                    0x3333 => 0.5,
                    _ => 0.0,
                })
            }
        }

        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0xFFFF,
            &ScoredFilter,
            &tb,
        );
        assert_eq!(target, Some(0x2222), "highest scorer wins");
    }

    /// Tied scores → tie-breaker resolves via lex NodeId fallback.
    #[test]
    fn select_migration_target_ties_resolved_by_lex_node_id() {
        let index = make_index_with_nodes(vec![
            (0x3333, caps_with_migration_tag()),
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 0.5,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0xFFFF,
            &placement,
            &tb,
        );
        // All three score 0.5; tie-breaker step 3 (lex NodeId)
        // picks the lowest.
        assert_eq!(target, Some(0x1111));
    }

    /// Filter vetoes everyone → `None`.
    #[test]
    fn select_migration_target_returns_none_when_all_vetoed() {
        let index = make_index_with_nodes(vec![
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![0x2222, 0x3333],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0xFFFF,
            &placement,
            &tb,
        );
        assert_eq!(target, None);
    }

    /// Empty candidate list (no migration-tagged nodes) → `None`.
    #[test]
    fn select_migration_target_returns_none_for_empty_candidates() {
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0xFFFF,
            &placement,
            &tb,
        );
        assert_eq!(target, None);
    }

    /// N-7 regression: `select_migration_target` applies the
    /// LocalPreferred fast-path. When the scheduler's local node is
    /// in the eligible-candidate pool (and isn't the source),
    /// migration stays local without consulting the placement
    /// scorer — even when the scorer would rank a remote higher.
    /// Pre-fix the fast-path lived inline in `place_migration_v2`;
    /// RTT-aware callers consuming `select_migration_target`
    /// directly silently lost it.
    #[test]
    fn select_migration_target_local_preferred_fast_path() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()), // local
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0x1111, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);

        // Synthetic placement: a remote scores higher than local.
        // The fast-path must prefer local anyway because the
        // CR-21 cost-of-network-hop argument outranks marginal
        // score differences.
        struct LocalLow;
        impl PlacementFilter for LocalLow {
            fn placement_score(&self, t: &PlacementNodeId, _: &Artifact<'_>) -> Option<f32> {
                Some(match *t {
                    0x1111 => 0.2,
                    0x2222 => 0.9,
                    0x3333 => 0.5,
                    _ => 0.0,
                })
            }
        }

        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // Source = 0x9999 (not in pool). Local 0x1111 is eligible
        // → fast-path returns local.
        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0x9999,
            &LocalLow,
            &tb,
        );
        assert_eq!(
            target,
            Some(0x1111),
            "local must win even when scoring lower"
        );
    }

    /// N-7 sibling: when the migration source IS the local node,
    /// LocalPreferred cannot trigger (the source is excluded from
    /// candidates anyway). The fast-path must check
    /// `source != local` before short-circuiting.
    #[test]
    fn select_migration_target_local_preferred_inactive_when_source_is_local() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()), // local + source
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0x1111, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);

        struct RemoteScores;
        impl PlacementFilter for RemoteScores {
            fn placement_score(&self, t: &PlacementNodeId, _: &Artifact<'_>) -> Option<f32> {
                Some(match *t {
                    0x2222 => 0.9,
                    0x3333 => 0.5,
                    _ => 0.0,
                })
            }
        }

        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // Source = 0x1111 (local). Fast-path inactive; scorer picks 0x2222.
        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0x1111,
            &RemoteScores,
            &tb,
        );
        assert_eq!(
            target,
            Some(0x2222),
            "scorer picks highest when local is source"
        );
    }

    /// Source node is excluded from candidates (already pinned by
    /// `find_migration_targets`; pin again at the
    /// `select_migration_target` level).
    #[test]
    fn select_migration_target_excludes_source_node() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // Source = 0x1111; target list excludes it. Only 0x2222 remains.
        let target = scheduler.select_migration_target(
            &artifact,
            &CapabilityFilter::default(),
            0x1111,
            &placement,
            &tb,
        );
        assert_eq!(target, Some(0x2222));
    }

    /// `daemon_filter` narrows candidates BEFORE scoring. A node
    /// without the required tag is excluded by
    /// `find_migration_targets`, so the placement filter never sees it.
    #[test]
    fn select_migration_target_honors_daemon_filter() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag().add_tag("hardware.gpu")),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // Filter: must have hardware.gpu — narrows to 0x1111 only.
        let filter = CapabilityFilter::default().require_tag("hardware.gpu".to_string());
        let target = scheduler.select_migration_target(&artifact, &filter, 0xFFFF, &placement, &tb);
        assert_eq!(target, Some(0x1111));
    }

    // ==================================================================
    // Phase G slice 3: select_member_node + select_promotion_target
    // ==================================================================

    use std::collections::HashSet;

    /// `select_member_node` with empty exclusion set — picks the
    /// best-scoring candidate from the entire filter pool.
    /// Tie-breaker resolves equal scores via lex NodeId.
    #[test]
    fn select_member_node_picks_best_with_empty_exclusion() {
        let index = make_index_with_nodes(vec![
            (0x3333, caps_no_gpu()),
            (0x1111, caps_no_gpu()),
            (0x2222, caps_no_gpu()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 0.5,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };
        let exclude = HashSet::new();

        let target = scheduler.select_member_node(
            &artifact,
            &CapabilityFilter::default(),
            &exclude,
            &placement,
            &tb,
        );
        // All three score 0.5; lex tie-breaker picks the lowest.
        assert_eq!(target, Some(0x1111));
    }

    /// `select_member_node` honors the exclusion set — already-
    /// placed members aren't re-picked. Pin the spread-aware
    /// behavior replica groups depend on.
    #[test]
    fn select_member_node_excludes_already_placed_members() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_no_gpu()),
            (0x2222, caps_no_gpu()),
            (0x3333, caps_no_gpu()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 0.5,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // 0x1111 is already a member; spread should pick the next-
        // lowest by lex order.
        let mut exclude = HashSet::new();
        exclude.insert(0x1111u64);

        let target = scheduler.select_member_node(
            &artifact,
            &CapabilityFilter::default(),
            &exclude,
            &placement,
            &tb,
        );
        assert_eq!(target, Some(0x2222));
    }

    /// `select_member_node`: exclusion set covers every candidate
    /// → `None`.
    #[test]
    fn select_member_node_returns_none_when_all_excluded() {
        let index = make_index_with_nodes(vec![(0x1111, caps_no_gpu()), (0x2222, caps_no_gpu())]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 0.5,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let mut exclude = HashSet::new();
        exclude.insert(0x1111u64);
        exclude.insert(0x2222u64);

        let target = scheduler.select_member_node(
            &artifact,
            &CapabilityFilter::default(),
            &exclude,
            &placement,
            &tb,
        );
        assert_eq!(target, None);
    }

    /// `select_member_node` honors the placement filter veto —
    /// excluded set + filter-vetoed candidates both drop out.
    #[test]
    fn select_member_node_combines_exclusion_with_filter_veto() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_no_gpu()),
            (0x2222, caps_no_gpu()),
            (0x3333, caps_no_gpu()),
        ]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        // Filter vetoes 0x2222.
        let placement = FixedScore {
            score: 1.0,
            veto: vec![0x2222],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };
        // Exclude 0x1111; with 0x2222 vetoed, only 0x3333 remains.
        let mut exclude = HashSet::new();
        exclude.insert(0x1111u64);

        let target = scheduler.select_member_node(
            &artifact,
            &CapabilityFilter::default(),
            &exclude,
            &placement,
            &tb,
        );
        assert_eq!(target, Some(0x3333));
    }

    /// `select_promotion_target` over a pre-computed roster
    /// (standby members) — picks the best by score + tie-break.
    #[test]
    fn select_promotion_target_picks_highest_scoring_standby() {
        let index = make_index_with_nodes(vec![(0x1111, caps_no_gpu()), (0x2222, caps_no_gpu())]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);

        // Synthetic filter: 0x1111 → 0.3, 0x2222 → 0.9.
        struct ScoredFilter;
        impl PlacementFilter for ScoredFilter {
            fn placement_score(&self, t: &PlacementNodeId, _: &Artifact<'_>) -> Option<f32> {
                Some(match *t {
                    0x1111 => 0.3,
                    0x2222 => 0.9,
                    _ => 0.0,
                })
            }
        }
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let standbys = vec![0x1111u64, 0x2222u64];
        let target = scheduler.select_promotion_target(standbys, &artifact, &ScoredFilter, &tb);
        assert_eq!(target, Some(0x2222));
    }

    /// `select_promotion_target` over an empty roster → `None`.
    #[test]
    fn select_promotion_target_empty_roster_returns_none() {
        let index = make_index_with_nodes(vec![]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_promotion_target(vec![], &artifact, &placement, &tb);
        assert_eq!(target, None);
    }

    /// `select_promotion_target` propagates filter vetoes — every
    /// candidate vetoed → `None`.
    #[test]
    fn select_promotion_target_returns_none_when_all_vetoed() {
        let index = make_index_with_nodes(vec![(0x1111, caps_no_gpu()), (0x2222, caps_no_gpu())]);
        let scheduler = Scheduler::new(index.clone(), 0xFFFF, caps_no_gpu());
        let req = empty_caps_pf();
        let opt = empty_caps_pf();
        let artifact = daemon_artifact_pf(&req, &opt);
        let placement = FixedScore {
            score: 1.0,
            veto: vec![0x1111, 0x2222],
        };
        let tb = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        let target = scheduler.select_promotion_target(
            vec![0x1111u64, 0x2222u64],
            &artifact,
            &placement,
            &tb,
        );
        assert_eq!(target, None);
    }

    // ==================================================================
    // Phase G slice 8: place_migration_v2 — default migration path
    //
    // Pin three guarantees:
    //   1. v2 always stamps `PlacementReason::BestScore` (telemetry
    //      contract — operators can grep for the v2 path).
    //   2. v2 finds the same eligibility set as v1 (uses
    //      `LegacyPlacement::permissive` against the same index +
    //      same `daemon_filter` narrowing via
    //      `find_migration_targets`).
    //   3. v2 excludes the source node and uses §7-LOCKED tie-breaker
    //      (lex NodeId fallback when no RTT data) — yields a
    //      deterministic pick across multiple eligible candidates.
    //   4. v1 (`place_migration`) still works — kept around for
    //      callers who explicitly want the legacy `LocalPreferred`
    //      / `FirstMatch` reasons.
    // ==================================================================

    /// `place_migration_v2` stamps `BestScore` on every successful
    /// pick. Pins the telemetry contract that distinguishes v2 from
    /// v1 (`LocalPreferred` / `OnlyCandidate` / `FirstMatch`).
    #[test]
    fn place_migration_v2_stamps_best_score_reason() {
        let index = make_index_with_nodes(vec![
            (0x2222, caps_with_migration_tag()),
            (0x3333, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let decision = scheduler
            .place_migration_v2(&CapabilityFilter::default(), 0x1111)
            .expect("two eligible targets, source excluded");

        assert_eq!(decision.reason, PlacementReason::BestScore);
        // 0x2222 wins lex tie-break over 0x3333 (no RTT data, all
        // candidates score 1.0 via LegacyPlacement::permissive).
        assert_eq!(decision.node_id, 0x2222);
    }

    /// `place_migration_v2` excludes the source node — v2 honors
    /// the same source-exclusion contract as v1.
    #[test]
    fn place_migration_v2_excludes_source_node() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0xFFFF, caps_no_gpu());

        // Source = 0x1111; v2 must pick 0x2222.
        let decision = scheduler
            .place_migration_v2(&CapabilityFilter::default(), 0x1111)
            .unwrap();
        assert_eq!(decision.node_id, 0x2222);
        assert_eq!(decision.reason, PlacementReason::BestScore);
    }

    /// `place_migration_v2` returns `NoCandidate` when nothing
    /// matches — same failure mode as v1.
    #[test]
    fn place_migration_v2_returns_no_candidate_when_nothing_matches() {
        let index = make_index_with_nodes(vec![
            (0x2222, caps_no_gpu()), // no migration tag
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_no_gpu());

        let err = scheduler
            .place_migration_v2(&CapabilityFilter::default(), 0x1111)
            .unwrap_err();
        assert_eq!(err, SchedulerError::NoCandidate);
    }

    /// CR-21: `place_migration_v2` prefers local when local is
    /// eligible (and not the source). Pre-CR-21 v2 routed every
    /// migration through `select_migration_target` →
    /// `LegacyPlacement::permissive`, where every eligible
    /// scored 1.0 and step-3 lex NodeId tie-break made the
    /// smallest-NodeId *remote* always beat a higher-NodeId
    /// local — every migration newly hopped the network even
    /// when local was fine. The fast-path matches v1 behavior
    /// and saves the round-trip.
    #[test]
    fn place_migration_v2_prefers_local() {
        let local_caps = caps_with_migration_tag();
        let index = make_index_with_nodes(vec![
            // Smallest NodeId is the remote, so without the
            // local-preferred fast-path lex tie-break would
            // always pick the remote.
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        // Local node = 0x2222 (HIGHER than the remote 0x1111).
        let scheduler = Scheduler::new(index, 0x2222, local_caps);

        // Source = 0x9999 (some other node), so local 0x2222
        // is eligible. Pre-CR-21: tie-break picked 0x1111
        // (smallest NodeId). Post-CR-21: local fast-path picks
        // 0x2222 with LocalPreferred reason.
        let decision = scheduler
            .place_migration_v2(&CapabilityFilter::default(), 0x9999)
            .unwrap();
        assert_eq!(decision.node_id, 0x2222, "local must win the fast-path");
        assert_eq!(decision.reason, PlacementReason::LocalPreferred);
    }

    /// `place_migration_v2` honors the daemon_filter — a node
    /// without the required tag is excluded by
    /// `find_migration_targets` before scoring (same path as v1).
    #[test]
    fn place_migration_v2_honors_daemon_filter() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag().add_tag("hardware.gpu")),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0xFFFF, caps_no_gpu());

        // Filter requires hardware.gpu — narrows candidate pool to
        // 0x1111. Source 0x9999 doesn't intersect either candidate.
        let filter = CapabilityFilter::default().require_tag("hardware.gpu".to_string());
        let decision = scheduler
            .place_migration_v2(&filter, 0x9999)
            .expect("0x1111 is the only filter-passing candidate");
        assert_eq!(decision.node_id, 0x1111);
        assert_eq!(decision.reason, PlacementReason::BestScore);
    }

    /// CR-6: NaN scores from custom `PlacementFilter` impls (e.g.
    /// FFI-registered Python/JS predicates) must not poison the
    /// placement sort. `Vec::sort_by` over a non-total ordering is
    /// undefined; `pick_best_candidate` must drop NaN candidates at
    /// the boundary so the surviving sort is a strict total order.
    #[test]
    fn pick_best_candidate_drops_nan_scores() {
        use crate::adapter::net::behavior::placement::{
            Artifact, NodeId, PlacementFilter, ResourceAxis, TieBreakContext,
        };

        struct NaNFilter;
        impl PlacementFilter for NaNFilter {
            fn placement_score(&self, target: &NodeId, _: &Artifact<'_>) -> Option<f32> {
                // Node 0x2222 — NaN score (must be dropped).
                // All others — finite score 1.0 (eligible).
                if *target == 0x2222 {
                    Some(f32::NAN)
                } else {
                    Some(1.0)
                }
            }
        }

        let required = CapabilitySet::new();
        let optional = CapabilitySet::new();
        let artifact = Artifact::Daemon {
            daemon_id: [0u8; 32],
            required: &required,
            optional: &optional,
        };
        let index = CapabilityIndex::new();
        let tie_break = TieBreakContext {
            rtt_lookup: None,
            index: &index,
            resource_axis: ResourceAxis::Compute,
        };

        // 64 runs to make any ordering randomness extremely
        // unlikely to mask the bug if the filter regresses.
        for run in 0..64 {
            let pick = Scheduler::pick_best_candidate(
                vec![0x1111u64, 0x2222u64, 0x3333u64],
                &artifact,
                &NaNFilter,
                &tie_break,
            );
            // 0x2222 (NaN) must NEVER win; 0x1111 wins by lex
            // tie-break against 0x3333 (both score 1.0).
            assert_eq!(
                pick,
                Some(0x1111),
                "run {run}: NaN candidate must be dropped"
            );
        }
    }

    /// `place_migration` (v1) is still available and unchanged.
    /// Pins the back-compat guarantee that callers who explicitly
    /// want v1's `LocalPreferred` reason can keep using it.
    #[test]
    fn place_migration_v1_still_returns_legacy_reasons() {
        let index = make_index_with_nodes(vec![
            (0x1111, caps_with_migration_tag()),
            (0x2222, caps_with_migration_tag()),
        ]);
        let scheduler = Scheduler::new(index, 0x1111, caps_with_migration_tag());

        // Source 0x3333; local 0x1111 is eligible → LocalPreferred.
        let decision = scheduler
            .place_migration(&CapabilityFilter::default(), 0x3333)
            .unwrap();
        assert_eq!(decision.node_id, 0x1111);
        assert_eq!(
            decision.reason,
            PlacementReason::LocalPreferred,
            "v1 path should still stamp LocalPreferred (legacy contract)"
        );
    }
}