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
//! What:
//! Startup recovery across every per-transaction directory of one worktree.
//! Why:
//! Live owners are skipped;
//! dead owners are recovered oldest first;
//! dead transactions that
//! entered the landing critical section are recovered only while holding the landing lock,
//! so recovery never races a live lander (`src/policy-engine/commit-transaction-recovery-scan.ts`,
//! `commit-landing-lock.ts`).
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! const outcomes = await recoverRegisteredTransactions({ root, gitPath, effectiveCwd });
//! ```
/// Debug diagnostics.
use super::diagnostic_log::debug;
/// Owner locks.
use super::owner_lock::{
DEFAULT_POLL_DELAY, OwnerLock, SilentWait, acquire_owner_lock, retire_lock_of_dead_owner,
};
/// The fail-closed recovery failure.
use super::recovery_error::{RecoveryError, io_failure};
/// Landing evidence.
use super::recovery_evidence::{entered_landing, has_landing_record};
/// Owner inspection and order.
use super::recovery_inspect::{
InspectedEntry, OwnerEvidence, inspect_registry_entry, oldest_first,
};
/// Dead-transaction recovery.
use super::recovery_landing::{RecoveryAction, RecoveryPlace, recover_dead_transaction};
/// Owner liveness.
use super::transaction_owner::OwnerLiveness;
/// Registry listing and names.
use super::transaction_registry::{
EntryKind, LANDING_LOCK_NAME, RESERVATION_LOCK_NAME, RegistryEntry, list_transaction_entries,
};
/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
use std::path::{Path, PathBuf};
/// What:
/// What recovery did for one directory.
/// Why:
/// `CommitTransactionRecoveryOutcome`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type CommitTransactionRecoveryOutcome = { directory: string; action: CommitTransactionRecoveryAction };
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecoveryOutcome {
/// The directory examined.
pub directory: PathBuf,
/// What recovery did,
/// or why it left the directory.
pub action: RecoveryAction,
}
/// What:
/// Recover or skip one inspected entry without a landing record,
/// or one whose landing the
/// caller serializes.
/// Why:
/// `recoverInspectedEntry`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function recoverInspectedEntry({ inspected, gitPath, effectiveCwd }): Promise<CommitTransactionRecoveryAction>;
/// ```
pub fn recover_inspected_entry(
place: &RecoveryPlace,
inspected: &InspectedEntry,
) -> Result<RecoveryAction, RecoveryError> {
let path: &Path = inspected.entry.path.as_path();
match &inspected.owner {
OwnerEvidence::Vanished => {
debug(
"recoverInspectedEntry",
format!(
"transaction finished while recovery listed it: {}",
path.display()
)
.as_str(),
);
return Ok(RecoveryAction::Vanished);
}
OwnerEvidence::Unattributed => {
debug(
"recoverInspectedEntry",
format!(
"staging candidate without a complete owner record left in place: {}",
path.display()
)
.as_str(),
);
return Ok(RecoveryAction::StagingUnattributed);
}
OwnerEvidence::Owned(record, OwnerLiveness::Alive) => {
debug(
"recoverInspectedEntry",
format!(
"transaction owner {} is active; skipping {}",
record.owner_pid,
path.display()
)
.as_str(),
);
return Ok(RecoveryAction::OwnerActive);
}
OwnerEvidence::Owned(record, OwnerLiveness::Dead) => {
if inspected.entry.kind == EntryKind::Staging {
// An unpublished candidate never started capture, so it touched nothing outside
// itself and remains for diagnosis.
debug(
"recoverInspectedEntry",
format!(
"dead owner stopped before publishing; staging candidate kept: {}",
path.display()
)
.as_str(),
);
return Ok(RecoveryAction::StagingRetained);
}
return recover_dead_transaction(
place,
path,
inspected.entry.transaction_id.as_str(),
record.owner_pid,
);
}
}
}
/// What:
/// Whether an inspected entry is a dead published transaction holding a landing record.
/// Why:
/// `needsLandingLock`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function needsLandingLock(inspected: InspectedEntry): Promise<boolean>;
/// ```
fn needs_landing_lock(inspected: &InspectedEntry) -> Result<bool, RecoveryError> {
if inspected.entry.kind != EntryKind::Transaction || inspected.dead_owner().is_none() {
return Ok(false);
}
return has_landing_record(inspected.entry.path.as_path());
}
/// What:
/// Recover every dead published transaction that entered the landing critical section;
/// the
/// caller holds the landing lock.
/// Why:
/// `recoverDeadLandings`:
/// an owner killed while holding the landing lock and `index.lock`
/// has no landing record yet,
/// and its `index.lock` would block the next landing.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function recoverDeadLandings({ root, gitPath, effectiveCwd }): Promise<readonly CommitTransactionRecoveryOutcome[]>;
/// ```
pub fn recover_dead_landings(
place: &RecoveryPlace,
root: &Path,
) -> Result<Vec<RecoveryOutcome>, RecoveryError> {
let mut inspected: Vec<InspectedEntry> = Vec::new();
for entry in list_transaction_entries(root)? {
if entry.kind == EntryKind::Transaction {
inspected.push(inspect_registry_entry(&entry)?);
}
}
// `mut` allows collecting outcomes in recovery order.
let mut outcomes: Vec<RecoveryOutcome> = Vec::new();
for item in oldest_first(inspected) {
let Some(record) = item.dead_owner() else {
continue;
};
if !entered_landing(item.entry.path.as_path())? {
continue;
}
debug(
"recoverDeadLandings",
format!("recovering dead landing {}", item.entry.path.display()).as_str(),
);
let action: RecoveryAction = recover_dead_transaction(
place,
item.entry.path.as_path(),
item.entry.transaction_id.as_str(),
record.owner_pid,
)?;
outcomes.push(RecoveryOutcome {
directory: item.entry.path.clone(),
action,
});
}
return Ok(outcomes);
}
/// What:
/// Take the landing lock,
/// waiting while a live owner holds it.
/// Why:
/// Recovery of a landing must never race a live lander.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// await acquireOwnerLock({ lockDirectory: join(root, LANDING_LOCK_NAME) })
/// ```
pub fn acquire_registry_lock(root: &Path, name: &str) -> Result<OwnerLock, RecoveryError> {
let directory: PathBuf = root.join(name);
// `mut` is required by the notice interface; this wait is silent, as the incumbent's.
let mut silent: SilentWait = SilentWait;
match acquire_owner_lock(directory.as_path(), DEFAULT_POLL_DELAY, &mut silent) {
Ok(lock) => return Ok(lock),
Err(error) => return Err(RecoveryError(error.to_string())),
}
}
/// What:
/// Whether an outcome already names a directory.
/// Why:
/// The landing pass may have recovered an entry the main pass would visit again.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// outcomes.some((outcome) => outcome.directory === path)
/// ```
fn recovered_already(outcomes: &[RecoveryOutcome], path: &Path) -> bool {
for outcome in outcomes {
if outcome.directory == path {
return true;
}
}
return false;
}
/// What:
/// Recover every dead-owner transaction of one worktree registry and remove retired
/// leftovers;
/// a dead reservation holder's lock is retired too.
/// Why:
/// `recoverRegisteredTransactions`.
/// Unlike the incumbent,
/// an entry the landing pass already
/// recovered is not recovered a second time (the incumbent would fail reading its removed
/// directory;
/// recorded in `doc/handover/cli-git-native-transactions.md`).
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function recoverRegisteredTransactions({ root, gitPath, effectiveCwd }): Promise<readonly CommitTransactionRecoveryOutcome[]>;
/// ```
pub fn recover_registered_transactions(
place: &RecoveryPlace,
root: &Path,
) -> Result<Vec<RecoveryOutcome>, RecoveryError> {
let entries: Vec<RegistryEntry> = list_transaction_entries(root)?;
let mut inspected: Vec<InspectedEntry> = Vec::new();
let mut retired: Vec<PathBuf> = Vec::new();
for entry in &entries {
if entry.kind == EntryKind::Retired {
retired.push(entry.path.clone());
} else {
inspected.push(inspect_registry_entry(entry)?);
}
}
let ordered: Vec<InspectedEntry> = oldest_first(inspected);
let mut needs: Vec<bool> = Vec::with_capacity(ordered.len());
for item in &ordered {
needs.push(needs_landing_lock(item)?);
}
let mut outcomes: Vec<RecoveryOutcome> = Vec::new();
if needs.contains(&true) {
let lock: OwnerLock = acquire_registry_lock(root, LANDING_LOCK_NAME)?;
let recovered: Result<Vec<RecoveryOutcome>, RecoveryError> =
recover_dead_landings(place, root);
let released: Result<(), super::owner_lock::OwnerLockError> = lock.release();
outcomes.extend(recovered?);
if let Err(error) = released {
return Err(RecoveryError(error.to_string()));
}
}
for (index, item) in ordered.iter().enumerate() {
if needs[index] || recovered_already(outcomes.as_slice(), item.entry.path.as_path()) {
continue;
}
let action: RecoveryAction = recover_inspected_entry(place, item)?;
outcomes.push(RecoveryOutcome {
directory: item.entry.path.clone(),
action,
});
}
for path in &retired {
if let Err(error) = super::private_storage::remove_tree(path.as_path()) {
return Err(io_failure(
"removing the retired transaction",
path.as_path(),
&error,
));
}
}
// A crashed reservation holder's lock is retired here as well as by the next requester.
if let Err(error) = retire_lock_of_dead_owner(root.join(RESERVATION_LOCK_NAME).as_path()) {
return Err(RecoveryError(error.to_string()));
}
for path in retired {
outcomes.push(RecoveryOutcome {
directory: path,
action: RecoveryAction::RetiredRemoved,
});
}
return Ok(outcomes);
}
/// Registry recovery controls stay out of the release executable.
#[cfg(test)]
#[path = "recovery_scan_tests.rs"]
mod tests;