-
Notifications
You must be signed in to change notification settings - Fork 295
/
scheduler.rs
2414 lines (2225 loc) · 102 KB
/
scheduler.rs
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
use crate::{
canister_manager::{uninstall_canister, AddCanisterChangeToHistory},
execution_environment::{
as_num_instructions, as_round_instructions, execute_canister, ExecuteCanisterResult,
ExecutionEnvironment, RoundInstructions, RoundLimits,
},
metrics::MeasurementScope,
util::process_responses,
};
use ic_config::flag_status::FlagStatus;
use ic_config::subnet_config::SchedulerConfig;
use ic_crypto_prng::{Csprng, RandomnessPurpose::ExecutionThread};
use ic_cycles_account_manager::CyclesAccountManager;
use ic_error_types::{ErrorCode, UserError};
use ic_interfaces::execution_environment::{ExecutionRoundType, RegistryExecutionSettings};
use ic_interfaces::execution_environment::{
IngressHistoryWriter, Scheduler, SubnetAvailableMemory,
};
use ic_logger::{debug, error, fatal, info, new_logger, warn, ReplicaLogger};
use ic_management_canister_types::{CanisterStatusType, EcdsaKeyId, Method as Ic00Method};
use ic_metrics::MetricsRegistry;
use ic_replicated_state::{
canister_state::{
execution_state::NextScheduledMethod, system_state::CyclesUseCase, NextExecution,
},
page_map::PageAllocatorFileDescriptor,
CanisterState, CanisterStatus, ExecutionTask, InputQueueType, NetworkTopology, ReplicatedState,
};
use ic_system_api::InstructionLimits;
use ic_types::{
consensus::ecdsa::QuadrupleId,
crypto::canister_threshold_sig::MasterPublicKey,
ingress::{IngressState, IngressStatus},
messages::{CanisterMessage, Ingress, MessageId, Response, StopCanisterContext, NO_DEADLINE},
AccumulatedPriority, CanisterId, ComputeAllocation, Cycles, ExecutionRound, LongExecutionMode,
MemoryAllocation, NumBytes, NumInstructions, NumSlices, Randomness, SubnetId, Time,
};
use ic_types::{nominal_cycles::NominalCycles, NumMessages};
use num_rational::Ratio;
use std::{
cell::RefCell,
cmp::Reverse,
collections::{BTreeMap, BTreeSet},
str::FromStr,
sync::Arc,
};
mod scheduler_metrics;
use scheduler_metrics::*;
mod round_schedule;
use crate::util::debug_assert_or_critical_error;
pub use round_schedule::RoundSchedule;
use round_schedule::*;
mod tecdsa;
use tecdsa::*;
/// Only log potentially spammy messages this often (in rounds). With a block
/// rate around 1.0, this will result in logging about once every 10 minutes.
const SPAMMY_LOG_INTERVAL_ROUNDS: u64 = 10 * 60;
/// Ideally we would split the per-round limit between subnet messages and
/// canister messages, so that their sum cannot exceed the limit. That would
/// make the limit for canister messages variable, which would break assumptions
/// of the scheduling algorithm. The next best thing we can do is to limit
/// subnet messages on top of the fixed limit for canister messages.
/// The value of the limit for subnet messages is chosen quite arbitrarily
/// as 1/16 of the fixed limit. Any other value in the same ballpark would
/// work here.
const SUBNET_MESSAGES_LIMIT_FRACTION: u64 = 16;
#[cfg(test)]
pub(crate) mod test_utilities;
#[cfg(test)]
pub(crate) mod tests;
/// Contains limits (or budget) for various resources that affect duration of
/// an execution round.
#[derive(Debug, Default, Clone)]
struct SchedulerRoundLimits {
/// Keeps track of remaining instructions in this execution round.
instructions: RoundInstructions,
/// Keeps track of remaining instruction to be used by subnet messages in this execution round.
subnet_instructions: RoundInstructions,
/// Keeps track of the available storage memory. It decreases if
/// - Wasm execution grows the Wasm/stable memory.
/// - Wasm execution pushes a new request to the output queue.
subnet_available_memory: SubnetAvailableMemory,
// Keeps track of the compute allocation limit.
compute_allocation_used: u64,
}
impl SchedulerRoundLimits {
fn subnet_round_limits(&self) -> RoundLimits {
RoundLimits {
instructions: self.subnet_instructions,
subnet_available_memory: self.subnet_available_memory,
compute_allocation_used: self.compute_allocation_used,
}
}
fn canister_round_limits(&self) -> RoundLimits {
RoundLimits {
instructions: self.instructions,
subnet_available_memory: self.subnet_available_memory,
compute_allocation_used: self.compute_allocation_used,
}
}
fn update_subnet_round_limits(&mut self, round_limits: &RoundLimits) {
self.subnet_instructions = round_limits.instructions;
self.subnet_available_memory = round_limits.subnet_available_memory;
self.compute_allocation_used = round_limits.compute_allocation_used;
}
pub fn update_canister_round_limits(&mut self, round_limits: &RoundLimits) {
self.instructions = round_limits.instructions;
self.subnet_available_memory = round_limits.subnet_available_memory;
self.compute_allocation_used = round_limits.compute_allocation_used;
}
}
////////////////////////////////////////////////////////////////////////
/// Scheduler Implementation
pub(crate) struct SchedulerImpl {
config: SchedulerConfig,
own_subnet_id: SubnetId,
ingress_history_writer: Arc<dyn IngressHistoryWriter<State = ReplicatedState>>,
exec_env: Arc<ExecutionEnvironment>,
cycles_account_manager: Arc<CyclesAccountManager>,
metrics: Arc<SchedulerMetrics>,
log: ReplicaLogger,
thread_pool: RefCell<scoped_threadpool::Pool>,
rate_limiting_of_heap_delta: FlagStatus,
rate_limiting_of_instructions: FlagStatus,
deterministic_time_slicing: FlagStatus,
fd_factory: Arc<dyn PageAllocatorFileDescriptor>,
}
impl SchedulerImpl {
/// Returns scheduler compute capacity in percent.
/// For the DTS scheduler, it's `(number of cores - 1) * 100%`
pub fn compute_capacity_percent(scheduler_cores: usize) -> usize {
// Note: the DTS scheduler requires at least 2 scheduler cores
if scheduler_cores >= 2 {
(scheduler_cores - 1) * 100
} else {
0
}
}
/// Orders canister round states according to the scheduling strategy.
/// The function is to keep in sync `apply_scheduling_strategy()` and
/// `abort_paused_executions_above_limit()`
fn order_canister_round_states(&self, round_states: &mut [CanisterRoundState]) {
round_states.sort_by_key(|rs| {
(
Reverse(rs.long_execution_mode),
Reverse(rs.has_aborted_or_paused_execution),
Reverse(rs.accumulated_priority),
rs.canister_id,
)
});
}
/// Orders the canisters and updates their accumulated priorities according to
/// the strategy described in RUN-58.
///
/// A shorter description of the scheduling strategy is available in the note
/// section about [Scheduler and AccumulatedPriority] in types/src/lib.rs
fn apply_scheduling_strategy(
&self,
logger: &ReplicaLogger,
scheduler_cores: usize,
current_round: ExecutionRound,
accumulated_priority_reset_interval: ExecutionRound,
canister_states: &mut BTreeMap<CanisterId, CanisterState>,
) -> RoundSchedule {
let number_of_canisters = canister_states.len();
// Total allocatable compute capacity in percent.
// As one scheduler core is reserved to guarantee long executions progress,
// compute capacity is `(scheduler_cores - 1) * 100`
let compute_capacity_percent = Self::compute_capacity_percent(scheduler_cores) as i64;
// Sum of all canisters compute allocation in percent.
// It's guaranteed to be less than `compute_capacity_percent`
// by `validate_compute_allocation()`.
// This corresponds to |a| in Scheduler Analysis.
let mut total_compute_allocation_percent: i64 = 0;
// Use this multiplier to achieve the following two:
// 1) The sum of all the values we add to accumulated priorities
// to calculate the round priorities must be divisible by the number
// of canisters that are given top priority in this round.
// 2) The free capacity (the difference between `compute_capacity_percent`
// and `total_compute_allocation_percent`) can be distributed to all
// the canisters evenly.
// The `max(1)` is the corner case when there are no Canisters.
let multiplier = (scheduler_cores * number_of_canisters).max(1) as i64;
// This corresponds to the vector p in the Scheduler Analysis document.
let mut round_states = Vec::with_capacity(number_of_canisters);
// Reset the accumulated priorities periodically.
// We want to reset the scheduler regularly to safely support changes in the set
// of canisters and their compute allocations.
let is_reset_round = (current_round.get() % accumulated_priority_reset_interval.get()) == 0;
// Compute the priority of the canisters for this round.
let mut accumulated_priority_invariant = AccumulatedPriority::default();
let mut accumulated_priority_deviation = 0;
for (&canister_id, canister) in canister_states.iter_mut() {
if is_reset_round {
canister.scheduler_state.accumulated_priority = Default::default();
canister.scheduler_state.priority_credit = Default::default();
}
let has_aborted_or_paused_execution =
canister.has_aborted_execution() || canister.has_paused_execution();
if !has_aborted_or_paused_execution {
canister.scheduler_state.long_execution_mode = Default::default();
}
let compute_allocation = canister.scheduler_state.compute_allocation;
let accumulated_priority = canister.scheduler_state.accumulated_priority;
round_states.push(CanisterRoundState {
canister_id,
accumulated_priority,
compute_allocation,
long_execution_mode: canister.scheduler_state.long_execution_mode,
has_aborted_or_paused_execution,
});
total_compute_allocation_percent += compute_allocation.as_percent() as i64;
accumulated_priority_invariant += accumulated_priority;
accumulated_priority_deviation +=
accumulated_priority.get() * accumulated_priority.get();
}
// Assert there is at least `1%` of free capacity to distribute across canisters.
// It's guaranteed by `validate_compute_allocation()`
debug_assert_or_critical_error!(
total_compute_allocation_percent < compute_capacity_percent,
self.metrics.scheduler_compute_allocation_invariant_broken,
logger,
"{}: Total compute allocation {}% must be less than compute capacity {}%",
SCHEDULER_COMPUTE_ALLOCATION_INVARIANT_BROKEN,
total_compute_allocation_percent,
compute_capacity_percent
);
// Observe accumulated priority metrics
self.metrics
.scheduler_accumulated_priority_invariant
.set(accumulated_priority_invariant.get());
self.metrics
.scheduler_accumulated_priority_deviation
.set((accumulated_priority_deviation as f64 / number_of_canisters as f64).sqrt());
// Free capacity per canister in multiplied percent.
// Note, to avoid division by zero when there are no canisters
// and having `multiplier == number_of_canisters * scheduler_cores`, the
// `(compute_capacity - total_compute_allocation) * multiplier / number_of_canisters`
// can be simplified to just
// `(compute_capacity - total_compute_allocation) * scheduler_cores`
let free_capacity_per_canister = (compute_capacity_percent
.saturating_sub(total_compute_allocation_percent))
* scheduler_cores as i64;
// Fully divide the free allocation across all canisters.
let mut long_executions_compute_allocation = 0;
let mut number_of_long_executions = 0;
for rs in round_states.iter_mut() {
// De-facto compute allocation includes bonus allocation
let factual =
rs.compute_allocation.as_percent() as i64 * multiplier + free_capacity_per_canister;
// Increase accumulated priority by de-facto compute allocation.
rs.accumulated_priority += factual.into();
// Count long executions and sum up their compute allocation.
if rs.has_aborted_or_paused_execution {
// Note: factual compute allocation is multiplied by `multiplier`
long_executions_compute_allocation += factual;
number_of_long_executions += 1;
}
}
// Optimization that makes use of accessing a canister state without an extra canister id lookup.
// IMPORTANT! Optimization relies on the fact that elements in `canister_states` and `round_states` follow in the same order.
for ((&_, canister), rs) in canister_states.iter_mut().zip(round_states.iter()) {
debug_assert!(
canister.canister_id() == rs.canister_id,
"Elements in canister_states and round_states must follow in the same order",
);
// Update canister state with a new accumulated_priority.
canister.scheduler_state.accumulated_priority = rs.accumulated_priority;
// Record a canister metric.
if !canister.has_input() {
canister
.system_state
.canister_metrics
.skipped_round_due_to_no_messages += 1;
}
}
// Count long execution cores by dividing `long_execution_compute_allocation`
// by `100%` and rounding up (as one scheduler core is reserved to guarantee
// long executions progress).
// Note, the `long_execution_compute_allocation` is in percent multiplied
// by the `multiplier`.
let long_execution_cores = ((long_executions_compute_allocation + 100 * multiplier - 1)
/ (100 * multiplier)) as usize;
// If there are long executions, the `long_execution_cores` must be non-zero.
debug_assert_or_critical_error!(
number_of_long_executions == 0 || long_execution_cores > 0,
self.metrics.scheduler_cores_invariant_broken,
logger,
"{}: Number of long execution cores {} must be more than 0",
SCHEDULER_CORES_INVARIANT_BROKEN,
long_execution_cores,
);
// As one scheduler core is reserved, the `long_execution_cores` is always
// less than `scheduler_cores`
debug_assert_or_critical_error!(
long_execution_cores < scheduler_cores,
self.metrics.scheduler_cores_invariant_broken,
logger,
"{}: Number of long execution cores {} must be less than scheduler cores {}",
SCHEDULER_CORES_INVARIANT_BROKEN,
long_execution_cores,
scheduler_cores
);
self.order_canister_round_states(&mut round_states);
let round_schedule = RoundSchedule::new(
scheduler_cores,
long_execution_cores,
round_states
.iter()
.skip(number_of_long_executions)
.map(|rs| rs.canister_id)
.collect(),
round_states
.iter()
.take(number_of_long_executions)
.map(|rs| rs.canister_id)
.collect(),
);
{
let scheduling_order = round_schedule.scheduling_order();
let scheduling_order = scheduling_order
.prioritized_long_canister_ids
.chain(scheduling_order.new_canister_ids)
.chain(scheduling_order.opportunistic_long_canister_ids);
// The number of active scheduler cores is limited by the number
// of canisters to schedule.
let active_cores = scheduler_cores.min(number_of_canisters);
for (i, canister_id) in scheduling_order.take(active_cores).enumerate() {
let canister_state = canister_states.get_mut(canister_id).unwrap();
// As top `scheduler_cores` canisters are guaranteed to be scheduled
// this round, their accumulated priorities must be decreased here
// by `capacity * multiplier / scheduler_cores`. But instead this
// value is accumulated in the `priority_credit`, and applied later:
// * For short executions, the `priority_credit` is deducted from
// the `accumulated_priority` at the end of the round.
// * For long executions, the `priority_credit` is accumulated
// for a few rounds, and deducted from the `accumulated_priority`
// at the end of the long execution.
canister_state.scheduler_state.priority_credit +=
(compute_capacity_percent * multiplier / active_cores as i64).into();
if i < round_schedule.long_execution_cores {
canister_state.scheduler_state.long_execution_mode =
LongExecutionMode::Prioritized;
}
}
}
round_schedule
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
config: SchedulerConfig,
own_subnet_id: SubnetId,
ingress_history_writer: Arc<dyn IngressHistoryWriter<State = ReplicatedState>>,
exec_env: Arc<ExecutionEnvironment>,
cycles_account_manager: Arc<CyclesAccountManager>,
metrics_registry: &MetricsRegistry,
log: ReplicaLogger,
rate_limiting_of_heap_delta: FlagStatus,
rate_limiting_of_instructions: FlagStatus,
deterministic_time_slicing: FlagStatus,
fd_factory: Arc<dyn PageAllocatorFileDescriptor>,
) -> Self {
let scheduler_cores = config.scheduler_cores as u32;
Self {
config,
thread_pool: RefCell::new(scoped_threadpool::Pool::new(scheduler_cores)),
own_subnet_id,
ingress_history_writer,
exec_env,
cycles_account_manager,
metrics: Arc::new(SchedulerMetrics::new(metrics_registry)),
log,
rate_limiting_of_heap_delta,
rate_limiting_of_instructions,
deterministic_time_slicing,
fd_factory,
}
}
/// Makes progress in executing long-running `install_code` messages.
fn advance_long_running_install_code(
&self,
mut state: ReplicatedState,
round_limits: &mut RoundLimits,
long_running_canister_ids: &BTreeSet<CanisterId>,
measurement_scope: &MeasurementScope,
subnet_size: usize,
) -> ReplicatedState {
let mut ongoing_long_install_code = false;
for canister_id in long_running_canister_ids.iter() {
match state.canister_state(canister_id) {
None => continue,
Some(canister) => match canister.next_execution() {
NextExecution::None | NextExecution::StartNew | NextExecution::ContinueLong => {
continue
}
NextExecution::ContinueInstallCode => {}
},
}
let instruction_limits = InstructionLimits::new(
self.deterministic_time_slicing,
self.config.max_instructions_per_install_code,
self.config.max_instructions_per_install_code_slice,
);
let instructions_before = round_limits.instructions;
let (new_state, message_instructions) = self.exec_env.resume_install_code(
state,
canister_id,
instruction_limits,
round_limits,
subnet_size,
);
state = new_state;
ongoing_long_install_code |= state
.canister_state(canister_id)
.map_or(false, |canister| canister.has_paused_install_code());
let round_instructions_executed =
as_num_instructions(instructions_before - round_limits.instructions);
let messages = NumMessages::from(message_instructions.map(|_| 1).unwrap_or(0));
measurement_scope.add(round_instructions_executed, NumSlices::from(1), messages);
// Break when round limits are reached or found a canister
// that has a long install code message in progress.
if round_limits.reached() || ongoing_long_install_code {
break;
}
}
state
}
/// Drains the subnet queues, executing all messages not blocked by long executions.
/// It consumes the `long_running_canister_ids` set instead of borrowing it
/// because after the function execution the set is no longer valid.
fn drain_subnet_queues(
&self,
mut state: ReplicatedState,
csprng: &mut Csprng,
round_limits: &mut RoundLimits,
measurement_scope: &MeasurementScope,
ongoing_long_install_code: bool,
long_running_canister_ids: BTreeSet<CanisterId>,
registry_settings: &RegistryExecutionSettings,
ecdsa_subnet_public_keys: &BTreeMap<EcdsaKeyId, MasterPublicKey>,
) -> ReplicatedState {
loop {
let mut available_subnet_messages = false;
let mut loop_detector = state.subnet_queues_loop_detector();
while let Some(msg) = state.peek_subnet_input() {
if can_execute_msg(&msg, ongoing_long_install_code, &long_running_canister_ids) {
available_subnet_messages = true;
break;
}
state.skip_subnet_input(&mut loop_detector);
if loop_detector.detected_loop(state.subnet_queues()) {
break;
}
}
if !available_subnet_messages {
break;
}
if let Some(msg) = state.pop_subnet_input() {
let (new_state, message_instructions) = self.execute_subnet_message(
msg,
state,
csprng,
round_limits,
registry_settings,
measurement_scope,
ecdsa_subnet_public_keys,
);
state = new_state;
if message_instructions.is_none() {
// This may happen only if the message execution was paused,
// which means that there should not be any instructions
// remaining in the round. Since we do not update
// `long_running_canister_ids` and `ongoing_long_install_code`,
// we need to break the loop here to ensure correctness in
// the unlikely case of some instructions still remaining
// in the round.
break;
}
if round_limits.reached() {
break;
}
}
}
state
}
/// Invokes `ExecutionEnvironmnet` to execute a subnet message.
fn execute_subnet_message(
&self,
msg: CanisterMessage,
state: ReplicatedState,
csprng: &mut Csprng,
round_limits: &mut RoundLimits,
registry_settings: &RegistryExecutionSettings,
measurement_scope: &MeasurementScope,
ecdsa_subnet_public_keys: &BTreeMap<EcdsaKeyId, MasterPublicKey>,
) -> (ReplicatedState, Option<NumInstructions>) {
let instruction_limits = get_instructions_limits_for_subnet_message(
self.deterministic_time_slicing,
&self.config,
&msg,
);
let instructions_before = round_limits.instructions;
let (new_state, message_instructions) = self.exec_env.execute_subnet_message(
msg,
state,
instruction_limits,
csprng,
ecdsa_subnet_public_keys,
registry_settings,
round_limits,
);
let round_instructions_executed =
as_num_instructions(instructions_before - round_limits.instructions);
let messages = NumMessages::from(message_instructions.map(|_| 1).unwrap_or(0));
measurement_scope.add(round_instructions_executed, NumSlices::from(1), messages);
(new_state, message_instructions)
}
/// Invoked in the first iteration of the inner round to add the `Heartbeat`
/// and `GlobalTimer` tasks that are carried out prior to processing
/// any input messages.
/// It also returns the list of canisters that have non-zero priority credit.
fn initialize_inner_round(
&self,
state: &mut ReplicatedState,
) -> (BTreeSet<CanisterId>, BTreeSet<CanisterId>) {
let _timer = self
.metrics
.round_inner_heartbeat_overhead_duration
.start_timer();
let mut heartbeat_and_timer_canister_ids = BTreeSet::new();
let mut non_zero_priority_credit_canister_ids = BTreeSet::new();
let now = state.time();
for canister in state.canisters_iter_mut() {
// Remember all non-zero priority_credit canisters to apply it after the round.
if canister.scheduler_state.priority_credit != AccumulatedPriority::default() {
non_zero_priority_credit_canister_ids.insert(canister.system_state.canister_id);
}
// Add `Heartbeat` or `GlobalTimer` for running canisters only.
match canister.system_state.status {
CanisterStatus::Running { .. } => {}
CanisterStatus::Stopping { .. } | CanisterStatus::Stopped => {
continue;
}
}
let may_schedule_heartbeat = canister.exports_heartbeat_method();
let may_schedule_global_timer = canister.exports_global_timer_method()
&& canister.system_state.global_timer.has_reached_deadline(now);
if !may_schedule_heartbeat && !may_schedule_global_timer {
// Canister has no heartbeat and no (schedulable) global timer.
continue;
}
match canister.next_execution() {
NextExecution::ContinueLong | NextExecution::ContinueInstallCode => {
// Do not add a heartbeat task if a long execution
// is pending.
}
NextExecution::None | NextExecution::StartNew => {
for _ in 0..NextScheduledMethod::NUMBER_OF_VARIANTS {
let method_chosen = is_next_method_chosen(
canister,
&mut heartbeat_and_timer_canister_ids,
may_schedule_heartbeat,
may_schedule_global_timer,
);
canister.inc_next_scheduled_method();
if method_chosen {
break;
}
}
}
}
}
(
heartbeat_and_timer_canister_ids,
non_zero_priority_credit_canister_ids,
)
}
/// Performs multiple iterations of canister execution until the instruction
/// limit per round is reached or the canisters become idle. The canisters
/// are executed in parallel using the thread pool.
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn inner_round<'a>(
&'a self,
mut state: ReplicatedState,
csprng: &mut Csprng,
round_schedule: &RoundSchedule,
current_round: ExecutionRound,
root_measurement_scope: &MeasurementScope<'a>,
scheduler_round_limits: &mut SchedulerRoundLimits,
registry_settings: &RegistryExecutionSettings,
ecdsa_subnet_public_keys: &BTreeMap<EcdsaKeyId, MasterPublicKey>,
) -> (ReplicatedState, BTreeSet<CanisterId>) {
let measurement_scope =
MeasurementScope::nested(&self.metrics.round_inner, root_measurement_scope);
let mut ingress_execution_results = Vec::new();
let mut is_first_iteration = true;
let mut round_filtered_canisters = FilteredCanisters::new();
let mut total_heap_delta = NumBytes::from(0);
let mut heartbeat_and_timer_canister_ids = BTreeSet::new();
let mut non_zero_priority_credit_canister_ids = BTreeSet::new();
// Start iteration loop:
// - Execute subnet messages.
// - Execute hearbeat and global timer tasks.
// - Execute canisters input messages in parallel.
// - Induct messages on the same subnet.
let mut state = loop {
// Execute subnet messages.
// If new messages are inducted into the subnet input queues,
// they are processed until the subbnet messages' instruction limit is reached.
{
let subnet_measurement_scope = MeasurementScope::nested(
&self.metrics.round_subnet_queue,
root_measurement_scope,
);
// TODO(EXC-1517): Improve inner loop preparation.
let mut ongoing_long_install_code = false;
let long_running_canister_ids = state
.canister_states
.iter()
.filter_map(|(&canister_id, canister)| match canister.next_execution() {
NextExecution::None | NextExecution::StartNew => None,
NextExecution::ContinueLong => Some(canister_id),
NextExecution::ContinueInstallCode => {
ongoing_long_install_code = true;
Some(canister_id)
}
})
.collect();
let mut subnet_round_limits = scheduler_round_limits.subnet_round_limits();
if !subnet_round_limits.reached() {
state = self.drain_subnet_queues(
state,
csprng,
&mut subnet_round_limits,
&subnet_measurement_scope,
ongoing_long_install_code,
long_running_canister_ids,
registry_settings,
ecdsa_subnet_public_keys,
);
scheduler_round_limits.update_subnet_round_limits(&subnet_round_limits);
}
}
let measurement_scope =
MeasurementScope::nested(&self.metrics.round_inner_iteration, &measurement_scope);
let mut round_limits = scheduler_round_limits.canister_round_limits();
let preparation_timer = self.metrics.round_inner_iteration_prep.start_timer();
// Add `Heartbeat` and `GlobalTimer` tasks to be executed before input messages.
if is_first_iteration {
(
heartbeat_and_timer_canister_ids,
non_zero_priority_credit_canister_ids,
) = self.initialize_inner_round(&mut state)
}
// Update subnet available memory before taking out the canisters.
round_limits.subnet_available_memory = self.exec_env.subnet_available_memory(&state);
let canisters = state.take_canister_states();
// Obtain the active canisters and update the collection of heap delta rate-limited canisters.
let (active_round_schedule, rate_limited_canister_ids) = round_schedule
.filter_canisters(
&canisters,
self.config.heap_delta_rate_limit,
self.rate_limiting_of_heap_delta,
);
round_filtered_canisters
.add_canisters(&active_round_schedule, &rate_limited_canister_ids);
let (mut active_canisters_partitioned_by_cores, inactive_canisters) =
active_round_schedule.partition_canisters_to_cores(canisters);
if is_first_iteration {
for partition in active_canisters_partitioned_by_cores.iter_mut() {
if let Some(canister) = partition.first_mut() {
canister.system_state.canister_metrics.scheduled_as_first += 1;
}
}
}
drop(preparation_timer);
let execution_timer = self.metrics.round_inner_iteration_exe.start_timer();
let instructions_before = round_limits.instructions;
let (executed_canisters, mut loop_ingress_execution_results, heap_delta) = self
.execute_canisters_in_inner_round(
active_canisters_partitioned_by_cores,
current_round,
state.time(),
Arc::new(state.metadata.network_topology.clone()),
&measurement_scope,
&mut round_limits,
registry_settings.subnet_size,
);
let instructions_consumed = instructions_before - round_limits.instructions;
drop(execution_timer);
let finalization_timer = self.metrics.round_inner_iteration_fin.start_timer();
total_heap_delta += heap_delta;
state.metadata.heap_delta_estimate += heap_delta;
// Put back the executed canisters into the canisters map. Since usually most
// canisters have no messages to execute, this is likely to be more efficient
// than rebuilding the map from scratch.
let mut canisters = inactive_canisters;
canisters.extend(
executed_canisters
.into_iter()
.map(|canister| (canister.canister_id(), canister)),
);
state.put_canister_states(canisters);
ingress_execution_results.append(&mut loop_ingress_execution_results);
round_limits.instructions -= as_round_instructions(
self.config
.instruction_overhead_per_canister_for_finalization
* state.num_canisters() as u64,
);
scheduler_round_limits.update_canister_round_limits(&round_limits);
if instructions_consumed == RoundInstructions::from(0) {
break state;
} else {
self.metrics
.inner_loop_consumed_non_zero_instructions_count
.inc();
}
if round_limits.reached() {
self.metrics
.inner_round_loop_consumed_max_instructions
.inc();
break state;
}
if total_heap_delta >= self.config.max_heap_delta_per_iteration {
break state;
}
{
let _induction_timer = self.metrics.round_inner_iteration_fin_induct.start_timer();
self.induct_messages_on_same_subnet(&mut state);
}
is_first_iteration = false;
drop(finalization_timer);
}; // end iteration loop.
{
let _timer = self
.metrics
.round_inner_heartbeat_overhead_duration
.start_timer();
// Remove all remaining `Heartbeat` and `GlobalTimer` tasks
// because they will be added again in the next round.
for canister_id in &heartbeat_and_timer_canister_ids {
let canister = state.canister_state_mut(canister_id).unwrap();
canister.system_state.task_queue.retain(|task| match task {
ExecutionTask::Heartbeat | ExecutionTask::GlobalTimer => false,
ExecutionTask::PausedExecution(..)
| ExecutionTask::PausedInstallCode(..)
| ExecutionTask::AbortedExecution { .. }
| ExecutionTask::AbortedInstallCode { .. } => true,
});
}
// Apply priority credit for all the finished executions.
for canister_id in &non_zero_priority_credit_canister_ids {
let canister = state.canister_state_mut(canister_id).unwrap();
match canister.next_execution() {
NextExecution::None
| NextExecution::StartNew
| NextExecution::ContinueInstallCode => canister.apply_priority_credit(),
NextExecution::ContinueLong => {}
}
}
}
// We only export metrics for "executable" canisters to ensure that the metrics
// are not polluted by canisters that haven't had any messages for a long time.
for canister_id in &round_filtered_canisters.active_canister_ids {
let canister_state = state.canister_state(canister_id).unwrap();
let canister_age = current_round.get()
- canister_state
.scheduler_state
.last_full_execution_round
.get();
self.metrics.canister_age.observe(canister_age as f64);
// If `canister_age` > 1 / `compute_allocation` the canister ought to have been
// scheduled.
let allocation = Ratio::new(
canister_state
.scheduler_state
.compute_allocation
.as_percent(),
100,
);
if *allocation.numer() > 0 && Ratio::from_integer(canister_age) > allocation.recip() {
self.metrics.canister_compute_allocation_violation.inc();
}
}
for (message_id, status) in ingress_execution_results {
self.ingress_history_writer
.set_status(&mut state, message_id, status);
}
self.metrics
.executable_canisters_per_round
.observe(round_filtered_canisters.active_canister_ids.len() as f64);
self.metrics
.heap_delta_rate_limited_canisters_per_round
.observe(round_filtered_canisters.rate_limited_canister_ids.len() as f64);
(state, round_filtered_canisters.active_canister_ids)
}
/// Executes canisters in parallel using the thread pool.
///
/// The function is invoked in each iteration of `inner_round`.
/// The given `canisters_by_thread` defines the priority of canisters.
/// Returns:
/// - the new states of the canisters,
/// - the ingress results,
/// - the maximum number of instructions executed on a thread,
/// - the total heap delta.
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn execute_canisters_in_inner_round(
&self,
canisters_by_thread: Vec<Vec<CanisterState>>,
round_id: ExecutionRound,
time: Time,
network_topology: Arc<NetworkTopology>,
measurement_scope: &MeasurementScope,
round_limits: &mut RoundLimits,
subnet_size: usize,
) -> (
Vec<CanisterState>,
Vec<(MessageId, IngressStatus)>,
NumBytes,
) {
let thread_pool = &mut self.thread_pool.borrow_mut();
let exec_env = self.exec_env.as_ref();
// If there are no more instructions left, then skip execution and
// return unchanged canisters.
if round_limits.reached() {
return (
canisters_by_thread.into_iter().flatten().collect(),
vec![],
NumBytes::from(0),
);
}
// Reserve the space for holding the result of each execution thread.
let mut results_by_thread: Vec<ExecutionThreadResult> = canisters_by_thread
.iter()
.map(|_| Default::default())
.collect();
// Distribute subnet available memory equally between the threads.
let round_limits_per_thread = RoundLimits {
instructions: round_limits.instructions,
subnet_available_memory: (round_limits.subnet_available_memory
/ self.config.scheduler_cores as i64),
compute_allocation_used: round_limits.compute_allocation_used,
};
// Run canisters in parallel. The results will be stored in `results_by_thread`.
thread_pool.scoped(|scope| {
// Zip together the input and the output of each thread.
// The input is a vector of canisters.
// The output is a reference to the corresponding item in `results_by_thread`.
let execution_data_by_thread = canisters_by_thread
.into_iter()
.zip(results_by_thread.iter_mut());
// Start execution of the canisters on each thread.
for (canisters, result) in execution_data_by_thread {
let network_topology = Arc::clone(&network_topology);
let metrics = Arc::clone(&self.metrics);
let logger = new_logger!(self.log; messaging.round => round_id.get());
let rate_limiting_of_heap_delta = self.rate_limiting_of_heap_delta;
let deterministic_time_slicing = self.deterministic_time_slicing;
let round_limits = RoundLimits {
instructions: round_limits.instructions,
subnet_available_memory: round_limits_per_thread.subnet_available_memory,
compute_allocation_used: round_limits.compute_allocation_used,
};
let config = &self.config;
scope.execute(move || {
*result = execute_canisters_on_thread(
canisters,
exec_env,
config,
metrics,
round_id,
time,
network_topology,
logger,
rate_limiting_of_heap_delta,
deterministic_time_slicing,
round_limits,
subnet_size,
);
});
}
});
// At this point all threads completed and stored their results.
// Aggregate `results_by_thread` to get the result of this function.
let mut canisters = Vec::new();
let mut ingress_results = Vec::new();
let mut total_instructions_executed = NumInstructions::from(0);
let mut max_instructions_executed_per_thread = NumInstructions::from(0);
let mut heap_delta = NumBytes::from(0);
for mut result in results_by_thread.into_iter() {
canisters.append(&mut result.canisters);
ingress_results.append(&mut result.ingress_results);
let instructions_executed = as_num_instructions(
round_limits_per_thread.instructions - result.round_limits.instructions,
);
total_instructions_executed += instructions_executed;
max_instructions_executed_per_thread =
max_instructions_executed_per_thread.max(instructions_executed);
self.metrics.compute_utilization_per_core.observe(
instructions_executed.get() as f64
/ round_limits_per_thread.instructions.get() as f64,
);
// Propagate the metrics from `execution_round_inner_iteration_thread`
// to `execution_round_inner_iteration`.
measurement_scope.add(
instructions_executed,
result.slices_executed,
result.messages_executed,
);
heap_delta += result.heap_delta;
}