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
37pub fn clock() -> VectorClock {
38 ExecutionState::with(|state| {
39 let me = state.current();
40 state.get_clock(me.id()).clone()
41 })
42}
43
44/// Gets the clock for the thread with the given task ID
45pub fn clock_for(task_id: TaskId) -> VectorClock {
46 ExecutionState::with(|state| state.get_clock(task_id).clone())
47}
48
49/// Apply the given function to the Labels for the specified task
50pub fn with_labels_for_task<F, T>(task_id: TaskId, f: F) -> T
51where
52 F: FnOnce(&mut Labels) -> T,
53{
54 LABELS.with(|cell| {
55 let mut map = cell.borrow_mut();
56 let m = map.entry(task_id).or_default();
57 f(m)
58 })
59}
60
61/// Get a label of the given type for the specified task, if any
62pub fn get_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId) -> Option<T> {
63 with_labels_for_task(task_id, |labels| labels.get().cloned())
64}
65
66/// Add the given label to the specified task, returning the old label for the type, if any
67pub fn set_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId, value: T) -> Option<T> {
68 with_labels_for_task(task_id, |labels| labels.insert(value))
69}
70
71/// Remove a label of the given type for the specified task, returning the old label for the type, if any
72pub fn remove_label_for_task<T: Clone + Debug + 'static>(task_id: TaskId) -> Option<T> {
73 with_labels_for_task(task_id, |labels| labels.remove())
74}
75
76/// Get the debug name for a task
77pub fn get_name_for_task(task_id: TaskId) -> Option<TaskName> {
78 get_label_for_task::<TaskName>(task_id)
79}
80
81/// Set the debug name for a task, returning the old name, if any
82pub fn set_name_for_task(task_id: TaskId, task_name: impl Into<TaskName>) -> Option<TaskName> {
83 let task_name = task_name.into();
84 crate::annotations::record_name_for_task(task_id, &task_name);
85 // Do note that `record` simply appends the new name as a field, meaning the step span will end up looking something like this:
86 // step{task="main-thread(2)" task="Child"}
87 // when running with something like the `tracing_subscriber::fmt` subscriber.
88 // 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
89 // (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
90 let res = ExecutionState::try_with(|state| {
91 state
92 .get_mut(task_id)
93 .step_span
94 .record("task", format!("{task_name:?}"));
95 });
96 if let Err(e) = res {
97 tracing::error!("`set_name_for_task` failed with error: {e:?}");
98 }
99 set_label_for_task::<TaskName>(task_id, task_name)
100}
101
102/// Gets the `TaskId` of the current task, or `None` if there is no current task.
103pub fn get_current_task() -> Option<TaskId> {
104 ExecutionState::with(|s| Some(s.try_current()?.id()))
105}
106
107/// Get the `TaskId` of the current task. Panics if there is no current task.
108pub fn me() -> TaskId {
109 get_current_task().unwrap()
110}
111
112/// Sets the number of scheduling steps used (wrt. the step bound) to 0.
113///
114/// 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.
115/// This allows tests to run with tighter step bounds, and to scale a test up without also changing the step bound.
116///
117/// NOTE: Be careful when using this, as if used wrongly it can be used to make a test execute forever.
118pub fn reset_step_count() {
119 ExecutionState::with(|s| s.steps_reset_at = CurrentSchedule::len());
120}
121
122/// Sets the `tag` field of the current task.
123/// Returns the `tag` which was there previously.
124#[deprecated]
125#[allow(deprecated)]
126pub fn set_tag_for_current_task(tag: Arc<dyn Tag>) -> Option<Arc<dyn Tag>> {
127 ExecutionState::set_tag_for_current_task(tag)
128}
129
130/// Gets the `tag` field of the current task.
131#[deprecated]
132#[allow(deprecated)]
133pub fn get_tag_for_current_task() -> Option<Arc<dyn Tag>> {
134 ExecutionState::get_tag_for_current_task()
135}
136
137/// Gets the `tag` field of the specified task.
138#[deprecated]
139#[allow(deprecated)]
140pub fn get_tag_for_task(task_id: TaskId) -> Option<Arc<dyn Tag>> {
141 TASK_ID_TO_TAGS.with(|cell| {
142 let map = cell.borrow();
143 map.get(&task_id).cloned()
144 })
145}
146
147/// Sets the `tag` field of the specified task.
148#[deprecated]
149#[allow(deprecated)]
150pub fn set_tag_for_task(task: TaskId, tag: Arc<dyn Tag>) -> Option<Arc<dyn Tag>> {
151 ExecutionState::set_tag_for_task(task, tag)
152}