Skip to main content

codewhale_runtime/
active_workshop.rs

1use std::sync::{Mutex, OnceLock};
2
3use codewhale_config::WorkshopConfig;
4
5static ACTIVE_WORKSHOP: OnceLock<Mutex<WorkshopConfig>> = OnceLock::new();
6
7#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
8static ACTIVE_WORKSHOP_TEST_SERIAL: OnceLock<Mutex<()>> = OnceLock::new();
9
10#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
11std::thread_local! {
12    static ACTIVE_WORKSHOP_TEST_SERIAL_HELD: std::cell::Cell<bool> = const {
13        std::cell::Cell::new(false)
14    };
15}
16
17/// Holds every test-side workshop activation behind one process-wide gate.
18/// The thread-local marker lets the owning current-thread test call
19/// `install_active` without trying to acquire its own non-reentrant lock.
20///
21/// The guard also owns the process-wide test env barrier, because holding this
22/// gate across a `reload_config` is holding it across `Settings::load` and
23/// `Config`'s env reads, which take that barrier (#6306). Field order is the
24/// release order: the serial gate first, then the barrier.
25#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
26pub struct ActiveWorkshopTestGuard {
27    _serial: std::sync::MutexGuard<'static, ()>,
28    _env: Option<crate::test_support::TestEnvLock>,
29}
30
31#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
32impl Drop for ActiveWorkshopTestGuard {
33    fn drop(&mut self) {
34        ACTIVE_WORKSHOP_TEST_SERIAL_HELD.with(|held| held.set(false));
35    }
36}
37
38/// Take the workshop gate, and the env barrier under it, in that order (#6306).
39///
40/// A holder of this gate keeps it across whole product calls — `reload_config`
41/// installs the budgets and then loads settings — and those calls read the
42/// environment through `test_support::with_test_env_lock`. A test that sealed
43/// the environment first and then reaches `install_active` through the very
44/// same `reload_config` takes the two locks in the opposite order, and the
45/// pair wedges the whole binary: `cargo test -p codewhale-tui --lib config`
46/// never returned, with dozens of unrelated tests queued on the barrier.
47/// Acquiring the barrier here, before the gate, makes that inversion
48/// impossible for every caller at once — the same shape as
49/// `provider_lake::lock_live_snapshot`.
50///
51/// Known limitation: this orders these two locks and nothing else. A future
52/// process-wide test gate held across product code has to join the same order
53/// rather than invent a third one.
54#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
55pub fn active_workshop_test_guard() -> ActiveWorkshopTestGuard {
56    assert!(
57        !ACTIVE_WORKSHOP_TEST_SERIAL_HELD.with(std::cell::Cell::get),
58        "active workshop test guard is not reentrant"
59    );
60    let env = if crate::test_support::current_thread_holds_test_env_lock() {
61        None
62    } else {
63        Some(crate::test_support::lock_test_env())
64    };
65    let serial = ACTIVE_WORKSHOP_TEST_SERIAL
66        .get_or_init(|| Mutex::new(()))
67        .lock()
68        .unwrap_or_else(std::sync::PoisonError::into_inner);
69    ACTIVE_WORKSHOP_TEST_SERIAL_HELD.with(|held| held.set(true));
70    ActiveWorkshopTestGuard {
71        _serial: serial,
72        _env: env,
73    }
74}
75
76fn active_workshop_slot() -> &'static Mutex<WorkshopConfig> {
77    ACTIVE_WORKSHOP.get_or_init(|| Mutex::new(WorkshopConfig::default()))
78}
79
80/// Install the process-wide workshop budgets used by read/tool compactors.
81///
82/// The returned immutable receipt is the snapshot written while the
83/// singleton lock was held. Callers that need evidence of their own
84/// activation can inspect it without racing a later process-wide update.
85pub fn install_active_workshop(config: Option<&WorkshopConfig>) -> WorkshopConfig {
86    #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
87    let _test_serial = if ACTIVE_WORKSHOP_TEST_SERIAL_HELD.with(std::cell::Cell::get) {
88        None
89    } else {
90        Some(
91            ACTIVE_WORKSHOP_TEST_SERIAL
92                .get_or_init(|| Mutex::new(()))
93                .lock()
94                .unwrap_or_else(std::sync::PoisonError::into_inner),
95        )
96    };
97    let snapshot = config.cloned().unwrap_or_default();
98    let mut slot = active_workshop_slot()
99        .lock()
100        .unwrap_or_else(std::sync::PoisonError::into_inner);
101    *slot = snapshot;
102    slot.clone()
103}
104
105/// Optional model-visible read budget, when the user opted in (#5367).
106#[must_use]
107pub fn active_read_result_max_bytes() -> Option<usize> {
108    active_workshop_slot()
109        .lock()
110        .ok()
111        .and_then(|cfg| cfg.read_result_max_bytes.filter(|n| *n > 0))
112}
113
114/// Optional model-visible tool-result budget, when the user opted in (#5367).
115#[must_use]
116pub fn active_tool_result_max_bytes() -> Option<usize> {
117    active_workshop_slot()
118        .lock()
119        .ok()
120        .and_then(|cfg| cfg.tool_result_max_bytes.filter(|n| *n > 0))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn workshop_byte_budgets_raise_floor_only() {
129        let _guard = active_workshop_test_guard();
130        let installed = install_active_workshop(Some(&WorkshopConfig {
131            large_output_threshold_tokens: None,
132            per_tool_thresholds: None,
133            read_result_max_bytes: Some(102_400),
134            tool_result_max_bytes: Some(80_000),
135        }));
136        assert_eq!(installed.read_result_max_bytes, Some(102_400));
137        assert_eq!(installed.tool_result_max_bytes, Some(80_000));
138        assert_eq!(active_read_result_max_bytes(), Some(102_400));
139        assert_eq!(active_tool_result_max_bytes(), Some(80_000));
140        let cleared = install_active_workshop(None);
141        assert_eq!(cleared.read_result_max_bytes, None);
142        assert_eq!(cleared.tool_result_max_bytes, None);
143        assert_eq!(active_read_result_max_bytes(), None);
144        assert_eq!(active_tool_result_max_bytes(), None);
145    }
146}