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
//! Response cycling state management.
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
/// A lock-free atomic cycler that packs response index and repeat index into a single AtomicU64
#[derive(Default)]
pub struct RuleCycler(AtomicU64);
fn split(v: u64) -> (u32, u32) {
((v >> 32) as u32, v as u32)
}
fn join(resp_idx: u32, repeat_idx: u32) -> u64 {
(u64::from(resp_idx) << 32) | u64::from(repeat_idx)
}
fn advance(
(mut resp_idx, mut repeat_idx): (u32, u32),
response_count: u32,
repeat_count: u32,
) -> (u32, u32) {
repeat_idx = repeat_idx.saturating_add(1);
if repeat_idx >= repeat_count {
repeat_idx = 0;
resp_idx += 1;
if resp_idx >= response_count {
resp_idx = 0;
}
}
(resp_idx, repeat_idx)
}
impl RuleCycler {
#[must_use]
pub const fn new() -> Self {
Self(AtomicU64::new(0))
}
#[must_use]
pub fn peek_response_index(&self, response_count: u32) -> u32 {
let value = self.0.load(Ordering::SeqCst);
let (resp_idx, _repeat_idx) = split(value);
resp_idx.min(response_count.saturating_sub(1))
}
/// The raw `(response index, repeat index)` cursor, unclamped.
#[must_use]
pub fn peek_position(&self) -> (u32, u32) {
split(self.0.load(Ordering::SeqCst))
}
/// Point the cursor at `resp_idx`, at the start of its repeat run.
pub fn set(&self, resp_idx: u32) {
self.0.store(join(resp_idx, 0), Ordering::SeqCst);
}
/// Point the cursor at `(resp_idx, repeat_idx)`, as a restored `--datadir` cursor names it
/// (issue #1603).
pub fn set_position(&self, resp_idx: u32, repeat_idx: u32) {
self.0.store(join(resp_idx, repeat_idx), Ordering::SeqCst);
}
pub fn reset(&self) {
self.0.store(0, Ordering::SeqCst);
}
/// Get current response index for a rule, handling repeat behavior
/// Returns the index to use for this request
#[must_use]
pub fn get_response_index_advance(
&self,
response_count: u32,
mut repeat_for_response: impl FnMut(u32) -> Option<u32>,
) -> u32 {
// SeqCst (not Relaxed): the advanced cursor must be *published* so a strictly-sequential
// zero-latency next request — reached via a different tokio worker thread after the client
// handoff — observes it, rather than serving a stale repeat branch (issue #565). Matches the
// ordering the sibling per-imposter cross-request state already uses (`enabled`, journal
// counts). The window is invisible under load-free / spawn transports but real on the
// in-process embedded runtime on loaded runners.
// `update` (the infallible CAS loop): the step itself cannot fail.
let old_value = self
.0
.update(Ordering::SeqCst, Ordering::SeqCst, |old_value| {
let (mut resp_idx, repeat_idx) = split(old_value);
if resp_idx >= response_count {
resp_idx = response_count.saturating_sub(1);
}
let repeat_count = repeat_for_response(resp_idx).unwrap_or(1).max(1);
let (resp_idx, repeat_idx) =
advance((resp_idx, repeat_idx), response_count, repeat_count);
join(resp_idx, repeat_idx)
});
split(old_value).0
}
}
impl fmt::Debug for RuleCycler {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (response_idx, repeat_idx) = split(self.0.load(Ordering::SeqCst));
f.debug_struct("RuleCycler")
.field("response_idx", &response_idx)
.field("repeat_idx", &repeat_idx)
.finish()
}
}
/// Trait for types that can have a repeat behavior
pub trait HasRepeatBehavior {
fn get_repeat(&self) -> Option<u32>;
}
#[cfg(test)]
mod rule_cycler_ordering_tests {
use super::*;
use std::sync::Arc;
use std::sync::mpsc;
/// AC1 — durable regression tripwire. A pure memory-visibility fix can't be caught by a
/// deterministic runtime test on a strong memory model, so gate the source instead: the cursor's
/// atomic ops must stay on a published ordering (`SeqCst`) and never regress to the relaxed
/// ordering that let a zero-latency next request observe a stale cursor (issue #565). The needle
/// is assembled at runtime so this assertion never matches its own source.
#[test]
fn rule_cycler_stays_on_published_ordering() {
let src = include_str!("cycler.rs");
let regressed = format!("Ordering::{}", "Relaxed");
assert!(
!src.contains(®ressed),
"RuleCycler atomic ops must use SeqCst (a published ordering), not the relaxed ordering — issue #565"
);
}
/// `peek_response_index` reports the response the next request will get without advancing,
/// and is clamped into range when the stub now has fewer responses than the cursor points at.
/// `reset` returns the cursor to the first response. Neither was asserted anywhere (both
/// survived as mutants in the weekly cargo-mutants run, #1345).
#[test]
fn peek_reports_the_next_response_without_advancing_and_reset_rewinds() {
let cycler = RuleCycler::new();
let once = |_: u32| None::<u32>;
assert_eq!(cycler.peek_response_index(3), 0);
assert_eq!(cycler.get_response_index_advance(3, once), 0);
assert_eq!(cycler.get_response_index_advance(3, once), 1);
assert_eq!(
cycler.peek_response_index(3),
2,
"peek sees the advanced cursor"
);
assert_eq!(
cycler.peek_response_index(3),
2,
"and peeking does not advance it"
);
assert_eq!(
cycler.peek_response_index(2),
1,
"a cursor past the last response is clamped to it"
);
assert_eq!(cycler.get_response_index_advance(3, once), 2);
assert_eq!(
cycler.get_response_index_advance(3, once),
0,
"wraps after the last"
);
assert_eq!(cycler.peek_response_index(3), 1);
cycler.reset();
assert_eq!(
cycler.peek_response_index(3),
0,
"reset rewinds to the first response"
);
assert_eq!(cycler.get_response_index_advance(3, once), 0);
}
/// AC2 — the exact cycling the flaky `/retry` fixture asserts: two responses where the first
/// repeats twice and the second once, i.e. index sequence 0,0,1 then wrap (503,503,200,...).
#[test]
fn cycler_matches_retry_fixture_pattern() {
let cycler = RuleCycler::new();
let repeats = [2u32, 1u32];
let repeat_for = |i: u32| repeats.get(i as usize).copied();
let got: Vec<u32> = (0..6)
.map(|_| cycler.get_response_index_advance(2, repeat_for))
.collect();
assert_eq!(
got,
vec![0, 0, 1, 0, 0, 1],
"repeat:[2,1] must cycle 503,503,200 and wrap"
);
}
/// AC3 — a strictly-sequential client hands the cursor from one worker thread to the next; the
/// request that crosses a repeat boundary must observe the prior request's advance. Emulates
/// the conformance replay (pull exactly one index, hand off, pull the next) with the pulls
/// landing on alternating threads, and asserts the concatenated sequence is the exact
/// deterministic cycling — no skipped or duplicated index across the hand-off.
#[test]
fn concurrent_strict_handoff_preserves_cycling() {
// Two responses, first repeats twice: expected 0,0,1,0,0,1,... (the /retry shape).
const ROUNDS: usize = 2_000;
let cycler = Arc::new(RuleCycler::new());
let (to_b, from_a) = mpsc::channel::<()>();
let (to_a, from_b) = mpsc::channel::<u32>();
let cycler_b = Arc::clone(&cycler);
let handle = std::thread::spawn(move || {
let repeats = [2u32, 1u32];
let repeat_for = |i: u32| repeats.get(i as usize).copied();
while from_a.recv().is_ok() {
let idx = cycler_b.get_response_index_advance(2, repeat_for);
if to_a.send(idx).is_err() {
break;
}
}
});
let repeats = [2u32, 1u32];
let repeat_for = |i: u32| repeats.get(i as usize).copied();
let mut seq = Vec::with_capacity(ROUNDS);
for round in 0..ROUNDS {
// Even rounds pulled on this (main) thread, odd rounds on the worker — so consecutive
// pulls alternate threads, exercising the cross-thread hand-off on every boundary.
if round % 2 == 0 {
seq.push(cycler.get_response_index_advance(2, repeat_for));
} else {
to_b.send(()).expect("worker alive");
seq.push(from_b.recv().expect("worker replied"));
}
}
drop(to_b);
handle.join().expect("worker joined");
let expected: Vec<u32> = (0..ROUNDS).map(|i| [0, 0, 1][i % 3]).collect();
assert_eq!(
seq, expected,
"cross-thread strict hand-off must observe every prior advance (no stale cursor)"
);
}
}