Skip to main content

iota_core/
execution_driver.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::sync::{Arc, Weak};
6
7use iota_common::{fatal, random::get_rng};
8use iota_macros::fail_point_async;
9use iota_metrics::{monitored_scope, spawn_monitored_task};
10use iota_types::error::IotaError;
11use rand::RngExt;
12use tokio::sync::{Semaphore, mpsc::UnboundedReceiver, oneshot};
13use tracing::{Instrument, error_span, info, instrument, warn};
14
15use crate::{authority::AuthorityState, execution_scheduler::PendingTransaction};
16
17#[cfg(test)]
18#[path = "unit_tests/execution_driver_tests.rs"]
19mod execution_driver_tests;
20
21const QUEUEING_DELAY_SAMPLING_RATIO: f64 = 0.05;
22
23/// When a notification that a new pending transaction is received we activate
24/// processing the transaction in a loop.
25#[instrument("start_execute_pending_transactions", level = "trace", skip_all)]
26pub async fn execution_process(
27    authority_state: Weak<AuthorityState>,
28    mut rx_ready_transactions: UnboundedReceiver<PendingTransaction>,
29    mut rx_execution_shutdown: oneshot::Receiver<()>,
30) {
31    info!("Starting pending transactions execution process.");
32
33    // Rate limit concurrent executions to # of cpus.
34    let limit = Arc::new(Semaphore::new(num_cpus::get()));
35
36    // Loop whenever there is a signal that a new transactions is ready to process.
37    loop {
38        let _scope = monitored_scope("ExecutionDriver::loop");
39
40        let transaction;
41        let execution_env;
42        let txn_ready_time;
43        // Held until execution completes, keeping the executing-certificates gauge
44        // accurate for ExecutionScheduler (always None for TransactionManager).
45        let executing_guard;
46        tokio::select! {
47            result = rx_ready_transactions.recv() => {
48                if let Some(pending_tx) = result {
49                    transaction = pending_tx.transaction;
50                    execution_env = pending_tx.execution_env;
51                    txn_ready_time = pending_tx.stats.ready_time.unwrap();
52                    executing_guard = pending_tx.executing_guard;
53                } else {
54                    // Should only happen after the AuthorityState has shut down and
55                    // the scheduler has dropped its tx_ready_transactions sender.
56                    info!("No more transaction will be received. Exiting executor ...");
57                    return;
58                };
59            }
60            _ = &mut rx_execution_shutdown => {
61                info!("Shutdown signal received. Exiting executor ...");
62                return;
63            }
64        };
65
66        let authority = if let Some(authority) = authority_state.upgrade() {
67            authority
68        } else {
69            // Terminate the execution if authority has already shutdown, even if there can
70            // be more items in rx_ready_transactions.
71            info!("Authority state has shutdown. Exiting ...");
72            return;
73        };
74        authority.metrics.execution_driver_dispatch_queue.dec();
75
76        // TODO: Ideally execution_driver should own a copy of epoch store and recreate
77        // each epoch.
78        let epoch_store = authority.load_epoch_store_one_call_per_task();
79
80        let digest = *transaction.digest();
81
82        if epoch_store.epoch() != transaction.epoch() {
83            info!(
84                ?digest,
85                cur_epoch = epoch_store.epoch(),
86                tx_epoch = transaction.epoch(),
87                "Ignoring transaction from previous epoch."
88            );
89            continue;
90        }
91
92        let limit = limit.clone();
93        // hold semaphore permit until task completes. unwrap ok because we never close
94        // the semaphore in this context.
95        let permit = limit.acquire_owned().await.unwrap();
96
97        if get_rng().random_range(0.0..1.0) < QUEUEING_DELAY_SAMPLING_RATIO {
98            authority
99                .metrics
100                .execution_queueing_latency
101                .report(txn_ready_time.elapsed());
102            if let Some(latency) = authority.metrics.execution_queueing_latency.latency() {
103                authority
104                    .metrics
105                    .execution_queueing_delay_s
106                    .observe(latency.as_secs_f64());
107            }
108        }
109
110        authority.metrics.execution_rate_tracker.lock().record();
111
112        // Transaction execution can take significant time, so run it in a separate
113        // task.
114        let epoch_store_clone = epoch_store.clone();
115        spawn_monitored_task!(epoch_store.within_alive_epoch(async move {
116            let _scope = monitored_scope("ExecutionDriver::task");
117            let _guard = permit;
118            // Held for the whole execution, not dropped at dispatch:
119            // `num_pending_transactions` counts executing transactions too, and
120            // overload admission reads that count.
121            let _executing_guard = executing_guard;
122            if let Ok(true) = authority.try_is_tx_already_executed(&digest) {
123                return;
124            }
125
126            fail_point_async!("transaction_execution_delay");
127
128            match authority.try_execute_immediately(
129                &transaction,
130                execution_env,
131                &epoch_store_clone,
132            ) {
133                Err(IotaError::ValidatorHaltedAtEpochEnd) => {
134                    warn!("Could not execute transaction {digest:?} because validator is halted at epoch end.");
135                    return;
136                }
137                Err(e) => {
138                    fatal!("Failed to execute transaction {digest:?}! error={e}");
139                }
140                _ => (),
141            }
142            authority
143                .metrics
144                .execution_driver_executed_transactions
145                .inc();
146        }.instrument(error_span!("executing_pending_transaction", tx_digest = ?digest))));
147    }
148}