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
//! Exclusive durable attempt reservations and exact receipt retention; no transport.
use super::json::check_json_size;
use super::{
BackupLayoutGuard, ExecutionProgressPersistenceError, JournalLock, JournalLockError,
PersistenceError, create_json_durable, read_json, write_json_durable,
};
use crate::model::artifacts::ArtifactChecksumRecord;
use crate::model::attempt_journal::{
AttemptAuthorityRecord, AttemptJournalRecord, AttemptJournalRecordError,
MAX_ATTEMPT_JOURNAL_BYTES, MutationReceiptRequest, ObservationReceiptRequest,
};
use std::path::{Path, PathBuf};
use thiserror::Error;
/// Exclusive local accounting borrowing stable layout exclusion.
///
/// Successful reservation persists consumption before returning its number.
/// It grants no fresh IC authority, backend settlement or subprocess dispatch permission.
#[derive(Debug)]
pub struct AttemptJournalGuard<'a> {
layout: &'a BackupLayoutGuard,
_lock: JournalLock,
record: AttemptJournalRecord,
usable: bool,
}
impl<'a> AttemptJournalGuard<'a> {
/// Create original exact identity and limits without replacing retained evidence.
///
/// # Errors
/// Rejects unsafe/existing journals, lock contention, replaced layouts and failed persistence.
pub fn create(
layout: &'a BackupLayoutGuard,
authority: AttemptAuthorityRecord,
) -> Result<Self, AttemptJournalError> {
layout.check_root()?;
let path = journal_path(layout, &authority);
let lock = JournalLock::acquire(&path)?;
let record = AttemptJournalRecord::new(authority);
check_json_size(&record, MAX_ATTEMPT_JOURNAL_BYTES)?;
create_json_durable(&path, &record)?;
Ok(Self {
layout,
_lock: lock,
record,
usable: true,
})
}
/// Open exact retained identity and original budgets, replaying only local events.
///
/// # Errors
/// Rejects identity/budget changes, invalid chronology, missing/unsafe/oversized records and locks.
pub fn open(
layout: &'a BackupLayoutGuard,
expected: &AttemptAuthorityRecord,
) -> Result<Self, AttemptJournalError> {
layout.check_root()?;
let path = journal_path(layout, expected);
let lock = JournalLock::acquire(&path)?;
let record: AttemptJournalRecord = read_json(&path, MAX_ATTEMPT_JOURNAL_BYTES)?;
check_json_size(&record, MAX_ATTEMPT_JOURNAL_BYTES)?;
if record.authority() != expected {
return Err(AttemptJournalError::AuthorityMismatch);
}
Ok(Self {
layout,
_lock: lock,
record,
usable: true,
})
}
/// Read validated retained accounting without observing remote state.
///
/// # Errors
/// Rejects indeterminate writes or replaced layouts.
pub fn record(&self) -> Result<&AttemptJournalRecord, AttemptJournalError> {
self.check_usable()?;
Ok(&self.record)
}
/// Return the exact journal location for this operation sequence.
#[must_use]
pub fn path(&self) -> PathBuf {
journal_path(self.layout, self.record.authority())
}
/// Durably consume one mutation attempt before any admitted caller-owned call.
///
/// # Errors
/// Rejects unresolved attempts, exhaustion, applied operations and persistence failures.
pub fn reserve_mutation(&mut self) -> Result<u32, AttemptJournalError> {
self.reserve_with(AttemptJournalRecord::reserve_mutation, write_json_durable)
}
/// Reserve only after admitting the exact persisted plan and all original journals.
///
/// Every declared prerequisite must retain Applied evidence. Hold no other attempt
/// guard; original journals are admitted with sequential locks while this guard
/// retains its own lock. No missing journal is created or treated as unused.
/// Fresh permissions, authenticated prerequisites, never-dispatched custody and
/// backend/application safety remain caller-owned. Success is accounting only.
/// # Errors
/// Rejects wrong/missing originals, contention, unmet dependencies and ordinary
/// pending/exhausted/Applied or indeterminate-write conditions without refunds.
pub fn reserve_planned_mutation(
&mut self,
expected_plan: &ArtifactChecksumRecord,
) -> Result<u32, ExecutionProgressPersistenceError> {
let view = super::execution_progress::read_with_current(
self.layout,
expected_plan,
Some(self.record()?),
)?;
let sequence = self.record.authority().binding().operation_sequence();
if view.operations.iter().any(|operation| {
operation.operation_sequence == sequence
&& operation.state
== crate::policy::execution_progress::OperationProgressState::AwaitingDependencies
}) {
return Err(ExecutionProgressPersistenceError::DependenciesUnapplied(sequence));
}
Ok(self.reserve_mutation()?)
}
/// Durably consume one observation bound to an exact unresolved mutation and request.
///
/// Fresh authority, paid-effect settlement and ended command custody remain caller-owned.
/// # Errors
/// Rejects wrong attempts/requests, unresolved observations, exhaustion and failed writes.
pub fn reserve_observation(
&mut self,
mutation: u32,
request: &str,
) -> Result<u32, AttemptJournalError> {
self.reserve_with(
|record| record.reserve_observation(mutation, request),
write_json_durable,
)
}
/// Reserve one original reconciliation observation after complete retained-plan admission.
///
/// Reuses the same mutation/observation accounting owner; complete original evidence
/// is required even after exhaustion or reopening. Hold no other attempt guard.
/// Fresh read permission, observation dispatch custody and settled authenticated
/// outcome qualification remain integration-owned. Lost replies stay pending.
/// # Errors
/// Rejects missing/changed/held originals, invalid causality and the existing
/// reservation/persistence failures. No journal or allowance is recreated.
pub fn reserve_planned_observation(
&mut self,
expected_plan: &ArtifactChecksumRecord,
mutation: u32,
request: &str,
) -> Result<u32, ExecutionProgressPersistenceError> {
super::execution_progress::read_with_current(
self.layout,
expected_plan,
Some(self.record()?),
)?;
Ok(self.reserve_observation(mutation, request)?)
}
/// Retain an exact integration-qualified direct mutation reply.
///
/// # Errors
/// Rejects unmatched identity, absent/unsettled attempts, invalid evidence and failed persistence.
pub fn record_mutation(
&mut self,
receipt: MutationReceiptRequest,
) -> Result<(), AttemptJournalError> {
self.reserve_with(|record| record.record_mutation(receipt), write_json_durable)
}
/// Retain an exact observation; unresolved evidence never authorizes another mutation.
///
/// The integration qualifies completed observation and paid-effect settlement.
/// A lost observation response stays pending until qualified settlement.
///
/// # Errors
/// Rejects unmatched identity, absent/unsettled attempts, invalid evidence and failed persistence.
pub fn record_observation(
&mut self,
receipt: ObservationReceiptRequest,
) -> Result<(), AttemptJournalError> {
self.reserve_with(
|record| record.record_observation(receipt),
write_json_durable,
)
}
/// Record an independently qualified observation after complete original-plan admission.
///
/// Hold no other attempt guards. Original journals are read with sequential locks;
/// missing evidence never means unused allowance. This reuses the existing receipt
/// transition and durable writer, without another reservation or spending owner.
/// Authentication, settled outcome and retained evidence remain integration-owned.
/// # Errors
/// Rejects missing/changed/held originals, invalid causality or receipt, and failed IO.
pub fn record_planned_observation(
&mut self,
expected_plan: &ArtifactChecksumRecord,
receipt: ObservationReceiptRequest,
) -> Result<(), ExecutionProgressPersistenceError> {
self.admit_planned_progress(expected_plan)?;
Ok(self.record_observation(receipt)?)
}
pub(crate) fn admit_planned_progress(
&self,
expected_plan: &ArtifactChecksumRecord,
) -> Result<(), ExecutionProgressPersistenceError> {
super::execution_progress::read_with_current(
self.layout,
expected_plan,
Some(self.record()?),
)?;
Ok(())
}
fn reserve_with<T>(
&mut self,
transition: impl FnOnce(&mut AttemptJournalRecord) -> Result<T, AttemptJournalRecordError>,
write: impl FnOnce(&Path, &AttemptJournalRecord) -> Result<(), PersistenceError>,
) -> Result<T, AttemptJournalError> {
self.check_usable()?;
let mut next = self.record.clone();
let result = transition(&mut next)?;
check_json_size(&next, MAX_ATTEMPT_JOURNAL_BYTES)?;
self.usable = false;
write(&self.path(), &next)?;
self.record = next;
self.usable = true;
Ok(result)
}
fn check_usable(&self) -> Result<(), AttemptJournalError> {
if !self.usable {
return Err(AttemptJournalError::IndeterminateWrite);
}
self.layout.check_root()?;
Ok(())
}
}
pub(super) fn read_original_journals(
layout: &BackupLayoutGuard,
authorities: &[AttemptAuthorityRecord],
current: Option<&AttemptJournalRecord>,
) -> Result<Vec<AttemptJournalRecord>, AttemptJournalError> {
layout.check_root()?;
if let Some(current) = current
&& !authorities.contains(current.authority())
{
return Err(AttemptJournalError::AuthorityMismatch);
}
let mut journals = Vec::with_capacity(authorities.len());
for authority in authorities {
if let Some(current) = current
&& current.authority() == authority
{
journals.push(current.clone());
} else {
let guard = AttemptJournalGuard::open(layout, authority)?;
journals.push(guard.record()?.clone());
}
}
layout.check_root()?;
Ok(journals)
}
fn journal_path(layout: &BackupLayoutGuard, authority: &AttemptAuthorityRecord) -> PathBuf {
layout.root().join(format!(
"attempt-{}.json",
authority.binding().operation_sequence()
))
}
/// Typed exact admission, local accounting or durable publication failure.
#[derive(Debug, Error)]
pub enum AttemptJournalError {
/// Retained identity or original ceilings differ from current exact selection.
#[error("attempt journal authority mismatch")]
AuthorityMismatch,
/// A write may have completed; drop and reopen exact retained evidence.
#[error("attempt journal write outcome indeterminate; reopen retained evidence")]
IndeterminateWrite,
/// Model identity, chronology or allowance admission failed.
#[error(transparent)]
Record(#[from] AttemptJournalRecordError),
/// Journal/layout exclusion failed.
#[error(transparent)]
Lock(#[from] JournalLockError),
/// Bounded durable record access failed.
#[error(transparent)]
Persistence(#[from] PersistenceError),
}
#[cfg(all(test, unix))]
mod tests;