Skip to main content

git_policy_cli/
transaction_phase.rs

1//! What:
2//!  Test-only transaction phase markers for crash and interleaving suites.
3//!  An explicit environment variable arms one marker:
4//!  `CLI_GIT_TEST_ONLY_PHASE_SIGNAL=<phase>:kill` ends the process with `SIGKILL` at the phase,
5//!  `<phase>:kill:<directory>` writes `<directory>/<phase>.reached` first,
6//!  and `<phase>:pause:<directory>` writes that marker and waits until `<directory>/<phase>.release` exists.
7//!  A repeatable phase numbers its files by occurrence: `<phase>-<n>.reached`.
8//! Why:
9//!  Crash suites need a deterministic point to kill the wrapper.
10//!  The marker is compiled into the release executable, but only the explicit variable arms it,
11//!  and a malformed value fails the invocation at every phase it reaches instead of being ignored
12//!  (`src/policy-engine/commit-transaction-test-phase.ts`).
13//!
14//! In TS you'd write (pseudocode):
15//! ```ts
16//! await reachTransactionPhase({ phase: 'ref-updated' });
17//! ```
18
19/// Diagnostic output to standard error when a marker fires.
20use super::diagnostic_log::warn;
21/// Strict JSON string quoting for the refusal message, as `JSON.stringify` writes it.
22use serde_json::to_string as json_string;
23/// `OsStr` is borrowed operating-system text, and `Path`/`PathBuf` are filesystem paths.
24use std::path::{Path, PathBuf};
25use std::time::Duration;
26
27/// Environment variable arming one phase marker.
28pub const PHASE_SIGNAL_VARIABLE: &str = "CLI_GIT_TEST_ONLY_PHASE_SIGNAL";
29
30/// Poll interval while paused.
31const RELEASE_POLL: Duration = Duration::from_millis(20);
32
33/// What:
34///  One transaction phase a marker can name.
35/// Why:
36///   The landing reaches four of them; the others are reached by the commit path and the replay.
37///
38/// In TS you'd write (pseudocode):
39/// ```ts
40/// type TransactionTestPhase = 'capture-locked' | 'preparation-done' | 'landing-locked' | ...;
41/// ```
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum Phase {
44    /// The invocation capture is locked.
45    CaptureLocked,
46    /// Preparation wrote its prepared record.
47    PreparationDone,
48    /// The landing lock and the real index lock are held.
49    LandingLocked,
50    /// The shadow's objects are migrated into the kept pack.
51    ObjectsMigrated,
52    /// The target advanced by compare-and-swap.
53    RefUpdated,
54    /// The post-index is installed as the real index.
55    IndexInstalled,
56    /// A landing race was lost; repeatable, numbered by occurrence.
57    RaceLost,
58}
59
60/// Every phase in transaction order, which the refusal message lists.
61pub const TRANSACTION_TEST_PHASES: [Phase; 7] = [
62    Phase::CaptureLocked,
63    Phase::PreparationDone,
64    Phase::LandingLocked,
65    Phase::ObjectsMigrated,
66    Phase::RefUpdated,
67    Phase::IndexInstalled,
68    Phase::RaceLost,
69];
70
71/// Phase names in transaction order.
72impl Phase {
73    /// What:
74    ///  The phase's name as the marker variable spells it.
75    /// Why:
76    ///   Marker files and the refusal message use these names.
77    ///
78    /// In TS you'd write (pseudocode):
79    /// ```ts
80    /// phase // 'landing-locked'
81    /// ```
82    pub fn name(self) -> &'static str {
83        match self {
84            Phase::CaptureLocked => return "capture-locked",
85            Phase::PreparationDone => return "preparation-done",
86            Phase::LandingLocked => return "landing-locked",
87            Phase::ObjectsMigrated => return "objects-migrated",
88            Phase::RefUpdated => return "ref-updated",
89            Phase::IndexInstalled => return "index-installed",
90            Phase::RaceLost => return "race-lost",
91        }
92    }
93}
94
95/// What:
96///  What a marker does at its phase.
97/// Why:
98///   `kill` ends the process; `pause` hands control to the test until the release file exists.
99///
100/// In TS you'd write (pseudocode):
101/// ```ts
102/// action: 'kill' | 'pause'
103/// ```
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
105pub enum PhaseAction {
106    /// Ends the process with `SIGKILL`.
107    Kill,
108    /// Waits for the release file.
109    Pause,
110}
111
112/// What:
113///  One parsed marker.
114/// Why:
115///   Parsing happens at every phase reached, so a malformed value fails wherever it is read.
116///
117/// In TS you'd write (pseudocode):
118/// ```ts
119/// type PhaseSignal = { phase: TransactionTestPhase; action: 'kill' | 'pause'; directory?: string };
120/// ```
121#[derive(Clone, Debug, Eq, PartialEq)]
122pub struct PhaseSignal {
123    /// Armed phase.
124    pub phase: Phase,
125    /// What happens at the phase.
126    pub action: PhaseAction,
127    /// Marker directory; required for `pause`, absent or empty otherwise.
128    pub directory: Option<PathBuf>,
129}
130
131/// What:
132///  The marker variable is malformed.
133/// Why:
134///   The invocation fails with this text instead of ignoring the value.
135///
136/// In TS you'd write (pseudocode):
137/// ```ts
138/// new TestPhaseSignalError(value)
139/// ```
140#[derive(Clone, Debug, Eq, PartialEq)]
141pub struct PhaseSignalError {
142    /// The rejected value, as read.
143    pub value: String,
144}
145
146/// Message text naming the variable, the quoted value and the accepted forms.
147impl std::fmt::Display for PhaseSignalError {
148    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        let quoted: String = json_string(self.value.as_str()).unwrap_or_else(|_| format!("{:?}", self.value));
150        let phases: Vec<&str> = TRANSACTION_TEST_PHASES.iter().map(|phase| { return phase.name(); }).collect();
151        return write!(
152            formatter,
153            "{PHASE_SIGNAL_VARIABLE}={quoted} is not <phase>:kill[:<absolute directory>] or <phase>:pause:<absolute directory> with a phase among {}.",
154            phases.join(", ")
155        )
156    }
157}
158
159/// Error type of the marker reach.
160impl std::error::Error for PhaseSignalError {}
161
162/// What:
163///  Why a reached phase could not be completed.
164/// Why:
165///   A malformed value and a failed marker write are both fatal to the invocation.
166///
167/// In TS you'd write (pseudocode):
168/// ```ts
169/// TestPhaseSignalError | NodeJS.ErrnoException
170/// ```
171#[derive(Debug)]
172pub enum PhaseMarkerError {
173    /// The marker variable is malformed.
174    Malformed(PhaseSignalError),
175    /// Writing the reached marker or polling the release file failed.
176    Io(std::io::Error),
177}
178
179/// Message text of either failure.
180impl std::fmt::Display for PhaseMarkerError {
181    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        match self {
183            PhaseMarkerError::Malformed(error) => return write!(formatter, "{error}"),
184            PhaseMarkerError::Io(error) => return write!(formatter, "transaction phase marker failed: {error}"),
185        }
186    }
187}
188
189/// Error type of the marker reach.
190impl std::error::Error for PhaseMarkerError {}
191
192/// What:
193///  Parses the marker variable.
194/// Why:
195///   The phase must match exactly, the action must be `kill` or `pause`,
196///  a pause needs a directory, and a directory must be absolute.
197///  An empty directory after `kill` counts as no directory, as the incumbent's parser reads it.
198///
199/// In TS you'd write (pseudocode):
200/// ```ts
201/// parsePhaseSignal(value);
202/// ```
203pub fn parse_phase_signal(value: &str) -> Result<PhaseSignal, PhaseSignalError> {
204    let refusal = || {
205        return PhaseSignalError {
206            value: value.to_string(),
207        };
208    };
209    let Some(phase_end) = value.find(':') else {
210        return Err(refusal());
211    };
212    let rest: &str = &value[phase_end + 1..];
213    let (action_text, directory_text) = match rest.find(':') {
214        Some(action_end) => (&rest[..action_end], &rest[action_end + 1..]),
215        None => (rest, ""),
216    };
217    let Some(phase) = TRANSACTION_TEST_PHASES
218        .iter()
219        .copied()
220        .find(|candidate| { return candidate.name() == &value[..phase_end]; })
221    else {
222        return Err(refusal());
223    };
224    let action: PhaseAction = match action_text {
225        "kill" => PhaseAction::Kill,
226        "pause" => PhaseAction::Pause,
227        _ => return Err(refusal()),
228    };
229    if (action == PhaseAction::Pause && directory_text.is_empty())
230        || (!directory_text.is_empty() && !Path::new(directory_text).is_absolute())
231    {
232        return Err(refusal());
233    }
234    return Ok(PhaseSignal {
235        phase,
236        action,
237        directory: if directory_text.is_empty() {
238            None
239        } else {
240            Some(PathBuf::from(directory_text))
241        },
242    });
243}
244
245/// What:
246///  Ends the process with `SIGKILL`, the signal no handler can catch.
247/// Why:
248///   A crash suite needs the process to die with no cleanup, as a power loss would leave it.
249///
250/// In TS you'd write (pseudocode):
251/// ```ts
252/// process.kill(process.pid, 'SIGKILL');
253/// ```
254#[cfg(unix)]
255fn kill_self() -> ! {
256    // SAFETY: `getpid` and `kill` take no pointers, and signalling this process with `SIGKILL` cannot return.
257    unsafe {
258        libc::kill(libc::getpid(), libc::SIGKILL);
259    }
260    std::process::abort()
261}
262
263/// What:
264///  Ends the process at once on platforms without `SIGKILL`, running no cleanup.
265/// Why:
266///   The marker must not run destructors, as an uncatchable kill would not.
267///
268/// In TS you'd write (pseudocode):
269/// ```ts
270/// process.kill(process.pid, 'SIGKILL');
271/// ```
272// UNTESTED ON WINDOWS: no gate compiles or runs this branch (the crate does not build for Windows; README, Requirements).
273#[cfg(not(unix))]
274fn kill_self() -> ! {
275    std::process::exit(137)
276}
277
278/// What:
279///  Waits until the release file exists, polling every 20 milliseconds.
280/// Why:
281///   A paused phase lets a test inspect the repository before the transaction continues.
282///
283/// In TS you'd write (pseudocode):
284/// ```ts
285/// for (;;) { try { await access(path); return; } catch { await wait(20); } }
286/// ```
287fn await_release(path: &Path) {
288    while !path.exists() {
289        std::thread::sleep(RELEASE_POLL);
290    }
291}
292
293/// What:
294///  Reaches one phase with the marker variable's value, killing or pausing when it is armed for this phase.
295/// Why:
296///   Tests pass the value directly; the production entry reads the process environment.
297///
298/// In TS you'd write (pseudocode):
299/// ```ts
300/// await reachTransactionPhase({ phase, occurrence, environment });
301/// ```
302pub(crate) fn reach_with_value(
303    value: Option<&str>,
304    phase: Phase,
305    occurrence: Option<u64>,
306) -> Result<(), PhaseMarkerError> {
307    let Some(armed) = value.filter(|text| { return !text.is_empty(); }) else {
308        return Ok(());
309    };
310    let signal: PhaseSignal = parse_phase_signal(armed).map_err(PhaseMarkerError::Malformed)?;
311    if signal.phase != phase {
312        return Ok(());
313    }
314    let stem: String = match occurrence {
315        Some(number) => format!("{}-{number}", phase.name()),
316        None => phase.name().to_string(),
317    };
318    warn(
319        "transactionPhase",
320        &format!("{PHASE_SIGNAL_VARIABLE} reached {stem}: {:?}", signal.action),
321    );
322    if let Some(directory) = signal.directory.as_deref() {
323        std::fs::write(directory.join(format!("{stem}.reached")), std::process::id().to_string())
324            .map_err(PhaseMarkerError::Io)?;
325    }
326    match signal.action {
327        PhaseAction::Kill => kill_self(),
328        PhaseAction::Pause => {
329            let directory: &Path = signal.directory.as_deref().unwrap_or(Path::new(""));
330            await_release(&directory.join(format!("{stem}.release")));
331            return Ok(());
332        }
333    }
334}
335
336/// What:
337///  Reaches one phase, reading the marker variable from the process environment.
338/// Why:
339///   The landing calls this at each marked phase; an unset variable costs one environment lookup.
340///
341/// In TS you'd write (pseudocode):
342/// ```ts
343/// await reachTransactionPhase({ phase: 'landing-locked' });
344/// ```
345pub fn reach_transaction_phase(phase: Phase, occurrence: Option<u64>) -> Result<(), PhaseMarkerError> {
346    let value: Option<String> = std::env::var_os(PHASE_SIGNAL_VARIABLE).map(|text: std::ffi::OsString| { return text.to_string_lossy().into_owned(); });
347    return reach_with_value(value.as_deref(), phase, occurrence);
348}
349
350/// Phase marker controls stay out of the production code path.
351#[cfg(test)]
352#[path = "transaction_phase_tests.rs"]
353mod tests;