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
//! # Thread Safety Primitives
//!
//! Based on "Formal methods for the unsafe side of the Force" (Antithesis, 2026).
//! Provides rigorously defined primitives for bridging FFI and multi-threaded boundaries.
//!
//! ## `RelaxedAtomic<T>`
//!
//! Provides inner mutability for `Copy` types via relaxed atomic loads and stores.
//! On x86_64 and ARM, relaxed loads/stores compile to the same instructions as
//! regular memory accesses (no `LOCK` prefix), making this a zero-overhead way to
//! achieve interior mutability for atomic-compatible types.
//!
//! For `u32`, provides `fetch_add` and `fetch_sub` methods that use atomic
//! read-modify-write operations. These are atomic but emit `LOCK`-prefixed
//! instructions on x86_64 (though without the stronger ordering fence overhead
//! of `SeqCst`).
//!
//! For simple load-mutate-store patterns, use the `load`–`store` methods:
//!
//! ```
//! # use vtcode_commons::thread_safety::RelaxedAtomic;
//! let counter = RelaxedAtomic::new(0u32);
//! let val = counter.load();
//! counter.store(val + 1);
//! ```
//!
//! For atomic increments/decrements, use `fetch_add`/`fetch_sub`:
//!
//! ```
//! # use vtcode_commons::thread_safety::RelaxedAtomic;
//! let counter = RelaxedAtomic::new(0u32);
//! counter.fetch_add(1); // Atomic, no race condition
//! ```
//!
//! # WARNING: Race Conditions Are Still Possible
//!
//! **Rust prevents data races, not race conditions.** (See "Rust Prevents Data Races,
//! Not Race Conditions" by Matthias Endler.)
//!
//! A data race is unsynchronized concurrent access where at least one side writes.
//! This is Undefined Behavior and Rust's type system prevents it.
//!
//! A **race condition** is any bug where the result depends on timing or thread
//! interleaving. Rust does *not* prevent these.
//!
//! The load–mutate–store pattern is *not* atomic as a whole:
//!
//! ```rust,ignore
//! // DANGEROUS: Two threads can interleave between load and store
//! let val = counter.load();
//! // <--- Another thread could load and store here
//! counter.store(val + 1);
//! ```
//!
//! This is the classic TOCTOU (Time-of-Check-Time-of-Use) bug. See the bank account
//! example in the article above.
//!
//! ## When to use
//!
//! Use when a field needs interior mutability and is accessed without
//! contention (same pattern as the original C code using plain loads/stores).
//! If you need multi-step atomic operations (CAS, fetch_add), use the
//! underlying `std::sync::atomic` types directly.
//!
//! ## When *not* to use
//!
//! Do not use when the operation must be atomic relative to other threads.
//! The load–mutate–store pattern is *not* atomic as a whole — it can race
//! with concurrent stores. Use only where the C code would have used a
//! non-atomic access that happens to be race-free by design.
//!
//! ## Correct usage examples
//!
//! ```rust,ignore
//! // CORRECT: Single-threaded or single-writer scenario
//! let flag = RelaxedAtomic::new(false);
//! // Only one thread ever writes to this
//! flag.store(true);
//!
//! // CORRECT: Using fetch_add for atomic increment
//! let counter = RelaxedAtomic::new(0u32);
//! counter.fetch_add(1); // Atomic, no race condition
//!
//! // CORRECT: Read-only scenario
//! let config = RelaxedAtomic::new(42u32);
//! let val = config.load(); // Multiple readers, no writers
//! ```
//!
//! ## Incorrect usage examples
//!
//! ```rust,ignore
//! // INCORRECT: Non-atomic compound operation
//! let counter = RelaxedAtomic::new(0u32);
//! // Two threads doing this simultaneously can lose updates
//! let val = counter.load();
//! counter.store(val + 1);
//!
//! // INCORRECT: Check-then-act (TOCTOU)
//! let balance = RelaxedAtomic::new(100u32);
//! // Thread A: check balance
//! let can_withdraw = balance.load() >= 100;
//! // <--- Thread B could withdraw here
//! // Thread A: withdraw
//! if can_withdraw {
//! balance.store(balance.load() - 100);
//! }
//! ```
use fmt;
use PhantomData;
use OnceLock;
use Ordering;
use ;
/// Trait for types that can be stored in a [`RelaxedAtomic`].
///
/// Implemented for `bool`, `u8`, `u16`, `u32`, `usize`, `i8`, `i16`, `i32`, `isize`.
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
impl_atomic_repr!;
/// Provides inner mutability for `Copy` types via relaxed atomic operations.
///
/// On x86_64 and ARM, relaxed loads and stores compile to the same instructions
/// as regular memory accesses — no `LOCK` prefix is emitted. This makes
/// `RelaxedAtomic` a zero-overhead way to achieve interior mutability without
/// the bus-lock cost of `fetch_*` or CAS operations.
///
/// Deliberately exposes only `load` and `store`. The `fetch_*` methods are
/// omitted because they emit `LOCK`-prefixed instructions with measurable
/// overhead. Instead, use the load–mutate–store pattern:
///
/// ```
/// # use vtcode_commons::thread_safety::RelaxedAtomic;
/// let counter = RelaxedAtomic::new(0u32);
/// let val = counter.load();
/// counter.store(val + 1);
/// ```
///
/// # When to use
///
/// Use when a field needs interior mutability and is accessed without
/// contention (same pattern as the original C code using plain loads/stores).
/// If you need multi-step atomic operations (CAS, fetch_add), use the
/// underlying `std::sync::atomic` types directly.
///
/// # When *not* to use
///
/// Do not use when the operation must be atomic relative to other threads.
/// The load–mutate–store pattern is *not* atomic as a whole — it can race
/// with concurrent stores. Use only where the C code would have used a
/// non-atomic access that happens to be race-free by design.
/// WARNING: This performs two separate relaxed loads. Under concurrent writes
/// the two values may come from different points in time. This is a race condition
/// (not a data race) — Rust does not prevent it.
///
/// Use this ONLY for diagnostic assertions, debug checks, or logging.
/// NEVER use this for correctness-critical decisions like:
/// - Deciding whether to proceed with an operation
/// - Checking if a resource is available
/// - Validating state transitions
///
/// For correctness-critical comparisons, load both values atomically first:
/// ```rust,ignore
/// let a = atomic_a.load(Ordering::SeqCst);
/// let b = atomic_b.load(Ordering::SeqCst);
/// if a == b { /* safe to proceed */ }
/// ```
/// Stores the `ThreadId` designated as the application's main thread.
///
/// Populated exactly once by [`designate_main_thread`]; subsequent calls are no-ops
/// so that callers can re-assert designation from defensive initialization paths
/// without panicking.
static MAIN_THREAD_ID: = new;
/// Designate the calling thread as the application's main thread.
///
/// Should be invoked once, early in `main`, before spawning any worker threads
/// that may try to obtain a [`MainThreadToken`]. Subsequent calls have no effect.
/// Returns the `ThreadId` previously designated as the main thread, if any.
/// A witness of execution that exists solely on a designated "Main Thread".
///
/// In FFI contexts, many libraries (especially legacy C++ or UI frameworks)
/// are not thread-safe and must only be initialized, called, or dropped from
/// the same thread that originally created them.
///
/// `MainThreadToken` is a zero-sized proof carrier. Possessing it proves
/// (at a type-system level) that the holder previously executed on the
/// designated main thread. The `PhantomData<*mut ()>` makes the token
/// `!Send + !Sync`, so a token obtained on the main thread cannot leak to
/// another thread through ordinary safe code.
>);
/// A wrapper that allows sending non-`Send` types across thread boundaries.
///
/// Re-exported from the `send_wrapper` crate. It implements `Send` and `Sync`
/// regardless of whether the wrapped type is thread-safe. However, it will
/// panic at runtime if the wrapped value is accessed from any thread other
/// than the one that created it.
pub use SendWrapper;