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
//! What:
//! Recovery of one dead-owner transaction from its schema-version-2 records.
//! Why:
//! Without a landing record the real index and refs were never touched:
//! recovery releases
//! the `index.lock` the transaction provably created and removes its `.keep` files,
//! shadow and
//! directory.
//! With a landing record (the caller holds the landing lock) it decides from
//! `ref-updated.json` or the reflog nonce whether the commit landed,
//! then discards the
//! attempt or completes it:
//! index,
//! conclusion cleanup,
//! added-path copies.
//! Missing evidence
//! fails closed and keeps the directory (`src/policy-engine/commit-transaction-recovery-landing.ts`).
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! await recoverDeadTransaction({ directory, transactionId, ownerPid, gitPath, effectiveCwd });
//! ```
/// Landed-capture recording.
use super::capture_records::record_landed_capture_or_warn;
/// Native conclusion cleanup.
use super::conclusion_cleanup::reproduce_conclusion_cleanup;
/// Debug diagnostics.
use super::diagnostic_log::debug;
/// Transaction keeps.
use super::pack_keep::remove_transaction_keeps;
/// The landed-or-not decision and index completion.
use super::recovery_completion::{IndexCompletion, commit_landed, complete_index};
/// The fail-closed recovery failure.
use super::recovery_error::RecoveryError;
/// Attempt evidence.
use super::recovery_evidence::{
LANDING_RECORD_PREFIX, RECORD_SUFFIX, attempt_numbers, directory_names, release_recorded_locks,
remove_dead_pid_file,
};
/// Exact reads and existence probes.
use super::recovery_files::{path_present, read_recovery_file, recovery_path_exists};
/// Shadow location and removal.
use super::shadow_git::{remove_shadow_repository, shadow_repository_path};
/// Running real Git.
use super::transaction_git::{GitContext, GitRequest, run_git};
/// Journal records.
use super::transaction_journal::{
Base, LandingOperation, LandingRecord, PREPARING_FILENAME, PreparingRecord,
};
/// Journal parsers.
use super::transaction_journal_parse::{parse_landing, parse_preparing};
/// Directory removal.
use super::transaction_registry::remove_transaction_directory;
/// Added-path worktree completion.
use super::worktree_completion::install_added_worktree_files;
/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
use std::path::{Path, PathBuf};
/// Prepared-journal filename written only by unreleased builds in registry directories.
pub const UNRELEASED_JOURNAL_FILENAME: &str = "journal.json";
/// What:
/// What recovery did for one transaction directory.
/// Why:
/// `CommitTransactionRecoveryAction`,
/// reported in debug output.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type CommitTransactionRecoveryAction = 'commit-not-created' | 'normalization-installed' | ...;
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecoveryAction {
/// The commit never landed;
/// the attempt was discarded.
CommitNotCreated,
/// An interrupted normalization's index was completed.
NormalizationInstalled,
/// A landed commit's post-index was installed now.
IndexInstalled,
/// A landed commit's post-index was already installed.
AlreadyInstalled,
/// The owner still runs;
/// nothing was touched.
OwnerActive,
/// The directory disappeared while recovery listed it.
Vanished,
/// A staging candidate without a complete owner record was left in place.
StagingUnattributed,
/// A dead owner's unpublished candidate was kept for diagnosis.
StagingRetained,
/// A retired directory whose removal was interrupted was removed.
RetiredRemoved,
}
/// What:
/// The incumbent's name of an action.
/// Why:
/// Debug output lists outcomes by these names.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// action // 'commit-not-created' | ...
/// ```
pub fn action_name(action: RecoveryAction) -> &'static str {
match action {
RecoveryAction::CommitNotCreated => return "commit-not-created",
RecoveryAction::NormalizationInstalled => return "normalization-installed",
RecoveryAction::IndexInstalled => return "index-installed",
RecoveryAction::AlreadyInstalled => return "already-installed",
RecoveryAction::OwnerActive => return "owner-active",
RecoveryAction::Vanished => return "vanished",
RecoveryAction::StagingUnattributed => return "staging-unattributed",
RecoveryAction::StagingRetained => return "staging-retained",
RecoveryAction::RetiredRemoved => return "retired-removed",
}
}
/// What:
/// Where recovery runs Git and finds the shared Git directory.
/// Why:
/// Every recovery step asks Git in the invocation's repository.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type RecoveryPlace = { gitPath: string; effectiveCwd: string; commonDir: string };
/// ```
#[derive(Clone, Debug)]
pub struct RecoveryPlace {
/// Real Git and its environment.
pub git: GitContext,
/// Working directory of every Git command.
pub cwd: PathBuf,
/// The repository's common Git directory.
pub common_dir: PathBuf,
}
/// What:
/// Remove everything a dead transaction left:
/// `.keep` files,
/// the shadow,
/// the directory.
/// Why:
/// `discardTransaction`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// await discardTransaction({ directory, transactionId, objectDirectory, shadowPath });
/// ```
fn discard_transaction(
directory: &Path,
transaction_id: &str,
preparing: &PreparingRecord,
) -> Result<(), RecoveryError> {
remove_transaction_keeps(
Path::new(preparing.object_directory.as_str()),
transaction_id,
)?;
remove_shadow_repository(Path::new(preparing.shadow_path.as_str()))?;
return remove_transaction_directory(directory);
}
/// What:
/// The invocation capture record,
/// or nothing when the owner died before writing it.
/// Why:
/// `readPreparing`.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function readPreparing(directory: string): Promise<PreparingRecord | typeof PREPARING_ABSENT>;
/// ```
fn read_preparing(directory: &Path) -> Result<Option<PreparingRecord>, RecoveryError> {
let path: PathBuf = directory.join(PREPARING_FILENAME);
if !recovery_path_exists(path.as_path())? {
return Ok(None);
}
return Ok(Some(parse_preparing(
read_recovery_file(path.as_path())?.as_slice(),
)?));
}
/// What:
/// Whether the target still resolves to the base an interrupted normalization recorded.
/// Why:
/// A normalization never moves the target;
/// one that moved belongs to someone else.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const current = await resolveRefCommit({ gitPath, cwd, ref: preparing.targetRef });
/// ```
fn target_unmoved(place: &RecoveryPlace, preparing: &PreparingRecord, expected: &Base) -> bool {
let revision: String = format!("{}^{{commit}}", preparing.target_ref);
let current: Base = match run_git(
&place.git,
&GitRequest::new(
place.cwd.as_path(),
&["rev-parse", "--verify", "--quiet", revision.as_str()],
),
) {
Ok(output) if output.succeeded() => Base::Commit(
String::from_utf8_lossy(output.stdout.as_slice())
.trim()
.to_string(),
),
_ => Base::Unborn,
};
return current == *expected;
}
/// What:
/// Recover one dead-owner transaction;
/// a caller recovering one with a landing record must
/// hold the landing lock.
/// Why:
/// `recoverDeadTransaction`,
/// step for step.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function recoverDeadTransaction({ directory, transactionId, ownerPid, gitPath, effectiveCwd }): Promise<CommitTransactionRecoveryAction>;
/// ```
pub fn recover_dead_transaction(
place: &RecoveryPlace,
directory: &Path,
transaction_id: &str,
owner_pid: i64,
) -> Result<RecoveryAction, RecoveryError> {
let names: Vec<String> = directory_names(directory)?;
if names.contains(&String::from(UNRELEASED_JOURNAL_FILENAME)) {
return Err(RecoveryError(format!(
"Transaction directory uses an unreleased journal format; inspect it before removing it: {}",
directory.display()
)));
}
let Some(preparing) = read_preparing(directory)? else {
debug(
"recoverDeadTransaction",
format!("dead owner stopped before capture: {}", directory.display()).as_str(),
);
remove_shadow_repository(
shadow_repository_path(place.common_dir.as_path(), transaction_id).as_path(),
)?;
remove_transaction_directory(directory)?;
return Ok(RecoveryAction::CommitNotCreated);
};
let real_index: &Path = Path::new(preparing.real_index_path.as_str());
let Some(latest) = attempt_numbers(names.as_slice(), LANDING_RECORD_PREFIX)
.last()
.copied()
else {
release_recorded_locks(directory, names.as_slice(), real_index, owner_pid)?;
discard_transaction(directory, transaction_id, &preparing)?;
return Ok(RecoveryAction::CommitNotCreated);
};
let landing: LandingRecord = parse_landing(
read_recovery_file(
directory
.join(format!("{LANDING_RECORD_PREFIX}{latest}{RECORD_SUFFIX}"))
.as_path(),
)?
.as_slice(),
)?;
if landing.operation == LandingOperation::Commit
&& !commit_landed(
&place.git,
place.cwd.as_path(),
directory,
&preparing,
&landing,
)?
{
debug(
"recoverDeadTransaction",
format!(
"landing attempt {latest} never advanced {}: {}",
preparing.target_ref,
directory.display()
)
.as_str(),
);
release_recorded_locks(directory, names.as_slice(), real_index, owner_pid)?;
discard_transaction(directory, transaction_id, &preparing)?;
return Ok(RecoveryAction::CommitNotCreated);
}
if landing.operation == LandingOperation::NormalizeOnly
&& !target_unmoved(place, &preparing, &landing.expected_old)
{
return Err(RecoveryError(format!(
"{} moved after an interrupted normalization; recovery retained at {}",
preparing.target_ref,
directory.display()
)));
}
remove_transaction_keeps(
Path::new(preparing.object_directory.as_str()),
transaction_id,
)?;
if landing.operation == LandingOperation::Commit
&& let Some(landed) = &landing.new_oid
{
// Before any other landing takes the landing lock, so no replay moves over this commit
// without its record.
record_landed_capture_or_warn(
Path::new(preparing.git_dir.as_str()),
directory,
transaction_id,
landed.as_str(),
);
}
let completion: IndexCompletion = complete_index(directory, &preparing, &landing)?;
remove_dead_pid_file(real_index, owner_pid)?;
let shadow: &Path = Path::new(preparing.shadow_path.as_str());
if landing.operation == LandingOperation::Commit && path_present(shadow)? {
reproduce_conclusion_cleanup(
&place.git,
place.cwd.as_path(),
Path::new(preparing.git_dir.as_str()),
shadow,
directory,
preparing.ref_format,
)?;
}
// Completion precedes shadow removal, so a missing shadow means an earlier run already
// finished the copies; the shadow store still holds originals that never landed.
if path_present(shadow)? {
let mut records: Vec<super::transaction_journal::AddedPath> = landing.added_paths.clone();
records.extend(landing.selected_worktree_paths.iter().cloned());
install_added_worktree_files(
&place.git,
place.cwd.as_path(),
Path::new(preparing.repository_root.as_str()),
records.as_slice(),
Some(shadow.join("objects").as_path()),
)?;
}
remove_shadow_repository(shadow)?;
remove_transaction_directory(directory)?;
if landing.operation == LandingOperation::NormalizeOnly {
return Ok(RecoveryAction::NormalizationInstalled);
}
match completion {
IndexCompletion::Installed => return Ok(RecoveryAction::IndexInstalled),
IndexCompletion::AlreadyInstalled => return Ok(RecoveryAction::AlreadyInstalled),
}
}
/// Dead-transaction recovery controls stay out of the release executable.
#[cfg(test)]
#[path = "recovery_landing_tests.rs"]
pub(crate) mod tests;