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
//! Workspace checkpoints of a session's turns, and rewinding to one.
//!
//! A turn's file writes are captured through the tool set's checkpoint
//! tracker between [`SessionRuntime::begin_workspace_checkpoint`] and
//! [`SessionRuntime::finalize_workspace_checkpoint`], for the sessions a
//! person prompts; a subagent's writes belong to its parent's turn. A
//! rewind restores the files a turn changed and moves the conversation to
//! the node before it (`tree.rs`).
use super::{build::SessionRole, SelectNodeError, SessionRuntime};
use crate::{
app::{
sdk_config::WorkspaceOptions,
workspace_rewind::{plans_full_restore, restored_fully, PlannedRewind},
},
config::Config,
permission::PermissionMode,
session::{
tree::NodeId,
workspace_checkpoint::{
CheckpointAppendError, CheckpointFileBudgetExceeded, CheckpointOutcome, RestoreAudit,
RestorePlan, WorkspaceCheckpointStore,
},
},
};
/// What [`SessionRuntime::rewind_workspace`] did.
#[derive(Debug)]
pub(crate) struct WorkspaceRewind {
/// The checkpoints it undid, oldest first.
pub(crate) turns: Vec<NodeId>,
/// What became of each path the checkpoints cover.
pub(crate) audit: RestoreAudit,
pub(crate) conversation: RewoundConversation,
}
/// Where the conversation stands after a rewind's files were restored.
#[derive(Debug)]
pub(crate) enum RewoundConversation {
/// It continues from before the rewound turn, in this row of the tree.
Moved { row: NodeId },
/// Some path was not restored, so it stays where it was.
Stayed,
/// Every path was restored, but the conversation could not be moved.
MoveFailed(SelectNodeError),
}
/// What [`SessionRuntime::rewind_workspace`] would do now, as
/// [`SessionRuntime::preview_rewind`] planned it.
#[derive(Debug)]
pub(crate) struct RewindPreview {
/// The conversation's current node the plan was made against, which
/// [`SessionRuntime::rewind_workspace`] may be held to.
pub(crate) tip: NodeId,
/// The checkpoints the rewind undoes, oldest first: the picked one, then
/// every later one on the conversation's current path.
pub(crate) turns: Vec<NodeId>,
pub(crate) plan: RestorePlan,
/// The row of the session's tree holding the node the conversation
/// would continue from, when every file would go back; `None` when it
/// would stay where it is.
pub(crate) returns_to: Option<NodeId>,
}
/// A rewind planned against the workspace as it is, which nothing refused.
struct PlannedWorkspaceRewind {
store: WorkspaceCheckpointStore,
workspace: rho_sdk::Workspace,
planned: PlannedRewind,
/// The node before the checkpoint's turn.
before: NodeId,
}
/// Why [`SessionRuntime::rewind_workspace`] changed nothing.
#[derive(Debug, thiserror::Error)]
pub(crate) enum RewindError {
/// The session cannot rewind, or not to this checkpoint; the requester
/// can tell why.
#[error("{0:#}")]
Refused(anyhow::Error),
/// The checkpoints or the workspace could not be read or written.
#[error("{0:#}")]
Failed(anyhow::Error),
/// The conversation moved on from the node the requester planned the
/// rewind at, so it would undo what the requester did not see.
#[error(
"the conversation moved on from '{expected}' to '{now}' since the rewind was previewed; \
preview it again"
)]
Moved { expected: NodeId, now: NodeId },
}
impl SessionRuntime {
/// Whether this session's turns take workspace checkpoints.
fn takes_checkpoints(&self) -> bool {
match self.build.run.role {
SessionRole::Interactive | SessionRole::Daemon | SessionRole::Run => {
!self.checkpoints_paused
}
// Their writes are their parent's turn's, or no session's.
SessionRole::Subagent { .. } | SessionRole::WorkflowNode => false,
}
}
/// Opens the coming turn's checkpoint at the conversation's leaf, which
/// the turn's checkpoint store has saved by now. Returns a notice when
/// checkpoint storage failed, which pauses capture for the session and
/// never the turn.
pub(super) fn begin_workspace_checkpoint(&mut self) -> anyhow::Result<Option<String>> {
if !self.takes_checkpoints() {
return Ok(None);
}
let Some(stored) = self.storage.file() else {
return Ok(None);
};
// One a turn that panicked left open would refuse this one.
self.built.tools.checkpoint_tracker().discard_turn();
match self
.built
.tools
.checkpoint_tracker()
.begin_turn(Some(stored))
{
Ok(()) => Ok(None),
Err(error)
if matches!(
error.downcast_ref::<CheckpointAppendError>(),
Some(CheckpointAppendError::Storage(_))
) =>
{
self.built.tools.checkpoint_tracker().discard_turn();
self.checkpoints_paused = true;
Ok(Some(format!(
"could not start workspace checkpoint: {error}; rewind paused for this session"
)))
}
Err(error) => Err(error),
}
}
/// Saves the ended turn's checkpoint against the conversation's leaf,
/// and returns what to tell the session's clients. A full checkpoint
/// budget pauses capture, not the conversation or earlier rewinds.
pub(super) fn finalize_workspace_checkpoint(
&mut self,
outcome: CheckpointOutcome,
) -> Vec<String> {
let tracker = self.built.tools.checkpoint_tracker().clone();
let Some(stored) = self.storage.file() else {
tracker.discard_turn();
return Vec::new();
};
let saved = stored
.active_checkpoint_target()
.and_then(|target| match target {
Some((node, revision)) => tracker.finalize_turn(node, revision, outcome),
None => {
tracker.discard_turn();
Ok(None)
}
});
match saved {
Ok(None) => Vec::new(),
Ok(Some(checkpoint)) => checkpoint
.files
.iter()
.filter_map(|file| {
let CheckpointFileBudgetExceeded { asked, limit } =
file.capture_budget_exceeded()?;
Some(format!(
"workspace checkpoint skipped '{}': per-file capture budget is {limit} bytes, asked {asked} bytes; this file cannot be rewound",
file.path.display()
))
})
.collect(),
Err(error) => {
tracing::warn!(%error, "failed to persist workspace checkpoint");
tracker.discard_turn();
match error.downcast::<CheckpointAppendError>() {
Ok(CheckpointAppendError::QuotaExceeded {
asked,
limit,
turn_bytes,
}) => {
self.checkpoints_paused = true;
vec![format!(
"workspace checkpoints paused: this session reached its {limit} bytes checkpoint budget (asked at least {asked} bytes; turn requested at least {turn_bytes} bytes); earlier turns stay rewindable"
)]
}
Ok(CheckpointAppendError::Storage(error)) | Err(error) => {
vec![format!("could not save workspace checkpoint: {error}")]
}
}
}
}
}
/// What rewinding checkpoint `target` would do to the files as they are
/// now, and so to the conversation, writing nothing. Refused as
/// [`Self::rewind_workspace`] would be.
pub(crate) fn preview_rewind(&self, target: &NodeId) -> Result<RewindPreview, RewindError> {
let PlannedWorkspaceRewind {
planned, before, ..
} = self.plan_rewind(target, /*tip*/ None)?;
let tip = planned.tip.clone();
let returns_to = plans_full_restore(&planned.plan)
.then(|| self.tree_row_of(&before))
.transpose()
.map_err(RewindError::Failed)?;
Ok(RewindPreview {
turns: planned.turns.turns().to_vec(),
tip,
plan: planned.plan,
returns_to,
})
}
/// Restores the files checkpoint `target`'s turn and every later turn
/// on the conversation's current path changed, as one plan, and, when
/// every one was restored, continues the conversation from before
/// `target`'s turn. A session or checkpoint that cannot rewind, one off
/// the current path included, is refused before a file is written;
/// moving the conversation can still fail after, which
/// [`RewoundConversation::MoveFailed`] says. With `tip`, the node a preview
/// was planned at, a conversation that moved on since is
/// [`RewindError::Moved`], before the checkpoint is looked at.
// NEXT_MAJOR(rho-protocol): make tip required once SessionChange::RewindWorkspace is removed.
pub(crate) async fn rewind_workspace(
&mut self,
target: &NodeId,
tip: Option<&NodeId>,
process_config: &Config,
) -> Result<WorkspaceRewind, RewindError> {
let PlannedWorkspaceRewind {
store,
workspace,
planned,
before,
} = self.plan_rewind(target, tip)?;
// The row the preview said it returns to, read as the preview reads
// it: before the conversation moves, and, failing, before a write.
// A plan that keeps a path cannot restore fully, so needs none.
let row = plans_full_restore(&planned.plan)
.then(|| self.tree_row_of(&before))
.transpose()
.map_err(RewindError::Failed)?;
let audit = planned
.restore(&store, &workspace)
.map_err(RewindError::Failed)?;
let conversation = match row.filter(|_| restored_fully(&audit)) {
Some(row) => match self.select_node(&before, process_config).await {
Ok(()) => RewoundConversation::Moved { row },
Err(error) => RewoundConversation::MoveFailed(error),
},
None => RewoundConversation::Stayed,
};
Ok(WorkspaceRewind {
turns: planned.turns.turns().to_vec(),
audit,
conversation,
})
}
/// Plans the rewind of checkpoint `target` against the workspace as it
/// is, refusing a session or checkpoint that cannot rewind, and, with
/// `tip`, a conversation whose current node is no longer `tip`.
fn plan_rewind(
&self,
target: &NodeId,
tip: Option<&NodeId>,
) -> Result<PlannedWorkspaceRewind, RewindError> {
use RewindError::{Failed, Moved, Refused};
if self.permission.mode == PermissionMode::Plan {
return Err(Refused(anyhow::anyhow!(
"workspace rewind is unavailable in plan permission mode"
)));
}
let stored = self
.storage
.file()
.ok_or_else(|| Refused(anyhow::anyhow!("the session has no saved conversation yet")))?;
let store = stored
.workspace_checkpoint_store()
.map_err(Failed)?
.ok_or_else(|| {
Refused(anyhow::anyhow!(
"workspace rewind is unavailable for this session"
))
})?;
let workspace = WorkspaceOptions {
root: self.permission.workspace_root.clone(),
}
.build_workspace(&self.added_dirs)
.map_err(|error| Failed(error.into()))?;
// A journal or tree that cannot be read is a failure, not a
// checkpoint the session does not have.
// The tip is compared in the same read as the plan, and before it: a
// checkpoint another rewind or a selected node left off the branch
// is the conversation having moved, not a bad checkpoint.
let planned = stored
.with_session_tree(|tree| {
let now = tree.active_leaf_id();
if let (Some(expected), Some(now)) = (tip, now) {
if expected != now {
return Ok(Err(Moved {
expected: expected.clone(),
now: now.clone(),
}));
}
}
Ok(
PlannedRewind::new(&store, &workspace, target, tree).map_err(|error| {
if error.refused() {
Refused(error.into())
} else {
Failed(error.into())
}
}),
)
})
.map_err(Failed)??;
let before = planned.turns.before().clone();
// The node must still be there to return to once files changed.
stored.history_for_node(&before).map_err(Refused)?;
Ok(PlannedWorkspaceRewind {
store,
workspace,
planned,
before,
})
}
}
#[cfg(test)]
#[path = "workspace_rewind_tests.rs"]
mod tests;