Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 118 additions & 15 deletions crates/dim-agent-capabilities/src/timeline_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,80 @@ impl TimelineTree {
)
.map(|_| ())
}
/// The sequence of the newest `session/forked` on the root through `head`:
/// the fact that says every earlier event of the root was copied
/// ([S5c §6.5](../../../docs/design/appserver/session-deletion-and-fork.md#65-opening-the-fork)).
/// A fork of a fork copied the source's fact too, so the newest is its own.
async fn forked_at(&self, head: u64) -> Result<Option<u64>> {
let reply = self
.store
.query(
&self.stored_scope(ROOT_BRANCH_ID, 1, head),
&QuerySpec {
filter: Some(QueryFilter::In {
value: QueryOperand::Field {
path: "kind".into(),
},
values: vec!["session/forked".into()],
}),
select: QuerySelect::Fields {
fields: vec!["position.sequence".into()],
},
group_by: vec![],
pick: Some(QueryPick::Last),
order_by: vec![],
},
Some(&QueryPage {
limit: NonZeroU64::MIN,
after: None,
}),
)
.await?;
let QueryOutput::Rows { rows } = reply.result else {
unreachable!("fork fact positions")
};
Ok(rows.into_iter().next().map(|row| {
let [QueryValue::Value { value }] =
<[_; 1]>::try_from(row.values).expect("one fork fact position")
else {
unreachable!("fork fact position")
};
value.as_u64().expect("event sequence is unsigned")
}))
}
/// Ends a line the fork copied from a line still open at its cut: `branch/end`
/// on the line, then the result `complete_end` writes on `main`
/// ([S5c §6.3](../../../docs/design/appserver/session-deletion-and-fork.md#63-what-a-fork-copies)).
/// A half-written end is completed by its caller's stored-end path, so only
/// a line without one reaches here.
async fn end_copied(&self, info: &TimelineInfo, head: u64) -> Result<EndedLine> {
let head = self
.append_stored(
&info.id,
head,
EventKind::BranchEnd(BranchEndData {
source: BranchSource::Host {
operation_id: "session.fork".into(),
},
ancestor: None,
final_message: None,
}),
)
.await?;
self.step_finished().await;
let Some((end_event, data)) = self.own_end(&info.id, head).await? else {
return Err(AgentError::fault(
"TimelineTree",
"the fork's end was not stored",
));
};
self.complete_end(info, end_event, data)?;
Ok(EndedLine {
head,
info: info.clone(),
end_event: Some(end_event),
})
}
async fn child_terminal(
&self,
parent: &str,
Expand Down Expand Up @@ -998,15 +1072,15 @@ impl TimelineTree {
};
let parent_head = stored[&parent].sequence;
let head = self
.append_stored_result(
.append_stored(
&parent,
parent_head,
BranchEndedData {
EventKind::BranchEnded(BranchEndedData {
branch: id.clone(),
end_event,
source: data.source,
ancestor: data.ancestor,
},
}),
)
.await?;
self.step_finished().await;
Expand All @@ -1017,14 +1091,9 @@ impl TimelineTree {
}
Ok(())
}
/// Appends one result on a line that restore keeps closed, and returns
/// Appends one stored fact on a line that restore keeps closed, and returns
/// the line's new head.
async fn append_stored_result(
&self,
branch: &str,
head: u64,
data: BranchEndedData,
) -> Result<u64> {
async fn append_stored(&self, branch: &str, head: u64, kind: EventKind) -> Result<u64> {
let key = TimelineKey {
session_id: self.session_id.clone(),
branch_id: branch.into(),
Expand All @@ -1036,7 +1105,7 @@ impl TimelineTree {
create_at: dim_agent_runtime::core::unix_millis(),
tags: None,
parent_call_id: None,
kind: EventKind::BranchEnded(data),
kind,
});
let (published, wait) = oneshot::channel();
self.store.append(
Expand Down Expand Up @@ -3004,6 +3073,14 @@ impl TimelineTreeControl for TimelineTree {
.into_iter()
.map(|branch| (branch.info.id.clone(), branch))
.collect();
let root_head = remaining
.get(ROOT_BRANCH_ID)
.map_or(0, |root| root.sequence);
// The newest fork fact on the root, read only for a copied line the
// restore finds without events: such a line was open at the cut when
// its creation is older than the fact, and this fork ends it
// (S5c §6.3). A restore that meets no such line reads nothing extra.
let mut forked: Option<Option<u64>> = None;
let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut pending = VecDeque::new();
for branch in remaining.values() {
Expand Down Expand Up @@ -3128,10 +3205,36 @@ impl TimelineTreeControl for TimelineTree {
let created = self.created(&next.id, stored.sequence).await?;
self.step_finished().await;
if !created {
let error = AgentError::Build(
"branch creation interrupted by process restart".into(),
);
self.record_create_failed(&next, &error)?;
let forked = match forked {
Some(forked) => forked,
None => {
let read = self.forked_at(root_head).await?;
self.step_finished().await;
*forked.insert(read)
}
};
// A line the fork copied from one still open at its cut is
// over in the fork; anything else is a creation a restart
// interrupted (S5c §6.3).
let open_at_cut = next.parent.as_deref() == Some(ROOT_BRANCH_ID)
&& next
.create_anchor
.zip(forked)
.is_some_and(|(anchor, forked)| anchor < forked);
if open_at_cut {
let ended = self.end_copied(&next, stored.sequence).await?;
self.step_finished().await;
self.state
.lock()
.unwrap()
.ended
.insert(next.id.clone(), ended);
} else {
let error = AgentError::Build(
"branch creation interrupted by process restart".into(),
);
self.record_create_failed(&next, &error)?;
}
remaining.remove(&next.id);
inactive.insert(next.id);
continue;
Expand Down
29 changes: 25 additions & 4 deletions crates/dim-app-server/src/storage/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3792,10 +3792,11 @@ impl SqliteTimelineStore {
/// `main` through `at` with the content rows its events reference and the
/// snapshots anchored on them, a directory without events for every branch
/// `main` created by then, and an owner row for every Session file and
/// every output path the source owns (ADR 013 D4). Rows are copied as
/// stored, except grants: a fork is a new Session and does not inherit
/// them. A source whose delete committed first is `Closed`. The runtime
/// validates the copy when it builds the fork.
/// every output path the source owns (ADR 013 D4). Opening the fork ends the
/// copied lines that were still open at the cut. Rows are copied as stored,
/// except grants: a fork is a new Session and does not inherit them. A source
/// whose delete committed first is `Closed`. The runtime validates the copy
/// when it builds the fork.
///
/// The events at or before `at` never change, so their references and the
/// content closure are read in bounded holds on read connections first.
Expand Down Expand Up @@ -4076,6 +4077,26 @@ fn copy_fork_rows(
if reject_conflicting_id(tx, root, fork)? {
return Ok(((), true));
}
// A source that lost its root row has nothing to fork. Failing here,
// before this chunk commits, leaves no fork behind: a retained source is
// a storage error, and a deleted one is `Closed`.
let (stored, rooted): (bool, bool) = tx
.prepare(
"SELECT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id=?1), \
EXISTS(SELECT 1 FROM timeline_branches WHERE session_id=?1 AND branch_id=?2)",
)
.map_err(error)?
.query_row(params![source, ROOT_BRANCH_ID], |row| {
Ok((row.get(0)?, row.get(1)?))
})
.map_err(error)?;
if !rooted {
return Err(if stored {
error("fork source has no root branch")
} else {
AgentError::Closed(source.to_owned())
});
}
branches = tx
.prepare("SELECT branch_id, info FROM timeline_branches WHERE session_id=?1")
.map_err(error)?
Expand Down
3 changes: 2 additions & 1 deletion crates/dim-app-server/tests/storage_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7818,7 +7818,8 @@ async fn a_fork_copies_main_through_the_cut_with_its_content_and_snapshots() {
.iter()
.map(|branch| (branch.info.id.as_str(), branch.sequence))
.collect::<Vec<_>>(),
[("child", 0), ("main", 5)]
[("child", 0), ("main", 5)],
"every copied line keeps its directory"
);
assert_eq!(
store
Expand Down
67 changes: 67 additions & 0 deletions crates/dim-app-server/tests/storage_flow/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2423,3 +2423,70 @@ async fn root_resolution_happens_outside_the_write_lock() {
store.close().await.unwrap();
db.close().await.unwrap();
}

/// A retained source that lost its root row has nothing to fork: the refusal
/// happens in the first chunk, before anything commits, so no fork row is
/// left behind; a deleted source keeps its `Closed` answer (#1978 review).
#[tokio::test]
async fn a_source_without_its_root_refuses_the_fork_before_anything_commits() {
let database = Database::new();
let directory = database.0.parent().unwrap().canonicalize().unwrap();
let root = rutis::Ctx::root().unwrap();
(&root.plugin(FileStoragePlugin::new(vec![directory.clone()])))
.await
.unwrap();
let db = SqliteStorage::open(database.0.clone()).unwrap();
let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0);
let store = SqliteTimelineStore::new(db.clone());
store
.create_session("source", &SessionConfig::default())
.await
.unwrap();
append(&store, key("source", "main"), vec![text(1, "source")])
.await
.unwrap();
let config = sessions
.session_config_text("source")
.await
.unwrap()
.unwrap();
let connection = Connection::open(&database.0).unwrap();
// A damaged store, written around the rows that reference the directory.
connection.execute_batch("PRAGMA foreign_keys=OFF").unwrap();
connection
.execute(
"DELETE FROM timeline_branches WHERE session_id='source' AND branch_id='main'",
[],
)
.unwrap();

let refused = sessions.fork_session("source", "fork", 1, &config).await;
assert!(
matches!(refused, Err(AgentError::Storage(_))),
"a retained source without its root is a storage error, got {refused:?}"
);
assert_eq!(
stored_rows(&connection, "fork"),
0,
"the refusal commits no fork row and copies no event"
);

connection
.execute("DELETE FROM agent_sessions WHERE session_id='source'", [])
.unwrap();
let closed = sessions.fork_session("source", "orphan", 1, &config).await;
assert!(
matches!(closed, Err(AgentError::Closed(_))),
"a deleted source keeps its Closed answer, got {closed:?}"
);
assert_eq!(
stored_rows(&connection, "orphan"),
0,
"nothing of a deleted source is committed either"
);

drop(connection);
drop(sessions);
store.close().await.unwrap();
db.close().await.unwrap();
}
Loading
Loading