shuttle_engine/current.rs
1//! Information about the current thread and current Shuttle execution.
2//!
3//! This module provides access to information about the current Shuttle execution. It is useful for
4//! building tools that need to exploit Shuttle's total ordering of concurrent operations; for
5//! example, a tool that wants to check linearizability might want access to a global timestamp for
6//! events, which the [`context_switches`] function provides.
7//!
8//! This module also provides functions to manage the assocation of `labels` to threads and async tasks.
9//! Labels are typed values that can be associated with a task. They are useful for debugging: for
10//! instance, the `TaskName` label can be set to assign names to tasks to make debug output easier to read.
11//! Labels can also be used to build customized schedulers: for instance, they can be used to assign
12//! numeric weights to tasks, which can be used to implement a priority-preemptive scheduler.
13
14#[allow(deprecated)]
15use crate::runtime::execution::TASK_ID_TO_TAGS;
16use crate::runtime::execution::{CurrentSchedule, ExecutionState, LABELS};
17use crate::runtime::task::clock::VectorClock;
18pub use crate::runtime::task::labels::Labels;
19pub use crate::runtime::task::{ChildLabelFn, TaskId, TaskName};
20#[allow(deprecated)]
21pub use crate::runtime::task::{Tag, Taggable};
22use std::fmt::Debug;
23use std::sync::Arc;
24
25/// The number of context switches that happened so far in the current Shuttle execution.
26///
27/// Note that this is the number of *possible* context switches, i.e., including times when the
28/// scheduler decided to continue with the same task. This means the result can be used as a
29/// timestamp for atomic actions during an execution.
30///
31/// Panics if called outside of a Shuttle execution.
32pub fn context_switches() -> usize {
33 ExecutionState::context_switches()
34}
35
36/// Get the current thread's vector clock, or an empty clock if there is no current task.
37///
38/// Every `BatchSemaphore` operation calls this, so a `Drop` handler that touches a modelled
39/// primitive during execution teardown reaches it with `ExecutionState` unavailable or no task
40/// scheduled. Panicking there happens inside a destructor, which aborts the process instead of
41/// reporting the failure under investigation.
42pub fn clock() -> VectorClock {
43 ExecutionState::try_with(|state| {
44 let id = state.try_current().map(|me| me.id());
45 id.map(|id| state.get_clock(id).clone())
46 })
47 .ok()
48 .flatten()
49 .unwrap_or_else(VectorClock::new)
50}
51
52/// Gets the clock for the thread with the given task ID
53pub fn clock_for(task_id: TaskId) -> VectorClock {
54 ExecutionState::with(|state| state.get_clock(task_id).clone())
55}
56
57/// Apply the given function to the Labels for the specified task
58pub fn with_labels_for_task<F, T>(task_id: TaskId, f: F) -> T
59where
60 F: FnOnce(&mut Labels) -> T,
61{
62 LABELS.with(|cell| {
63 let mut map = cell.borrow_mut();
64 let m = map.entry(task_id).or_default();
65 f(m)
66 })
67}
68
69/// Get a label of the given type for the specified task, if any
70pub fn get_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId) -> Option<T> {
71 with_labels_for_task(task_id, |labels| labels.get().cloned())
72}
73
74/// Add the given label to the specified task, returning the old label for the type, if any
75pub fn set_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId, value: T) -> Option<T> {
76 with_labels_for_task(task_id, |labels| labels.insert(value))
77}
78
79/// Remove a label of the given type for the specified task, returning the old label for the type, if any
80pub fn remove_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId) -> Option<T> {
81 with_labels_for_task(task_id, |labels| labels.remove())
82}
83
84/// Get the debug name for a task
85pub fn get_name_for_task(task_id: TaskId) -> Option<TaskName> {
86 get_label_for_task::<TaskName>(task_id)
87}
88
89/// Set the debug name for a task, returning the old name, if any
90pub fn set_name_for_task(task_id: TaskId, task_name: impl Into<TaskName>) -> Option<TaskName> {
91 let task_name = task_name.into();
92 crate::annotations::record_name_for_task(task_id, &task_name);
93 // Do note that `record` simply appends the new name as a field, meaning the step span will end up looking something like this:
94 // step{task="main-thread(2)" task="Child"}
95 // when running with something like the `tracing_subscriber::fmt` subscriber.
96 // This either has to be lived with, or the task name should be set via the `ChildLabelFn` mechanism, or a different subscriber should be used
97 // (if this is done, then `record_steps_in_span` should be set to true as well), or Shuttle will have to be chanegd to recreate the Span
98 let res = ExecutionState::try_with(|state| {
99 state
100 .get_mut(task_id)
101 .step_span
102 .record("task", format!("{task_name:?}"));
103 });
104 if let Err(e) = res {
105 tracing::error!("`set_name_for_task` failed with error: {e:?}");
106 }
107 set_label_for_task::<TaskName>(task_id, task_name)
108}
109
110/// Gets the `TaskId` of the current task, or `None` if there is no current task.
111pub fn get_current_task() -> Option<TaskId> {
112 ExecutionState::with(|s| Some(s.try_current()?.id()))
113}
114
115/// Get the `TaskId` of the current task. Panics if there is no current task.
116pub fn me() -> TaskId {
117 get_current_task().unwrap()
118}
119
120/// Sets the number of scheduling steps used (wrt. the step bound) to 0.
121///
122/// The idea behind this is to run the test with some step bound, and then call this function whenever it is known that progress has been made.
123/// This allows tests to run with tighter step bounds, and to scale a test up without also changing the step bound.
124///
125/// NOTE: Be careful when using this, as if used wrongly it can be used to make a test execute forever.
126pub fn reset_step_count() {
127 ExecutionState::with(|s| s.steps_reset_at = CurrentSchedule::len());
128}
129
130/// Sets the `tag` field of the current task.
131/// Returns the `tag` which was there previously.
132#[deprecated]
133#[allow(deprecated)]
134pub fn set_tag_for_current_task(tag: Arc<dyn Tag>) -> Option<Arc<dyn Tag>> {
135 ExecutionState::set_tag_for_current_task(tag)
136}
137
138/// Gets the `tag` field of the current task.
139#[deprecated]
140#[allow(deprecated)]
141pub fn get_tag_for_current_task() -> Option<Arc<dyn Tag>> {
142 ExecutionState::get_tag_for_current_task()
143}
144
145/// Gets the `tag` field of the specified task.
146#[deprecated]
147#[allow(deprecated)]
148pub fn get_tag_for_task(task_id: TaskId) -> Option<Arc<dyn Tag>> {
149 TASK_ID_TO_TAGS.with(|cell| {
150 let map = cell.borrow();
151 map.get(&task_id).cloned()
152 })
153}
154
155/// Sets the `tag` field of the specified task.
156#[deprecated]
157#[allow(deprecated)]
158pub fn set_tag_for_task(task: TaskId, tag: Arc<dyn Tag>) -> Option<Arc<dyn Tag>> {
159 ExecutionState::set_tag_for_task(task, tag)
160}