diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 862b1a9a77..6ddfc7f5fb 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -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> { + 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 { + 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, @@ -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; @@ -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 { + async fn append_stored(&self, branch: &str, head: u64, kind: EventKind) -> Result { let key = TimelineKey { session_id: self.session_id.clone(), branch_id: branch.into(), @@ -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( @@ -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> = None; let mut children: BTreeMap> = BTreeMap::new(); let mut pending = VecDeque::new(); for branch in remaining.values() { @@ -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; diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 244a5ff850..8b7baae20e 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -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. @@ -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)? diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 7340580e64..9f6ad0dc9a 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -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::>(), - [("child", 0), ("main", 5)] + [("child", 0), ("main", 5)], + "every copied line keeps its directory" ); assert_eq!( store diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs index 2ec3b8b505..d0d17de6a3 100644 --- a/crates/dim-app-server/tests/storage_flow/admission.rs +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -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(); +} diff --git a/crates/dim-app-server/tests/transport_flow/fork.rs b/crates/dim-app-server/tests/transport_flow/fork.rs index 94c82f9ff0..e470024638 100644 --- a/crates/dim-app-server/tests/transport_flow/fork.rs +++ b/crates/dim-app-server/tests/transport_flow/fork.rs @@ -48,6 +48,34 @@ fn forked(reply: &Value) -> String { async fn history(session: &Session, branch: &str) -> Vec> { chain_events(session, branch, ..).await.unwrap() } +/// A line's stored events as a client reads them: an ended line has no live +/// history, so the read goes through `session.history`. +async fn line_events(client: &mut Client, session: &str, branch: &str) -> Vec { + let page = client + .rpc( + "session.history", + json!({"sessionId":session,"branchId":branch,"after":0,"limit":256}), + ) + .await; + assert_ok(&page); + page["result"]["events"].as_array().unwrap().clone() +} +/// The end the stored `branch/end` records for a copied line. +fn line_end(events: &[Value]) -> dim_agent_types::BranchEndData { + let end = events + .iter() + .find(|event| event["type"] == "branch" && event["name"] == "end") + .unwrap_or_else(|| panic!("the line holds its end: {events:?}")); + serde_json::from_value(end["data"].clone()).expect("a stored end") +} +/// The sequence of the stored `branch/end`, as the directory names it. +fn end_sequence(events: &[Value]) -> Value { + events + .iter() + .find(|event| event["type"] == "branch" && event["name"] == "end") + .unwrap_or_else(|| panic!("the line holds its end: {events:?}"))["sequence"] + .clone() +} fn keys(events: &[Arc]) -> Vec<&str> { events.iter().map(|event| event.kind.key()).collect() } @@ -87,10 +115,10 @@ fn error(reply: &Value) -> (String, String) { } /// Acceptance 3, 4 and 5: a fork at a rest point copies `main` through the -/// cut byte for byte with the content rows its events reference, copies the -/// branches `main` created by then as directories without events, and runs -/// nothing until a client sends it input, while the source's children go -/// on unaffected. A restart reloads it without a second failed creation. +/// cut byte for byte with the content rows its events reference, copies no +/// line still open at the cut, and runs nothing until a client sends it +/// input, while the source's children go on unaffected. A restart reloads it +/// without a second failed creation. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { let store = Store::new(); @@ -142,24 +170,16 @@ async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { .unwrap(), "first" ); - let mut children = vec![done.clone(), running.clone(), steered.clone()]; - children.sort(); + let children = vec![done.clone(), running.clone(), steered.clone()]; let fork = agent.get_session(&fid).unwrap(); let reply_sequence = reply["result"]["sequence"].as_u64().unwrap(); - // The reply is read from the published fork after its build returns, so a copied child's - // branch/create-failed may already be published; branch/resume at at + 2 is the floor. + // The reply is read from the published fork after its build returns; branch/resume at at + 2 + // is the floor, and nothing else follows it. assert!( (at + 2..=fork.sequence("main").unwrap()).contains(&reply_sequence), "the reply names the fork's main head when it is read: {reply_sequence}" ); - let mut copied = vec![]; - for _ in 0..500 { - copied = history(&fork, "main").await; - if failed_creations(&copied) == children { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } + let copied = history(&fork, "main").await; let prefix = chain_events(&source, "main", ..=at).await.unwrap(); let encode = |events: &[Arc]| -> Vec { events @@ -168,31 +188,6 @@ async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { .collect() }; assert_eq!(encode(&copied[..at as usize]), encode(&prefix)); - let tail = &copied[at as usize..]; - assert_eq!(tail[0].kind.key(), "session/forked"); - assert_eq!( - tail.iter() - .filter(|event| matches!(event.kind, EventKind::BranchResume(_))) - .count(), - 1 - ); - assert_eq!(failed_creations(tail), children, "{:?}", keys(tail)); - assert_eq!( - tail.iter() - .filter(|event| { - !matches!(&event.kind, EventKind::InputMessage(data) if data.user.is_none()) - && !matches!(event.kind, EventKind::InputApplied(_)) - && !matches!( - event.kind.key(), - "input-queue/node" | "input-queue/recovered" | "prompt-state/recovered" - ) - }) - .count(), - 2 + children.len(), - "the fork only initializes state: {:?}", - keys(tail) - ); - assert_eq!(fork.branches().len(), 1, "only main is active in the fork"); let rows = |sql: &str| count(&store, sql, [&fid, &sid]); assert_eq!( @@ -208,24 +203,23 @@ async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { rusqlite::params![sid, at as i64], ) ); - let directories: Vec<(String, i64)> = store - .connection() - .prepare("SELECT branch_id, sequence FROM timeline_branches WHERE session_id=?1 ORDER BY branch_id") - .unwrap() - .query_map([&fid], |row| Ok((row.get(0)?, row.get(1)?))) - .unwrap() - .collect::>() - .unwrap(); - let mut expected: Vec<(String, i64)> = children.iter().map(|id| (id.clone(), 0)).collect(); - expected.push(("main".into(), fork.sequence("main").unwrap() as i64)); - expected.sort(); - assert_eq!(directories, expected); - assert!(!directories.iter().any(|(id, _)| *id == after)); assert_eq!( - rows( - "SELECT COUNT(*) FROM timeline_events WHERE session_id=?1 AND branch_id<>'main' AND ?2<>''" + count( + &store, + "SELECT COUNT(*) FROM timeline_events WHERE session_id=?1 AND branch_id<>'main'", + [&fid] ), - 0 + children.len() as i64, + "a copied line holds its end and nothing of its work" + ); + assert_eq!( + count( + &store, + "SELECT COUNT(*) FROM timeline_events WHERE session_id=?1 AND branch_id<>'main' \ + AND kind='branch/end'", + [&fid] + ), + children.len() as i64 ); assert_eq!( rows( @@ -286,16 +280,139 @@ async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { [dim_agent_types::ContentBlock::Text { text }] if text == "steer after the cut"))) })); assert!(source.state(&running).unwrap().running); - let tail = history(&fork, "main").await.split_off(at as usize); - assert!( - !keys(&tail).iter().any(|key| WORK.contains(key)), + // A turn the fork accepts is ordered after everything its opening wrote, so + // reading once the turn ends settles the opening. + turn(&mut client, &fid, "in the fork").await; + let settled = history(&fork, "main").await; + let tail = &settled[at as usize..]; + assert_eq!(tail[0].kind.key(), "session/forked"); + let own = tail + .iter() + .position( + |event| matches!(&event.kind, EventKind::InputMessage(data) if data.user.is_some()), + ) + .expect("the fork's own input"); + let opening = &tail[..own]; + assert_eq!( + opening + .iter() + .filter(|event| matches!(event.kind, EventKind::BranchResume(_))) + .count(), + 1 + ); + assert_eq!( + failed_creations(opening), + Vec::::new(), "{:?}", - keys(&tail) + keys(opening) ); + // Every copied child was open at the cut, so the fork ends it: `branch/ended` + // on main names the child and the source's own end fact, with no final message. + let mut ends: Vec<&str> = opening + .iter() + .filter_map(|event| match &event.kind { + EventKind::BranchEnded(data) => Some(data.branch.as_str()), + _ => None, + }) + .collect(); + ends.sort(); + let mut named: Vec<&str> = children.iter().map(String::as_str).collect(); + named.sort(); + assert_eq!(ends, named, "{:?}", keys(opening)); + for event in opening { + if let EventKind::BranchEnded(data) = &event.kind { + assert_eq!( + data.source, + dim_agent_types::BranchSource::Host { + operation_id: "session.fork".into() + }, + "the fork's own end names its operation" + ); + } + } + assert_eq!( + opening + .iter() + .filter(|event| { + !matches!(&event.kind, EventKind::InputMessage(data) if data.user.is_none()) + && !matches!(event.kind, EventKind::InputApplied(_)) + && !matches!( + event.kind.key(), + "input-queue/node" | "input-queue/recovered" | "prompt-state/recovered" + ) + }) + .count(), + 2 + children.len(), + "the fork only initializes state and ends the lines it copied: {:?}", + keys(opening) + ); + assert!( + !keys(opening).iter().any(|key| WORK.contains(key)), + "the fork starts nothing: {:?}", + keys(opening) + ); + assert_eq!(fork.branches().len(), 1, "only main is active in the fork"); + let directories: Vec<(String, i64)> = store + .connection() + .prepare("SELECT branch_id, sequence FROM timeline_branches WHERE session_id=?1 ORDER BY branch_id") + .unwrap() + .query_map([&fid], |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + let mut expected: Vec = children.clone(); + expected.push("main".into()); + expected.sort(); + assert_eq!( + directories + .iter() + .map(|(id, _)| id.clone()) + .collect::>(), + expected, + "a fork keeps every copied line's directory" + ); + assert_eq!( + directories + .iter() + .find(|(id, _)| id == "main") + .expect("main's directory row") + .1, + fork.sequence("main").unwrap() as i64 + ); + assert!( + directories + .iter() + .filter(|(id, _)| id != "main") + .all(|(_, head)| *head == 1), + "a copied line holds only its end: {directories:?}" + ); + assert!(!directories.iter().any(|(id, _)| *id == after)); + let listed = client + .rpc("session.branches", json!({"sessionId":fid})) + .await; + assert_ok(&listed); + let rows = listed["result"]["branches"].as_array().unwrap(); for child in &children { + let row = rows + .iter() + .find(|row| row["branchId"] == child.as_str()) + .unwrap_or_else(|| panic!("{child} is listed: {listed}")); + assert_eq!(row["state"], "ended", "the fork ends the copied line"); + let end = line_end(&line_events(&mut client, &fid, child).await); + assert_eq!( + end.source, + dim_agent_types::BranchSource::Host { + operation_id: "session.fork".into() + } + ); + assert_eq!(end.final_message, None); + assert_eq!( + row["endEvent"], + end_sequence(&line_events(&mut client, &fid, child).await) + ); assert!( fork.state(child).is_err(), - "{child} is not part of the fork" + "{child} is not an open line of the fork" ); } @@ -306,20 +423,305 @@ async fn a_fork_copies_main_through_a_rest_point_and_starts_nothing() { let mut client = Client::new_version(&server, false, 3).await; assert_ok(&client.rpc("session.attach", json!({"sessionId":fid})).await); let fork = agent.get_session(&fid).unwrap(); + // As above, a turn accepted after the reload is ordered after everything the + // reload wrote. + turn(&mut client, &fid, "after the reload").await; let reloaded = history(&fork, "main").await; - assert_eq!(failed_creations(&reloaded), children); + assert_eq!( + failed_creations(&reloaded), + Vec::::new(), + "a reload records no creation failure" + ); + for child in &children { + assert_eq!( + line_events(&mut client, &fid, child).await.len(), + 1, + "a reload writes no second end for {child}" + ); + } + assert_eq!( + reloaded + .iter() + .filter(|event| matches!(&event.kind, EventKind::BranchEnded(_))) + .count(), + children.len(), + "a reload repeats no end on main" + ); + let resumed = reloaded + .iter() + .rposition(|event| matches!(event.kind, EventKind::BranchResume(_))) + .expect("the reload resumes the fork's main"); + let input = reloaded + .iter() + .rposition( + |event| matches!(&event.kind, EventKind::InputMessage(data) if data.user.is_some()), + ) + .expect("the fork's own input"); assert!( - !keys(&reloaded[at as usize..]) + !keys(&reloaded[resumed..input]) .iter() - .any(|key| WORK.contains(key)) + .any(|key| WORK.contains(key)), + "the reload starts nothing: {:?}", + keys(&reloaded[resumed..input]) + ); + assert!( + keys(&reloaded).contains(&"turn/start"), + "the fork runs the turn a client sends it" ); - turn(&mut client, &fid, "in the fork").await; - assert!(keys(&history(&fork, "main").await).contains(&"turn/start")); drop((client, fork, agent)); server.shutdown(); server.join().await.unwrap(); } +/// A fork copies every child line `main` created by its cut and ends the ones +/// still open there, so nothing is reported as a failed creation and the source +/// keeps its work (S5c §6.3, #1978). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_fork_ends_the_child_branches_that_were_open_at_its_cut() { + let store = Store::new(); + let (server, agent) = launch_with_agent(Arc::new(MockTools), store.config()).await; + let mut client = Client::new_version(&server, false, 3).await; + let mut params = create(json!(["wait", "branch"])); + params["interactive"] = json!(false); + let sid = forked(&client.rpc("session.create", params).await); + turn(&mut client, &sid, "first").await; + let source = agent.get_session(&sid).unwrap(); + let head = source.sequence("main").unwrap(); + let open = branch(&mut client, &sid, head, "tool:wait {\"millis\":1}").await; + let ended = branch(&mut client, &sid, head, "tool:wait {\"millis\":1}").await; + for line in [&open, &ended] { + assert_ok( + &client + .rpc("session.idle", json!({"sessionId":sid,"branchId":line})) + .await, + ); + assert!(!history(&source, line).await.is_empty(), "{line} ran"); + } + assert_ok( + &client + .rpc( + "session.branch_end", + json!({"sessionId":sid,"branchId":ended}), + ) + .await, + ); + tokio::time::timeout(Duration::from_secs(10), async { + while !history(&source, "main").await.iter().any( + |event| matches!(&event.kind, EventKind::BranchEnded(data) if data.branch == ended), + ) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the tree records the ended line on main"); + let recorded = ended_source(&history(&source, "main").await, &ended); + let at = source.sequence("main").unwrap(); + + let fid = forked(&fork(&mut client, &sid, at).await); + let fork = agent.get_session(&fid).unwrap(); + // The fork's opening writes its facts before it accepts input, so a turn + // that ends here settles everything the opening wrote. + turn(&mut client, &fid, "in the fork").await; + let copied = history(&fork, "main").await; + assert_eq!( + failed_creations(&copied), + Vec::::new(), + "opening a fork records no creation failure: {:?}", + keys(&copied) + ); + let opening = &copied[at as usize..]; + assert_eq!(opening[0].kind.key(), "session/forked"); + // The line open at the cut is ended by the fork itself; the line already over + // keeps the end the source recorded. + assert_eq!( + ended_source(opening, &open), + dim_agent_types::BranchSource::Host { + operation_id: "session.fork".into() + } + ); + assert_eq!(ended_source(&copied, &ended), recorded); + let own = line_events(&mut client, &fid, &open).await; + assert_eq!(own.len(), 1, "the copied line holds its end: {own:?}"); + let data = line_end(&own); + assert_eq!( + data.source, + dim_agent_types::BranchSource::Host { + operation_id: "session.fork".into() + } + ); + assert_eq!(data.final_message, None, "a fork owes no final message"); + assert!( + line_events(&mut client, &fid, &ended).await.is_empty(), + "the line that was over has no events in the fork" + ); + let listed = client + .rpc("session.branches", json!({"sessionId":fid})) + .await; + assert_ok(&listed); + let row = |line: &str| -> Value { + listed["result"]["branches"] + .as_array() + .unwrap() + .iter() + .find(|row| row["branchId"] == line) + .cloned() + .unwrap_or_else(|| panic!("{line} is listed: {listed}")) + }; + assert_eq!(row(&open)["state"], "ended", "{listed}"); + assert_eq!(row(&ended)["state"], "ended", "{listed}"); + assert_eq!( + row(&open)["endEvent"], + end_sequence(&own), + "the directory names the fork's end: {listed}" + ); + assert_eq!( + listed["result"]["branches"].as_array().unwrap().len(), + 3, + "every copied line is listed: {listed}" + ); + + // The source keeps its work: its line is still open, has no end, and takes + // input after the fork. + assert!( + source.state(&open).is_ok_and(|state| !state.running), + "the source's line is still open" + ); + assert!(!keys(&history(&source, &open).await).contains(&"branch/end")); + let before = history(&source, &open).await.len(); + assert_ok( + &client + .rpc( + "session.submit", + json!({"sessionId":sid,"branchId":open,"text":"after the fork"}), + ) + .await, + ); + assert_ok( + &client + .rpc("session.idle", json!({"sessionId":sid,"branchId":open})) + .await, + ); + let grown = history(&source, &open).await; + assert!(grown.len() > before, "the source's line runs its input"); + assert!(!keys(&grown).contains(&"branch/end")); + + // A reload keeps the ends it wrote and writes no second one. + drop((client, fork, source, agent)); + server.shutdown(); + server.join().await.unwrap(); + let (server, agent) = launch_with_agent(Arc::new(MockTools), store.config()).await; + let mut client = Client::new_version(&server, false, 3).await; + assert_ok(&client.rpc("session.attach", json!({"sessionId":fid})).await); + let fork = agent.get_session(&fid).unwrap(); + turn(&mut client, &fid, "after the reload").await; + let reloaded = history(&fork, "main").await; + assert_eq!( + failed_creations(&reloaded), + Vec::::new(), + "a reload records no creation failure" + ); + assert_eq!( + line_events(&mut client, &fid, &open).await.len(), + 1, + "a reload writes no second end" + ); + assert_eq!( + reloaded + .iter() + .filter( + |event| matches!(&event.kind, EventKind::BranchEnded(data) if data.branch == open) + ) + .count(), + 1, + "a reload repeats no end on main" + ); + server.shutdown(); + server.join().await.unwrap(); +} + +/// The source `main` recorded for `line`'s end. +fn ended_source(events: &[Arc], line: &str) -> dim_agent_types::BranchSource { + events + .iter() + .find_map(|event| match &event.kind { + EventKind::BranchEnded(data) if data.branch == line => Some(data.source.clone()), + _ => None, + }) + .unwrap_or_else(|| panic!("{line} has an end on main")) +} + +/// A fork of a fork copies the ends the first fork wrote: the line stays over +/// with the same `endEvent` and neither fork writes a second one (S5c §6.3). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_fork_of_a_fork_keeps_the_ends_it_copied() { + let store = Store::new(); + let (server, agent) = launch_with_agent(Arc::new(MockTools), store.config()).await; + let mut client = Client::new_version(&server, false, 3).await; + let mut params = create(json!(["wait", "branch"])); + params["interactive"] = json!(false); + let sid = forked(&client.rpc("session.create", params).await); + turn(&mut client, &sid, "first").await; + let source = agent.get_session(&sid).unwrap(); + let head = source.sequence("main").unwrap(); + let child = branch(&mut client, &sid, head, "tool:wait {\"millis\":1}").await; + assert_ok( + &client + .rpc("session.idle", json!({"sessionId":sid,"branchId":child})) + .await, + ); + let at = source.sequence("main").unwrap(); + let fid = forked(&fork(&mut client, &sid, at).await); + let first = agent.get_session(&fid).unwrap(); + turn(&mut client, &fid, "in the fork").await; + let first_end = history(&first, "main") + .await + .iter() + .find_map(|event| match &event.kind { + EventKind::BranchEnded(data) if data.branch == child => Some(data.end_event), + _ => None, + }) + .expect("the fork ends the copied line"); + + let at = first.sequence("main").unwrap(); + let gid = forked(&fork(&mut client, &fid, at).await); + let second = agent.get_session(&gid).unwrap(); + turn(&mut client, &gid, "in the fork of the fork").await; + let copied = history(&second, "main").await; + assert_eq!( + failed_creations(&copied), + Vec::::new(), + "a fork of a fork records no creation failure: {:?}", + keys(&copied) + ); + let ends: Vec = copied + .iter() + .filter_map(|event| match &event.kind { + EventKind::BranchEnded(data) if data.branch == child => Some(data.end_event), + _ => None, + }) + .collect(); + assert_eq!(ends, [first_end], "the copies agree on the end"); + assert!( + line_events(&mut client, &gid, &child).await.is_empty(), + "the ended line keeps no events in either fork" + ); + let listed = client + .rpc("session.branches", json!({"sessionId":gid})) + .await; + assert_ok(&listed); + let row = listed["result"]["branches"] + .as_array() + .unwrap() + .iter() + .find(|row| row["branchId"] == child.as_str()) + .cloned() + .unwrap_or_else(|| panic!("the line is listed: {listed}")); + assert_eq!(row["state"], "ended", "{listed}"); + assert_eq!(row["endEvent"], first_end, "{listed}"); + server.shutdown(); + server.join().await.unwrap(); +} + /// A branch's cut is at most its parent's published head: `session.branch_create` /// checks it before any read and creates nothing when the cut is a future one. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -1211,36 +1613,43 @@ async fn a_fork_waits_for_background_work_and_keeps_preset_and_model() { .await["result"], policy["result"] ); - tokio::time::timeout(Duration::from_secs(10), async { - while failed_creations(&history(&fork, "main").await[at as usize..]).is_empty() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("the fork records the child's creation as failed"); - tokio::time::sleep(Duration::from_millis(300)).await; + // A turn the fork accepts is ordered after everything its opening wrote, so + // the tail read once the turn ends settles the opening. + turn(&mut client, &fid, "in the fork").await; let tail = history(&fork, "main").await.split_off(at as usize); - assert!( - !keys(&tail).iter().any(|key| WORK.contains(key)), - "{:?}", + assert!(!store.output(&fid).exists(), "the fork ran no command"); + assert_eq!( + failed_creations(&tail), + Vec::::new(), + "the fork records no creation failure: {:?}", keys(&tail) ); - assert!(!store.output(&fid).exists(), "the fork ran no command"); - assert_eq!(failed_creations(&tail), std::slice::from_ref(&child)); - assert!(fork.state(&child).is_err()); + let opening = tail + .iter() + .position( + |event| matches!(&event.kind, EventKind::InputMessage(data) if data.user.is_some()), + ) + .map_or(&tail[..], |own| &tail[..own]); + assert!( + !keys(opening).iter().any(|key| WORK.contains(key)), + "the fork starts nothing: {:?}", + keys(opening) + ); + assert!( + fork.state(&child).is_err(), + "the child is not an open line of the fork" + ); assert_eq!( - count( - &store, - "SELECT COUNT(*) FROM timeline_events WHERE session_id=?1 AND branch_id=?2", - [&fid, &child] - ), - 0 + line_end(&line_events(&mut client, &fid, &child).await).source, + dim_agent_types::BranchSource::Host { + operation_id: "session.fork".into() + }, + "the fork ends the copied line and copies none of its work" ); assert!( !keys(&branch_events(&source, &child, ..).await.unwrap()).contains(&"exec/ended"), "the source's task still runs" ); - turn(&mut client, &fid, "in the fork").await; let calls: Vec = history(&fork, "main") .await .iter() diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index afd41c973e..8ffa115e1d 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -2330,4 +2330,97 @@ mod tests { "a repeated failure schedules no second snapshot" ); } + + /// The end `main` records for `branch`, as a fork writes it. + fn line_ended(sequence: u64, branch: &str, end_event: u64) -> serde_json::Value { + json!({ + "id": format!("ended-{branch}"), + "sequence": sequence, + "create_at": 2000, + "type": "branch", + "name": "ended", + "data": { + "branch": branch, + "endEvent": end_event, + "source": {"kind": "host", "operation_id": "session.fork"} + } + }) + } + + /// A Session's attach read the directory, then replays `main`'s history. + /// A creation fact for a line the directory lists as ended stays ended and + /// starts no turn read; one the directory lists as open keeps its waiting + /// row and its read; a `branch/create-failed` still shows its terminal row + /// (S5c §6.3, #1978). + #[tokio::test] + async fn a_replayed_creation_follows_the_directory_the_attach_read() { + let (mut fork, _receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + fork.session_id = "f1".into(); + fork.discover_branch("main"); + { + let history = fork.task_history.get_mut("main").unwrap(); + history.done = true; + history.window.through = Some(6); + } + let mut tombstone = listed_line("b-c1", "main", 2); + tombstone.state = "ended".into(); + fork.projection.directory(&tombstone); + { + let history = fork.task_history.entry("b-c1".to_owned()).or_default(); + history.ended = true; + history.done = true; + } + fork.task_history_queue.clear(); + fork.replay("main", tell(line_created(4, "b-c1", 2))); + assert_eq!( + listed(&fork, "b-c1").state, + LineState::Ended, + "the directory's ended row survives the copied creation" + ); + assert!( + !fork.task_history_queue.contains(&"b-c1".to_owned()), + "the fork lists the line as ended, so the replay reads no turn" + ); + fork.replay("main", tell(line_ended(5, "b-c1", 1))); + assert_eq!( + listed(&fork, "b-c1").state, + LineState::EndedByOperation, + "the fork's own end names its operation" + ); + assert!( + !fork.task_history_queue.contains(&"b-c1".to_owned()), + "the end queues no read either" + ); + fork.replay("main", create_failed(6, "b-cf")); + fork.replay("main", tell(line_created(7, "b-cf", 2))); + assert_eq!( + listed(&fork, "b-cf").state, + LineState::CreationFailed, + "a failed creation still shows its terminal row" + ); + + let (mut source, _receiver, _sent) = + crate::session_host::test_worker(&crate::session_host::TEST_FEATURES).await; + source.session_id = "s1".into(); + source.discover_branch("main"); + { + let history = source.task_history.get_mut("main").unwrap(); + history.done = true; + history.window.through = Some(6); + } + source.projection.directory(&listed_line("b-c1", "main", 2)); + source.discover_branch("b-c1"); + assert!( + source.task_history_queue.contains(&"b-c1".to_owned()), + "the source lists the line, so its read starts" + ); + source.task_history_queue.clear(); + source.replay("main", tell(line_created(4, "b-c1", 2))); + assert_eq!( + listed(&source, "b-c1").state, + LineState::Waiting, + "the source's line is still open" + ); + } } diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index 396cbd5eae..9ed99059ee 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -742,7 +742,7 @@ from **v42** to **v43** for InputQueue's [路线图](../roadmap.md) S5c([Session 删除、清理与分叉](session-deletion-and-fork.md#8-storage-format),已实现)的格式决定:**S5c 本身不改格式**。#222 在 v16 下让分叉在复制的行之后再写一行 `session/forked`(数据为空),没有升版本号;[v17](#193-v17-格式决定) 原样保留这一行。 - **删除**:在一个事务内按 `session_id` 删除该 Session 在各表中的全部行(顺序为 `session_file_owners`、`timeline_snapshots`、`timeline_events`、`timeline_branches`、`timeline_content`、`session_owners`、`agent_sessions`),与创建回滚是同一操作。不写墓碑行:命令输出目录在提交之前移除,Session 文件由 S5a 的行和清扫处理。 -- **分叉**:在一个事务内为新 Session 插入现有表的行。`agent_sessions.config` 按存储的文本原样复制;`main` 截至分叉点的事件行、被复制事件引用的内容行、锚定在被复制事件上的快照,以及 S5a 的 `session_file_owners` 行,都按原字节复制。截至分叉点由 `main` 创建的分支只复制目录行(保留存储的 `info`,头部为 0,不含事件),其下属分支不复制;没有事件的子分支目录是存储已经接受的状态,即子分支尚未开始的创建。持久化 JSON 类型不变;随后在 `at + 1` 写入一行 `session/forked`,`main` 的头部为 `at + 1`(在 `0` 处分叉不写,头部为 `0`)。 +- **分叉**:在一个事务内为新 Session 插入现有表的行。`agent_sessions.config` 按存储的文本原样复制;`main` 截至分叉点的事件行、被复制事件引用的内容行、锚定在被复制事件上的快照,以及 S5a 的 `session_file_owners` 行,都按原字节复制。分支目录是 `main` 那一行,加上分叉点前 `main` 创建的每个子分支(保留存储的 `info`,头部为 0,不含事件),其下属分支不复制。持久化 JSON 类型不变;随后在 `at + 1` 写入一行 `session/forked`,`main` 的头部为 `at + 1`(在 `0` 处分叉不写,头部为 `0`)。打开分叉时,切点处仍打开的子分支由 TimelineTree 在 F 内各写一条 `branch/end`(`Host`,操作 id 为 `session.fork`),随后在 F 的 `main` 上写对应的 `branch/ended`;不新增事件种类、字段或枚举值([删除与分叉 §6.3](session-deletion-and-fork.md#63-what-a-fork-copies))。 - **事件 ID**:事件 ID 在所属 Session 内唯一;分叉在另一个 Session 中重复源 Session 的 ID。现有校验和 `timeline_events_by_id` 索引本就按 Session 划分,这是对不变量的说明,不是格式变化。 - **不记来源**:不加记录分叉来源的列,`session/forked` 不带数据;目前没有任何决定使用它,[Session 访问 A.3](../contracts/session-access.md#a3-sessionconfig-fields) 规定 Session 来源在有使用方时连同其格式决定一起加入。 - **旧版本(开发阶段兼容范围,随 #222 决定)**:`EventKind` 是封闭列表,在 `session/forked` 出现之前构建的守护进程无法解码这一行,因而无法恢复新版守护进程分叉出的 Session;首次发布前原生格式不承诺兼容,所以不升版本号、不加回退解码或迁移。没有这一行的 Session(从未分叉、或在 `0` 处分叉)照常读取;已删除的 Session 当作从未存在。v17 起,在这一行出现之前构建的守护进程都以现有错误拒绝 v17 库,能打开 v17 库的守护进程都能解码它,上述差异只留在 v16 库中。 diff --git a/docs/design/appserver/request-delta-storage.md b/docs/design/appserver/request-delta-storage.md index 8831f9dcdc..836be1d864 100644 --- a/docs/design/appserver/request-delta-storage.md +++ b/docs/design/appserver/request-delta-storage.md @@ -555,9 +555,10 @@ compaction: the requests that reference the same message in v16. byte for byte. The fork copies the content rows those rows reference, as today, and for each `list` every node on the way to the first one: one recursive query over `(session_id, hash)` in the fork transaction, whose `UNION` visits a prefix shared by many lists once. No node of a request after the cut is copied unless an earlier - request shares it. Copied child directories have head 0 and no events. The copy remains one transaction whose length - grows with `main`'s copied prefix, as S5c states. The `session/forked` row the fork then writes at `at + 1` carries - no request and references no content, so the closure copies nothing for it. + request shares it. The fork copies `main`'s directory row and every child line's, and opening the fork ends the + lines that were still open at the cut. The copy remains + one transaction whose length grows with `main`'s copied prefix, as S5c states. The `session/forked` row the fork then + writes at `at + 1` carries no request and references no content, so the closure copies nothing for it. - **Delete and creation rollback** remove the Session's rows from every table, as today; the writer drops the Session's memo entries. diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 87c4f73a13..5b28dcb217 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -27,8 +27,9 @@ file steps. bounded transactions. An interruption leaves the Session invisible and at most unreachable rows of the id, which a retry removes; the next sweep finishes the files (§4). - **Fork.** A fork copies the source's `main` through a cut into a new Session in bounded transactions, byte for - byte, and shares the source's Session files. The cut is a rest point of `main`, and branches `main` created by then are - copied without their events, so the fork starts no work until a client sends it input (§6.5). The fork's `main` + byte, and shares the source's Session files. The cut is a rest point of `main`, and every line `main` created by + then comes with its directory: a line still open at the cut is ended in the fork, so the fork starts no work until + a client sends it input (§6.3, §6.5). The fork's `main` opens with `branch/resume`: the fork is the source's conversation restored at the cut under a new id. Right after the copied facts the fork writes one fact of its own, `session/forked`, so an owner that folds a branch's own history knows where the copy ends (§6.5); v3 connections deliver it and v2 keeps its list. @@ -353,11 +354,11 @@ fork would then be a Session whose `main` is not its whole history, and every la numbering spaces. **A fork's default branch is its root.** Every `branch/default` the copy inherits was written on the source's `main` -before the cut, so it names a line that is either absent from F or present only as a directory row without events -(§6.3). F therefore records its default branch as `main`: its `session/forked` at `at + 1` is later than every -copied `branch/default`, and the one lookup that decides a Session's default branch (timeline branches §5) reads the -newest of the two kinds. A cut of `0` records no `session/forked`, and its default branch is `main` for the same -reason: no copied fact names another. +before the cut, so it names a line the fork does not continue: a direct child is copied and listed as an ended line +(§6.3), and a line below one is not copied at all. F therefore records its default branch as `main`: its +`session/forked` at `at + 1` is later than every copied `branch/default`, and the one lookup that decides a Session's +default branch (timeline branches §5) reads the newest of the two kinds. A cut of `0` records no `session/forked`, and +its default branch is `main` for the same reason: no copied fact names another. ### 6.3 What a fork copies @@ -365,9 +366,10 @@ reason: no copied fact names another. Source S Fork F (bounded transactions) main: 1 .. 7 8 branch/create(c1) 9 .. 12 | 13 .. main: 1 .. 12, same ids (at = 12, a rest point) | cut then 13 session/forked; F's first load - c1: 1 branch/start .. 30 (may still grow) writes 14 branch/resume, 15 branch/create-failed(c1) - c2: branch/create at main 15 c1: directory (stored info, head 0), no events - - c2 not copied (created after the cut) + c1: 1 branch/start .. 11 branch/end (ended) writes 14 branch/resume, 15 branch/ended(c2) + c2: 1 branch/start .. 30 (may still grow) c1: directory (stored info, head 0), no events + c3: branch/create at main 13 c2: directory, then 1 branch/end (host: session.fork) + - c3 created after the cut: not copied timeline_content: rows the events reference only the rows the copied events reference, with the list nodes they reach timeline_snapshots: main, c1 main's, anchored at or before 12 @@ -383,7 +385,7 @@ reason: no copied fact names another. | `agent_sessions` | A new id (UUID v4), `created_at_ms` at the fork, and the source's `config` text unchanged. That is the whole `SessionConfig`, including `interactive` ([session access A.3](../contracts/session-access.md#a3-sessionconfig-fields)), `permissionPolicy`, `collaborationRole`, `cwd`, `model`, `systemPrompt` and `tools`. Copying the text instead of re-serializing it keeps `interactive`'s omission rule as written | | `session_owners` | The source's Agent and protocol version | | `session_catalog` | One row for F, with the values a backfill over F's events writes: `updated_at_ms` the `create_at` of the newest activity event the fork transaction writes ([session catalog §3.2](session-catalog.md#32-order-cursor-and-paging)) — the `session/forked` row at `at + 1` for a nonzero cut, F's creation time at a cut of `0` — and `preview` the first user input among the copied events under the same batch-complete window, NULL at a cut of `0` ([#556's catalog projection](native-storage-format.md#556-v23-格式决定)) | -| `timeline_branches` | `main` with head `at + 1` (its `session/forked`; `0` for a fork at `0`), and every branch whose `branch/create` is on `main` at or before `at`, with its stored `info` and head 0. Branches below those are not copied: their creations are in events F does not get | +| `timeline_branches` | `main` with head `at + 1` (its `session/forked`; `0` for a fork at `0`) and its stored `info`, and every branch whose `branch/create` is on `main` at or before `at`, with its stored `info` and head 0 (see below) | | `timeline_events` | `main`'s rows through `at` (the cut rule means no row spans it), with kinds, bodies, sequences, batch ends, event ids and before traces as stored, then one new `session/forked` row at `at + 1` (none for a fork at `0`). No row of a child branch | | `timeline_content` | The rows the copied events reference, by the references the codec writes for requests and their before traces, and every list node those references reach (format v17). The `session/forked` row references no content | | `timeline_snapshots` | The rows anchored on copied `main` events. They are derived from the same facts, so F's first load uses them instead of replaying from the start | @@ -392,17 +394,40 @@ reason: no copied fact names another. | `session_grants` | None: a fork is a new Session and does not inherit grants ([ADR 012](../../adr/012-session-grants.md) D1) | | Title metadata (S5b) | None: a fork starts untitled ([SessionTitle](../plugins/SessionTitle.md) A7) | -**Why child branches come without their events.** A child's events are not ordered against `main`'s cut, so no prefix -of a child corresponds to `at`. Copied whole, a child holds what happened after the cut, and its pending work (an -unstarted first input, a Queue or Steer input, a background task's wake) would start turns in F for work the source -already ran or is running, in the same `cwd` (§6.5). Fork copies each child directory with head 0. -Directory restore does not scan creation events; see [restore read boundary](restore-validation.md). -TimelineTree treats a child without its `branch/start` and first -Queue input as a creation that never started ([timeline_tree.rs](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) -`restore`): at F's first load it writes `branch/create-failed` (`error: "branch creation failed"`) on F's `main` and -builds nothing, and later loads skip the child because of that fact. A crash between a creation's commit and the -child's start already takes this path. In F the fact means the branch is not part of F; the branch and its work stay -in S, where a client can continue them. The fact is not model context, so the prompt prefix at the cut is unchanged. +**Which child directories are copied, and how F opens them.** A child's events are not ordered against `main`'s cut, +so no prefix of a child corresponds to `at`. Copied whole, a child holds what happened after the cut, and its pending +work (an unstarted first input, a Queue or Steer input, a background task's wake) would start turns in F for work the +source already ran or is running, in the same `cwd` (§6.5). F therefore copies **every** child directory `main` +created by the cut and none of its events, and the branch restore ends the ones still open there: + +- A child whose conclusion (`branch/ended` or `branch/create-failed`) is in the copied prefix was already over; F + lists it as ended or as a failed creation, with the end S recorded ([timeline branches + §10](../timeline-branches.md#10-ending-a-line)). +- A child with no conclusion and a creation older than F's `session/forked` was still open at the cut. The restore + writes one `branch/end` on that line with `source: Host { operation_id: "session.fork" }` and no final message, and + the existing end path writes `branch/ended` on F's `main` with that sequence as the `endEvent`. So the line is over + in F and appears as ended by an operation: a fait accompli the fork records itself, not a creation failure and not a + change to S. +- A child with no conclusion and a creation after the fork fact is a line a *this* fork's crash interrupted; it keeps + the `branch/create-failed` conclusion. + +A line's directory without events cannot be read any other way: the store writes a child's `timeline_branches` row in +the same transaction as the parent's `branch/create`, so a directory with no events means a creation still in flight. +Directory restore does not scan creation events ([restore read +boundary](restore-validation.md)); TimelineTree treats such a child as a creation that never started +([timeline_tree.rs](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) `restore`) and writes +`branch/create-failed` on its parent, which is the right conclusion for a crash between a creation's commit and the +child's start and a false one for a copy no creation touched. + +Facts, not deletions: the end is one `branch/end` and one `branch/ended` written in F's own store. No event kind, +field or enum value is added, the copies agree on the end (`branch/ended` copied into a fork of a fork keeps its +`endEvent`), and the source keeps every line, its head and its work. A reload sees `branch/ended` on `main` and marks +the line ended without writing a second end; a crash between the two appends is completed by the existing stored-end +path. + +The copied `main` keeps the `branch/create` facts of every branch S created by the cut, as stored: they are S's +conversation, and F does not rewrite `main`. Nothing F opens starts work, and the copied facts are not model context, +so the prompt prefix at the cut is unchanged. **Why only referenced content.** Content rows are per Session. Copying all of them would copy, for a fork from an early point of a long Session, the requests of everything after the cut, while the copy holds the store's write lock. @@ -414,6 +439,10 @@ Rejected alternatives: | Copy each child whole, as committed when the fork transaction runs (this page's first draft) | It carries the child's work after the cut into F, and the reload rules run its pending inputs and wakes again in the shared `cwd` (§6.5) | | Copy a child only up to its creation | Its first Queue input becomes pending again, and F runs the delegated task a second time | | Copy a child through its last rest point | It still carries work after the cut. A child on its first task has no rest point after its creation, and the check would read every copied child's facts while the fork transaction holds the write lock | +| Leave a copied line still open at the cut without an end (this page's earlier draft) | A directory without events is what a creation in flight looks like, so the fork's own restore records it as `branch/create-failed` and clients report lines that did not fail (#1978). Read as open, it would also say the line's work is going on in F while the work stays in S | +| Copy only the directories of lines that ended by the cut (this page's next draft) | The fork would silently drop every line the source still had open, so the tree a client sees in F would not be the tree at the cut, and a fork of a fork would lose lines for no reason | +| Teach restore to skip a directory with no events | It cannot tell that copy from a creation a crash interrupted, and that creation must keep its conclusion; the fork instead writes the end it means | +| Delete the copied line's directory instead of ending it | A row the source's tree showed would vanish from the copy while `main` still holds its `branch/create`, so the fact and the directory would disagree | | Copy every content row of the source | Disk and lock time for requests after the cut, which no copied event references | The copy runs in bounded transactions on its own connection: the session row is inserted only by the last one, so no @@ -426,7 +455,7 @@ grows with `main`'s copied prefix, but no single transaction holds the writer fo | Not copied | Why | | --- | --- | | `main` events after `at`, branches created after `at` | After the cut | -| Events of child branches, and the branches below them | Not ordered against the cut, and a reload would run their pending work again (§6.3). Their work stays in S | +| Events of child branches, the branches below them, and the creation's own work of a line open at the cut | Not ordered against the cut, and a reload would run their pending work again (§6.3). The line's directory stays and F ends it. Their work stays in S | | The loaded instance, leases, subscriptions, attached clients, in-flight requests | Runtime state, not stored; F builds its own | | An input still being submitted | Not committed, so not a fact | | The command output directory | The bytes are not copied; F's `session_output_owners` rows name the same files under `command-output//` or `.dim/exec///` and keep them readable after S is deleted (ADR 013 D4, §6.6) | @@ -455,9 +484,9 @@ every earlier event of F's `main` was copied. Owners that fold a branch's own hi after it, and v3 clients read it the same way; every other owner keeps treating the copied facts as F's history under its reload rule, and a v2 connection keeps its list and drops this fact. A fork at `0` copies nothing, writes no `session/forked` and opens with `branch/start` like a new Session. F is the source's conversation restored at the cut under a new -id, and every owner applies its existing reload rule. The cut is a rest point (§6.2) and child branches come without -events (§6.3), so no reload rule starts work: **F runs no turn, model call or tool until a client sends it input.** -F and S share `cwd`, so this keeps a fork from repeating the source's side effects. +id, and every owner applies its existing reload rule. The cut is a rest point (§6.2) and F ends the lines it copied +that were still open (§6.3), so no reload rule starts work: **F runs no turn, model call or tool until a client sends +it input.** F and S share `cwd`, so this keeps a fork from repeating the source's side effects. | At the cut | In F | | --- | --- | @@ -465,7 +494,7 @@ F and S share `cwd`, so this keeps a fork from repeating the source's side effec | Permission preset (`permission/changed`) | Kept. Permission folds the copied facts (#26); the policy in `SessionConfig` is copied too | | An open turn, a Queue or Steer input not consumed, a running background task | None: the cut is a rest point (§6.2) | | An Append input not consumed | Stays pending, and joins the next request a client's input starts in F | -| A branch `main` created | Its directory without events. TimelineTree writes `branch/create-failed` on F's `main` at the first load (§6.3) | +| A branch `main` created | Its directory. Ended by the cut: listed as ended with the end S recorded and no events. Still open at the cut: ended by F itself, `Host { operation_id: "session.fork" }`, with one `branch/end` and its result on F's `main` (§6.3). The copied `branch/create` facts stay as stored | | A Collaboration request delivered without a result | Collaboration writes its failed result (`capability reloading`). A result written by a reload posts no report input, so no turn starts. It does not stop the source's member: a reload stops only members whose relation names the reloading Session as their leader ([#127](https://github.com/arcships/dim/issues/127), §14) | | A Collaboration result whose report input comes after the cut | F keeps the result without its report: a reload posts no report, as for the source after a crash in that window. Nothing starts; the model can still read the result with the `agent` tool | | A live goal (Goal, P5) | Goal's A11 (§14) | @@ -478,27 +507,27 @@ events from after the cut. F holds none of them: S main: .. 8 branch/create(c1) .. 10 step/tool-result "Branch created: c1" .. 12 turn/end | 13 .. cut S c1: 1 branch/start 2 input/message (the task) 3 turn/start .. 25 turn/end (after the cut) - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: directory only + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end (host: session.fork) 2. The child is running when the fork commits S main: .. 8 branch/create(c1) .. 12 turn/end | .. S c1: 1 .. 5 turn/start 6 step/tool-call (exec) <- the fork transaction commits here - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: directory only: no turn to fail, no input to apply, no task to wake + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end: no turn to fail, no input to apply, no task to wake 3. The child gets input after the cut S main: .. 8 branch/create(c1) .. 12 turn/end | .. S c1: 1 .. 9 turn/end 10 input/message (steer, from a client) 11 turn/start .. - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: directory only + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end ``` | Case | In the source | In F | | --- | --- | --- | -| 1. The child finishes after the cut | Nothing reaches `main`. TimelineTree has no hand-back: the `branch` tool returns `Branch created: ` once the child has started, and a child's turns end in its own Timeline. `wait` wakes on background-task notices and steers, not on a child | F's `main` holds the creation and, for a `branch` tool call, that result, both before the cut, then `branch/create-failed`. It is handed no result, waits for nothing and records no other failure. The child's result stays readable in S. The one hand-back Dim has is Collaboration's, from a member Session: the Collaboration row above | -| 2. The child is running when the fork commits | Its turn, model call or tool batch is open | No child event is copied, so nothing is failed, applied, woken or run again in the shared `cwd`. F's `main` gets `branch/create-failed`, not a "delegation failed" input: no such input exists | -| 3. The child gets input after the cut | `main` cannot send input to a child. A child gets input from clients (`session.submit {branchId}`), from its own capabilities (exec wakes, Collaboration reports) and from TimelineTree's first input | F has none of the child's inputs, so it holds no input F never received | +| 1. The child finishes after the cut | Nothing reaches `main`. TimelineTree has no hand-back: the `branch` tool returns `Branch created: ` once the child has started, and a child's turns end in its own Timeline. `wait` wakes on background-task notices and steers, not on a child | F's `main` holds the creation and, for a `branch` tool call, that result, both before the cut. The line was open at the cut, so F ends it: it holds `branch/end` and is handed no result, waits for nothing and records no failure. The child's result stays readable in S. The one hand-back Dim has is Collaboration's, from a member Session: the Collaboration row above | +| 2. The child is running when the fork commits | Its turn, model call or tool batch is open | No child event is copied, so nothing is failed, applied, woken or run again in the shared `cwd`. F ends the line and records no creation failure and no "delegation failed" input: neither happened | +| 3. The child gets input after the cut | `main` cannot send input to a child. A child gets input from clients (`session.submit {branchId}`), from its own capabilities (exec wakes, Collaboration reports) and from TimelineTree's first input | F has none of the child's inputs, so it holds no input F never received; its line is over and refuses input | Rejected: `branch/start` after the copied facts. Prompt reads a root `branch/start` as a new Session and adopts the model and system prompt in `SessionConfig`, which would undo model changes the copied facts carry and change the @@ -558,7 +587,7 @@ delete against loading. | Delete of a Session still building: a `session.create`, a member's creation or a fork whose rows are committed and listed | The creation holds the new id's gate from before its rows commit until the Session is published and its protocol version recorded (D6). The delete waits, then closes the published Session and removes its rows. A creation that fails rolls its rows back, and the delete finds nothing | | Delete against attach, submit or a Session method | They wait for the gate, then fail `session_closed`; requests that already hold a use end with the close | | Delete against the Session's own appends | The close settles them; the row transaction follows every queued append on the Timeline writer | -| Fork against appends to the source | Rows through `at` never change, and the fork copies no row after them: child directories come without events | +| Fork against appends to the source | Rows through `at` never change, and the fork copies no row after them: it copies every line's directory and ends, in F's own rows, the lines still open at the cut | | Delete of a Collaboration leader | Its close stops its member requests, and Agents then deletes the Team with it: the members it leads and the Agents it owns ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)) | | Delete of a member | The leader's requests to it settle as member closed, as today | | Two forks of one source | Independent Sessions, each owning the shared files | @@ -580,9 +609,9 @@ steps read and write those rows with the steps above. - A delete removes rows from existing tables and, since [#556's catalog projection](native-storage-format.md#556-v23-格式决定), the derived `session_catalog` row. - A fork inserts rows into existing tables and copies stored text byte for byte, then inserts one `session/forked` row - (empty data) at `at + 1`, and writes F's `session_catalog` row in the same transaction from the rows it writes. A - child directory with head 0 and no events is a state the store already accepts: a creation whose child never - started. + (empty data) at `at + 1`, and writes F's `session_catalog` row in the same transaction from the rows it writes. The + branch directory it writes is `main`'s row and every child line's; opening the fork ends the child lines still + open at the cut (§6.3). - An event id is unique within its Session, and a fork repeats the source's ids in another Session. The store already checks and indexes ids per Session; S5c states this as an invariant, not as a change. - No provenance column and no tombstone, for the reasons in §4 and §6.6. @@ -652,7 +681,7 @@ unlike in a shared database directory, can attribute its entries. | Rule | Answer | | --- | --- | -| Principles §4 rule 1 (commands for others' state) | Delete and fork change only Agents' and SessionStore's own state: Session records and rows. A fork copies stored bytes and writes one fact of its own, `session/forked`, and none for another owner; the facts F writes when it opens come from their owners (TimelineTree's `branch/resume` and `branch/create-failed`, Collaboration's failed results). Goal decides on `session/forked` itself (A11). The preset is copied, not reset (#26) | +| Principles §4 rule 1 (commands for others' state) | Delete and fork change only Agents' and SessionStore's own state: Session records and rows. A fork copies stored bytes and writes one fact of its own, `session/forked`, and none for another owner; the facts F writes when it opens come from their owners (TimelineTree's `branch/resume` and the `branch/end` it writes to end a copied line, Collaboration's failed results). Goal decides on `session/forked` itself (A11). The preset is copied, not reset (#26) | | Principles §4 rule 2 (handover) | Not applicable: nothing is handed over | | Principles §4 rule 3 (before callbacks only) | No before callback. Rpc checks shape and the Session's version; the cut check is `session.branch_create`'s existing one plus the rest point, both reads of the fixed prefix | | Principles §4 rule 4 (no business meaning in core) | Timeline, Dispatcher, before and batches are untouched. TimelineTree's existing rules, that a root with events resumes and a child without its start is a failed creation, apply unchanged | @@ -695,13 +724,15 @@ stop would deadlock that reload, and delaying release would let a later member i replies `{deleted: false}`. 2. Delete an unloaded Session, and one whose rows fail validation: both reply `{deleted: true}` and leave no row. 3. Fork at a rest point of `main`, with one child branch created before the cut and one after: F's `main` holds the - source's events through `at` with the same ids, then `session/forked`, `branch/resume` and one `branch/create-failed` for the first - child; F has the first child's directory without events and nothing of the second; F has only the content rows - and snapshots of its `main` events; after a restart it reloads without a second `session/forked` or `branch/create-failed`. A fork at `0` opens with `branch/start` and has no `session/forked`. + source's events through `at` with the same ids, then `session/forked` and `branch/resume`, and no + `branch/create-failed`; F has every child's directory, the child still open at the cut holds one `branch/end` from + the fork and its `branch/ended` on `main`, and the child created after the cut is absent; F has only the content + rows and snapshots of its `main` events; after a restart it reloads without a second `session/forked`, `branch/end` + or `branch/create-failed`. A fork at `0` opens with `branch/start` and has no `session/forked`. 4. The cases of §6.5: fork while a child finishes after the cut, while a child has an open turn with a tool batch and - a background task, and while a client steers a child after the cut. In each, F's child has no events, F records - no `turn/start`, model call, tool execution or `exec/started` until a client submits input to F, and the source's - child goes on unaffected. + a background task, and while a client steers a child after the cut. In each, F ends that child, records no + `turn/start`, model call, tool execution or `exec/started` until a client submits input to F, and the source's + child goes on unaffected and still takes input, with no end of its own. 5. A fork's `SessionConfig` text equals the source's, including `"interactive": false`. A permission preset and a model set on the source before the cut are F's preset and model. 6. A fork is refused for `at` beyond the head, inside a batch, outside a context boundary or not at a rest point diff --git a/docs/zh/design/appserver/request-delta-storage.md b/docs/zh/design/appserver/request-delta-storage.md index 1fabf439a0..5574cbd142 100644 --- a/docs/zh/design/appserver/request-delta-storage.md +++ b/docs/zh/design/appserver/request-delta-storage.md @@ -341,7 +341,7 @@ node body = { parent: string | null, message: Message } ## 9. 分支、分叉与删除 - **跨分支。** 子分支的第一个请求与最近一个有请求的祖先上截点及之前的最后一个请求共用节点;它只引用节点,从不引用祖先的事件行。父分支在截点之后继续写入时新增的节点不在子分支的任何列表中。 -- **分叉**([S5c §6.3](session-deletion-and-fork.md#63-分叉复制什么))。截点及之前的 `main` 行逐字节复制。分叉照旧复制这些行引用的内容行,另外对每个 `list` 复制一直到第一个节点为止经过的每个节点:在分叉事务中对 `(session_id, hash)` 做一次递归查询,其 `UNION` 对多个列表共享的前缀只访问一次。截点之后的请求的节点不会被复制,除非某个更早的请求也共用它。复制的子分支目录 head 为 0,没有事件。复制仍是一个事务,其长度随 `main` 被复制的前缀增长,与 S5c 所述一致。分叉随后在 `at + 1` 写下的 `session/forked` 行不带请求、不引用内容,闭包不因它复制任何行。 +- **分叉**([S5c §6.3](session-deletion-and-fork.md#63-分叉复制什么))。截点及之前的 `main` 行逐字节复制。分叉照旧复制这些行引用的内容行,另外对每个 `list` 复制一直到第一个节点为止经过的每个节点:在分叉事务中对 `(session_id, hash)` 做一次递归查询,其 `UNION` 对多个列表共享的前缀只访问一次。截点之后的请求的节点不会被复制,除非某个更早的请求也共用它。分叉复制 `main` 的目录行和每条子分支的目录行,打开分叉时结束那些在切点处仍打开的线。复制仍是一个事务,其长度随 `main` 被复制的前缀增长,与 S5c 所述一致。分叉随后在 `at + 1` 写下的 `session/forked` 行不带请求、不引用内容,闭包不因它复制任何行。 - **删除与创建回滚**照旧删除该 Session 在每张表中的行;写入方丢弃该 Session 的记忆条目。 ## 10. 压缩与检查点读取 diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index d6c657e7c3..8d8555566d 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -15,7 +15,7 @@ - **删除。** Agents 不再加载该 Session;若它已加载,就关闭它,让各能力结算在途工作并释放所持资源。随后 SessionStore 移除该 Session 的输出目录:它自己的 `command-output//`,以及它每一行路径所在的目录;另一个 Session 仍在该目录下有行时保留(ADR 013 D4)。然后在一个事务内删除使 Session 可见的行(Session 文件和输出所有权行、授权、标题、目录、owner、Session 与分支),再按有界事务删除它的 Timeline 行。失去最后一个所有者的文件由 S5a 的清扫移除。删除不存在的 Session 也成功。 - **清理。** 一次删除移除该 Session 拥有的一切(§3.3)。按时间或保留数量清理并预览,由 CLI 组合 `session.summaries` 与 `session.delete` 完成,没有对应的服务端方法。 - **崩溃安全。** 目录的移除在第一个行事务提交之前落盘,Session 文件按 S5a 的行处理。第一个事务移除使 Session 可见的行;其余 Timeline 行按有界事务删除。中断只会留下不可见的 Session 和至多该 id 的不可达行,重试会删除它们;下一次清扫完成文件(§4)。 -- **分叉。** 分叉按有界事务把源 Session 的 `main` 截至某个切点的部分按存储的字节复制到一个新 Session,并共享源的 Session 文件。切点必须是 `main` 的静止点,`main` 到那时创建的分支只复制目录、不带事件,因此客户端给分叉发送输入之前,分叉不会自己开始任何工作(§6.5)。分叉的 `main` 以 `branch/resume` 打开:分叉就是源的对话在切点处、以新 id 恢复。分叉紧接在复制的事实之后写下自己的一个事实 `session/forked`,让折叠分支自身历史的所有者知道复制到哪里为止(§6.5);v3 连接会投递它,v2 保持自己的事件列表。`SessionConfig` 整体复制,`interactive` 和权限预设随之带过去,不放宽任何权限。 +- **分叉。** 分叉按有界事务把源 Session 的 `main` 截至某个切点的部分按存储的字节复制到一个新 Session,并共享源的 Session 文件。切点必须是 `main` 的静止点,`main` 到那时创建的每条线都带目录一起过去:切点处仍打开的线由分叉自己结束,因此客户端给分叉发送输入之前,分叉不会自己开始任何工作(§6.3、§6.5)。分叉的 `main` 以 `branch/resume` 打开:分叉就是源的对话在切点处、以新 id 恢复。分叉紧接在复制的事实之后写下自己的一个事实 `session/forked`,让折叠分支自身历史的所有者知道复制到哪里为止(§6.5);v3 连接会投递它,v2 保持自己的事件列表。`SessionConfig` 整体复制,`interactive` 和权限预设随之带过去,不放宽任何权限。 - **格式。** S5c 不改格式。新事件行是在 v16 下加入的开发阶段扩展,在它之前构建的守护进程读不了;格式 v17 原样保留它(§8)。不加来源列,不写墓碑。 新增一种事件 `session/forked`(数据为空),不改 Timeline、Dispatcher、TimelineTree、Prompt、rutis 或 Session 门面。 @@ -212,7 +212,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 被否决:以相同的分支 id 复制子分支的祖先链,并在子分支的副本上继续。那样分叉会变成一个 `main` 不是它全部历史的 Session,此后对那条线的每次读取都会拼接两个编号空间。 -**分叉的主线是它的根。** 副本继承的每条 `branch/default` 都是切点之前在源的 `main` 上写下的,所以它指名的线要么不在 F 中,要么只作为没有事件的目录行存在(§6.3)。因此 F 把它的主线记为 `main`:它在 `at + 1` 处的 `session/forked` 晚于每条复制来的 `branch/default`,而决定一个 Session 主线的唯一一次查询(timeline branches §5)读取两者中较新的那条。切点为 `0` 时不写 `session/forked`,它同样因为没有任何复制来的事实指名别的线,主线是 `main`。 +**分叉的主线是它的根。** 副本继承的每条 `branch/default` 都是切点之前在源的 `main` 上写下的,所以它指名的线在分叉里不会继续:直接子分支被复制过来,在 F 的目录里是一条已结束的线(§6.3),而再往下的线完全不复制。因此 F 把它的主线记为 `main`:它在 `at + 1` 处的 `session/forked` 晚于每条复制来的 `branch/default`,而决定一个 Session 主线的唯一一次查询(timeline branches §5)读取两者中较新的那条。切点为 `0` 时不写 `session/forked`,它同样因为没有任何复制来的事实指名别的线,主线是 `main`。 ### 6.3 分叉复制什么 @@ -220,9 +220,10 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 源 S 分叉 F(有界事务) main: 1 .. 7 8 branch/create(c1) 9 .. 12 | 13 .. main: 1 .. 12,id 相同 (at = 12,静止点) | 切点 然后 13 session/forked;F 首次加载 - c1: 1 branch/start .. 30(可能仍在增长) 写 14 branch/resume、15 branch/create-failed(c1) - c2: 在 main 15 处 branch/create c1: 目录(存储的 info,头部 0),没有事件 - - c2 不复制(在切点之后创建) + c1: 1 branch/start .. 11 branch/end(已结束) 写 14 branch/resume、15 branch/ended(c2) + c2: 1 branch/start .. 30(可能仍在增长) c1: 目录(存储的 info,头部 0),没有事件 + c3: 在 main 13 处 branch/create c2: 目录,然后 1 branch/end(host: session.fork) + - c3 在切点之后创建:不复制 timeline_content: 事件引用的行 只复制被复制事件引用的行及其到达的列表节点 timeline_snapshots: main、c1 main 的,锚点在 12 及之前 session_file_owners: (S,f1) (S,f2) (F,f1) (F,f2),不复制字节 @@ -237,7 +238,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | `agent_sessions` | 新 id(UUID v4)、分叉时刻的 `created_at_ms`,以及原样的源 `config` 文本,也就是整个 `SessionConfig`,包括 `interactive`([Session 访问 A.3](../contracts/session-access.md#a3-sessionconfig-字段))、`permissionPolicy`、`collaborationRole`、`cwd`、`model`、`systemPrompt` 和 `tools`。复制文本而不重新序列化,`interactive` 的省略规则保持原样 | | `session_owners` | 源的 Agent 与协议版本 | | `session_catalog` | 给 F 一行,取值与按 F 的事件回填相同:`updated_at_ms` 是分叉事务写入的最新一条活动事件的 `create_at`([Session 目录 §3.2](session-catalog.md#32-顺序游标与分页))——非零处为 `at + 1` 的 `session/forked`,`0` 处为 F 的创建时间——`preview` 是被复制事件里按同一按批次完整的窗口的第一条用户输入,`0` 处为 NULL([#556 的目录投影](../../../design/appserver/native-storage-format.md#556-v23-格式决定)) | -| `timeline_branches` | 头部为 `at + 1` 的 `main`(即它的 `session/forked`;在 `0` 处分叉为 `0`),以及 `branch/create` 位于 `main` 上 `at` 及之前的每个分支,保留存储的 `info`,头部为 0。其下的分支不复制:它们的创建事件在 F 拿不到的事件里 | +| `timeline_branches` | 头部为 `at + 1` 的 `main`(即它的 `session/forked`;在 `0` 处分叉为 `0`)及其存储的 `info`,以及 `branch/create` 位于 `main` 上 `at` 及之前的每个分支,保留存储的 `info`,头部为 0(见下) | | `timeline_events` | `main` 截至 `at` 的行(切点规则保证没有行跨过它),种类、正文、序号、批次终点、事件 id 和 before 轨迹都按存储的样子;随后在 `at + 1` 新写一行 `session/forked`(在 `0` 处分叉不写)。不含任何子分支的行 | | `timeline_content` | 被复制事件按编解码器写入的引用(请求及其 before 轨迹)所引用的行,以及这些引用到达的每个列表节点(格式 v17)。`session/forked` 行不引用内容 | | `timeline_snapshots` | 锚定在被复制的 `main` 事件上的行。它们由相同的事实派生,F 首次加载时可以直接使用,不必从头重放 | @@ -245,7 +246,17 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | `session_output_owners` | S 拥有的每条输出路径给 F 一行,包括分叉时仍在运行的命令登记的行(ADR 013 D4)。不复制文件;F 读取当前内容,并在 S 删除后继续保留 | | 标题元数据(S5b) | 不复制:分叉没有标题([SessionTitle](../plugins/SessionTitle.md) A7) | -**为什么子分支不带事件。** 子分支的事件与 `main` 的切点之间没有先后顺序,子分支没有哪个前缀对应 `at`。整体复制的子分支带着切点之后发生的事,它待处理的工作(尚未开始的第一个输入、Queue 或 Steer 输入、后台任务的唤醒)会在 F 中启动轮次,在同一个 `cwd` 里重做源已经做过或正在做的工作(§6.5)。分叉复制每个子分支目录,头部为 0。恢复目录不扫描创建事件,见[恢复读取边界](../../../design/appserver/restore-validation.md)。TimelineTree 把缺少 `branch/start` 和第一个 Queue 输入的子分支当作从未开始的创建([timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 `restore`):F 首次加载时,它在 F 的 `main` 上写 `branch/create-failed`(`error: "branch creation failed"`),不构建这个分支;之后的加载看到这条事实就跳过它。创建已提交、子分支尚未开始时崩溃,走的就是这条路径。在 F 中,这条事实表示该分支不属于 F;分支和它的工作留在 S 中,客户端可以在那里继续。这条事实不进入模型上下文,切点处的提示词前缀不变。 +**复制哪些子分支目录,以及 F 如何打开它们。** 子分支的事件与 `main` 的切点之间没有先后顺序,子分支没有哪个前缀对应 `at`。整体复制的子分支带着切点之后发生的事,它待处理的工作(尚未开始的第一个输入、Queue 或 Steer 输入、后台任务的唤醒)会在 F 中启动轮次,在同一个 `cwd` 里重做源已经做过或正在做的工作(§6.5)。所以 F 复制 `main` 到切点为止创建的**每一条**子分支的目录、不带任何子分支事件,并由分支恢复结束其中仍打开的那些: + +- 结论(`branch/ended` 或 `branch/create-failed`)已在复制前缀里的子分支本来就已经结束;F 按已结束或创建失败列出它,并带上 S 记录的结束([Timeline 分支 §10](../../../design/timeline-branches.md#10-结束一条线))。 +- 没有结论、且创建早于 F 的 `session/forked` 的子分支在切点处仍打开。恢复在那条线上写一条 `branch/end`,`source` 为 `Host { operation_id: "session.fork" }`,没有最终消息;已有的结束路径随后以它的序号作为 `endEvent` 在 F 的 `main` 上写 `branch/ended`。于是这条线在 F 中已经结束,显示为由某个操作结束:这是分叉自己记下的既成事实,既不是创建失败,也不改动 S。 +- 没有结论、但创建晚于分叉事实的子分支,是**这个**分叉自己的崩溃打断的创建;它保留 `branch/create-failed` 结论。 + +没有事件的目录行无法用其他方式表示:存储把子分支的 `timeline_branches` 行与父分支的 `branch/create` 写在同一个事务里,所以没有事件的目录意味着一次仍在进行中的创建。恢复目录不扫描创建事件([恢复读取边界](../../../design/appserver/restore-validation.md));TimelineTree 把这样的子分支当作从未开始的创建([timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 `restore`),在它的父分支上写 `branch/create-failed`。对创建已提交、子分支尚未开始时崩溃来说这是正确的结论,对没有任何创建碰过的副本却是假的。 + +这里写的是事实,不是删除:结束就是 F 自己在自己的存储里写的一条 `branch/end` 和一条 `branch/ended`。不新增事件种类、字段或枚举值,分叉的副本对结束保持一致(分叉的分叉复制来的 `branch/ended` 保留其 `endEvent`),源保留每一条线、它的头部和它的工作。重载时 `main` 上的 `branch/ended` 让该线直接记为已结束,不再写第二条结束;两次追加之间崩溃时,由已有的“已存储结束”路径完成。 + +复制来的 `main` 保留源在切点及之前写下的全部 `branch/create` 事实,按存储的样子:那是源的对话,F 不改写 `main`。它们指名的线在 F 中都有目录,并在切点处仍打开时由 F 结束。F 打开时不开始任何工作,复制来的事实也不进入模型上下文,切点处的提示词前缀不变。 **为什么只复制被引用的内容。** 内容行按 Session 存放。全部复制的话,从长 Session 的早期分叉会把切点之后所有请求的内容也复制过去,而复制期间一直持有存储的写锁。 @@ -256,6 +267,10 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 按分叉事务执行时已提交的样子整体复制每个子分支(本页初稿) | 把子分支在切点之后的工作带进 F,重载规则还会在共用的 `cwd` 里重新执行它待处理的输入和唤醒(§6.5) | | 子分支只复制到创建为止 | 它的第一个 Queue 输入重新变成待处理,F 会把委托的任务再执行一遍 | | 子分支复制到它最后一个静止点 | 仍然带着切点之后的工作。还在做第一个任务的子分支在创建之后没有静止点,而且检查要在分叉事务持有写锁时读取每个被复制子分支的事实 | +| 把切点处仍打开的被复制子分支留着不写结束(本页早先的版本) | 没有事件的目录正是“创建进行中”的样子,分叉自己的恢复就把它记为 `branch/create-failed`,客户端会报出并没有失败的线(#1978)。把它当作打开的线来读,也会说它的工作还在 F 中进行,而工作留在 S | +| 只复制切点前已结束的线的目录(本页下一个版本) | 分叉会默默丢掉源里仍打开的每一条线,客户端在 F 中看到的树就不是切点处的树,分叉的分叉也会平白少线 | +| 让恢复跳过没有事件的目录 | 它无法区分这种副本与崩溃打断的创建,而后者必须保留自己的结论;分叉改成写下它要表达的结束 | +| 删除被复制线的目录而不是结束它 | 源树里出现过的行会从副本中消失,而 `main` 仍持有它的 `branch/create`,事实和目录就不一致了 | | 复制源的全部内容行 | 为切点之后、没有被复制事件引用的请求付出磁盘和锁的时间 | 复制在自己的连接上按有界事务进行:只有最后一个事务插入 Session 行,因此读者在 F 完整之前看不到它,所有 Session 的提交与发布都能在块之间进行(#599)。复制前先用只读连接分段读取引用及其内容闭包。工作量仍随被复制的 `main` 前缀增长,但没有任何一个事务为整个前缀占住 writer。 @@ -265,7 +280,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 不复制 | 原因 | | --- | --- | | `at` 之后的 `main` 事件,`at` 之后创建的分支 | 在切点之后 | -| 子分支的事件,以及其下的分支 | 与切点之间没有先后顺序,重载还会重新执行其中待处理的工作(§6.3)。它们的工作留在 S 中 | +| 子分支的事件、其下的分支,以及切点处仍打开的线的创建本身的工作 | 与切点之间没有先后顺序,重载还会重新执行其中待处理的工作(§6.3)。线保留目录,由 F 结束它。它们的工作留在 S 中 | | 已加载实例、租约、订阅、已附着的客户端、在途请求 | 运行时状态,不存储;F 自己建立 | | 正在提交中的输入 | 尚未提交,不是事实 | | 命令输出目录 | 不复制字节;F 的 `session_output_owners` 行命名 `command-output//` 或 `.dim/exec///` 下的同一批文件,S 删除后仍可读(ADR 013 D4,§6.6) | @@ -277,7 +292,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 Agents 用现有的预备创建来创建 F:预备步骤是 SessionStore 的分叉事务,而不是 `create_owned_session`。随后运行时校验 F 的行并构建 F。失败时回滚 F,包括它的所有者行([Session 文件 §5.3](session-files.md));源不受影响。 -TimelineTree 以 `branch/resume` 打开已有事件的根分支([timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 `restore`),因此 F 的 `main` 在复制来的事实之后接着写 `branch/resume`。在此之前,分叉事务自己在复制来的事实之后写一条自己的事实:位于 `at + 1` 的 `session/forked`(数据为空),因此 F 不会在没有它的情况下存在。它表示 F 的 `main` 中此前的每条事件都是复制来的。按分支自身历史折叠的所有者(Goal,A11)从它之后开始,v3 客户端也这样读;其他所有者仍按各自的重载规则把复制来的事实当作 F 的历史,v2 连接则保持自己的事件列表、丢弃这条事实。在 `0` 处分叉不复制任何东西,不写 `session/forked`,像新 Session 一样以 `branch/start` 打开。F 就是源的对话在切点处、以新 id 恢复,每个所有者按现有的重载规则处理。切点是静止点(§6.2),子分支不带事件(§6.3),所以没有哪条重载规则会开始工作:**客户端给 F 发送输入之前,F 不运行任何轮次、模型调用或工具。** F 与 S 共用 `cwd`,这一点保证分叉不会重复源的副作用。 +TimelineTree 以 `branch/resume` 打开已有事件的根分支([timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline_tree.rs) 的 `restore`),因此 F 的 `main` 在复制来的事实之后接着写 `branch/resume`。在此之前,分叉事务自己在复制来的事实之后写一条自己的事实:位于 `at + 1` 的 `session/forked`(数据为空),因此 F 不会在没有它的情况下存在。它表示 F 的 `main` 中此前的每条事件都是复制来的。按分支自身历史折叠的所有者(Goal,A11)从它之后开始,v3 客户端也这样读;其他所有者仍按各自的重载规则把复制来的事实当作 F 的历史,v2 连接则保持自己的事件列表、丢弃这条事实。在 `0` 处分叉不复制任何东西,不写 `session/forked`,像新 Session 一样以 `branch/start` 打开。F 就是源的对话在切点处、以新 id 恢复,每个所有者按现有的重载规则处理。切点是静止点(§6.2),F 会结束它复制来的仍打开的线(§6.3),所以没有哪条重载规则会开始工作:**客户端给 F 发送输入之前,F 不运行任何轮次、模型调用或工具。** F 与 S 共用 `cwd`,这一点保证分叉不会重复源的副作用。 | 切点处 | 在 F 中 | | --- | --- | @@ -285,7 +300,7 @@ TimelineTree 以 `branch/resume` 打开已有事件的根分支([timeline_tree | 权限预设(`permission/changed`) | 保留。Permission 折叠复制来的事实(#26);`SessionConfig` 中的策略也一并复制 | | 未结束的轮次、未消费的 Queue 或 Steer 输入、运行中的后台任务 | 不存在:切点是静止点(§6.2) | | 未消费的 Append 输入 | 保持待处理,并入 F 中由客户端输入启动的下一次请求 | -| `main` 创建的分支 | 只有目录,没有事件。F 首次加载时 TimelineTree 在 F 的 `main` 上写 `branch/create-failed`(§6.3) | +| `main` 创建的分支 | 带目录。切点前已结束的:按已结束列出并带上 S 记录的结束,没有事件。切点处仍打开的:由 F 自己结束(`Host { operation_id: "session.fork" }`),一条 `branch/end` 及其在 F 的 `main` 上的结果(§6.3)。复制来的 `branch/create` 事实按存储的样子保留 | | 已送达但没有结果的 Collaboration 请求 | Collaboration 写出失败结果(`capability reloading`)。重载写出的结果不投递报告输入,因此不启动轮次。它不停止源的成员:重载只停止成员关系以重载中的 Session 为 leader 的成员([#127](https://github.com/arcships/dim/issues/127),§14) | | 报告输入在切点之后的 Collaboration 结果 | F 保留结果但没有它的报告:重载不投递报告,与源在这段窗口内崩溃后相同。不会启动任何工作;模型仍可用 `agent` 工具读取结果 | | 生效中的目标(Goal,P5) | Goal 的 A11(§14) | @@ -297,27 +312,27 @@ TimelineTree 以 `branch/resume` 打开已有事件的根分支([timeline_tree S main: .. 8 branch/create(c1) .. 10 step/tool-result "Branch created: c1" .. 12 turn/end | 13 .. 切点 S c1: 1 branch/start 2 input/message(任务) 3 turn/start .. 25 turn/end (在切点之后) - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: 只有目录 + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end(host: session.fork) 2. 分叉提交时子分支正在运行 S main: .. 8 branch/create(c1) .. 12 turn/end | .. S c1: 1 .. 5 turn/start 6 step/tool-call (exec) <- 分叉事务在这里提交 - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: 只有目录:没有要记为失败的轮次,没有要采纳的输入,没有要唤醒的任务 + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end:没有要记为失败的轮次,没有要采纳的输入,没有要唤醒的任务 3. 子分支在切点之后收到输入 S main: .. 8 branch/create(c1) .. 12 turn/end | .. S c1: 1 .. 9 turn/end 10 input/message(steer,来自客户端) 11 turn/start .. - F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/create-failed(c1) - F c1: 只有目录 + F main: .. 12 turn/end 13 session/forked 14 branch/resume 15 branch/ended(c1) + F c1: 1 branch/end ``` | 情况 | 在源中 | 在 F 中 | | --- | --- | --- | -| 1. 子分支在切点之后完成 | 没有任何东西回到 `main`。TimelineTree 没有交回机制:`branch` 工具在子分支开始后就返回 `Branch created: `,子分支的轮次在它自己的 Timeline 上结束。`wait` 只被后台任务通知和 steer 唤醒,不等子分支 | F 的 `main` 有这次创建,若由 `branch` 工具创建还有那条工具结果,都在切点之前,之后是 `branch/create-failed`。它不会收到结果,不等待任何东西,也不记其他失败。子分支的结果仍可在 S 中读取。Dim 唯一的交回机制是 Collaboration 从成员 Session 交回结果,见上表 Collaboration 一行 | -| 2. 分叉提交时子分支正在运行 | 它的轮次、模型调用或工具批次尚未结束 | 不复制子分支的任何事件,所以没有东西被记为失败、采纳、唤醒或在共用的 `cwd` 里重新执行。F 的 `main` 收到的是 `branch/create-failed`,不是"委托失败"输入:不存在这样的输入 | -| 3. 子分支在切点之后收到输入 | `main` 无法给子分支发送输入。子分支的输入来自客户端(`session.submit {branchId}`)、它自己的能力(exec 唤醒、Collaboration 报告)和 TimelineTree 的第一个输入 | F 没有子分支的任何输入,因此不含 F 从未收到的输入 | +| 1. 子分支在切点之后完成 | 没有任何东西回到 `main`。TimelineTree 没有交回机制:`branch` 工具在子分支开始后就返回 `Branch created: `,子分支的轮次在它自己的 Timeline 上结束。`wait` 只被后台任务通知和 steer 唤醒,不等子分支 | F 的 `main` 有这次创建,若由 `branch` 工具创建还有那条工具结果,都在切点之前。该线在切点处仍打开,所以 F 结束它:它持有 `branch/end`,不会收到结果,不等待任何东西,也不记任何失败。子分支的结果仍可在 S 中读取。Dim 唯一的交回机制是 Collaboration 从成员 Session 交回结果,见上表 Collaboration 一行 | +| 2. 分叉提交时子分支正在运行 | 它的轮次、模型调用或工具批次尚未结束 | 不复制子分支的任何事件,所以没有东西被记为失败、采纳、唤醒或在共用的 `cwd` 里重新执行。F 结束这条线,不记创建失败,也没有“委托失败”输入:两者都没有发生 | +| 3. 子分支在切点之后收到输入 | `main` 无法给子分支发送输入。子分支的输入来自客户端(`session.submit {branchId}`)、它自己的能力(exec 唤醒、Collaboration 报告)和 TimelineTree 的第一个输入 | F 没有子分支的任何输入,因此不含 F 从未收到的输入;它的线已结束,不再接受输入 | 被否决:在复制来的事实之后写 `branch/start`。Prompt 把根分支的 `branch/start` 当作新 Session,会采用 `SessionConfig` 中的模型和系统提示词,从而撤销复制来的事实中的模型变更,并改变提示词前缀([prompt.rs](../../../../crates/dim-agent-capabilities/src/prompt.rs) 的 `open`)。要避免这一点,得改 TimelineTree(让已有事件的预备根分支以 start 打开)和 Prompt(区分分叉的 start 与新 Session 的 start)。而且 F 提交之后、写出 start 之前崩溃,F 仍会以 `branch/resume` 打开。 @@ -357,7 +372,7 @@ S5c 中被否决:在 S 的分叉都删除之前保留 S 的命令输出。ADR | 删除仍在构建的 Session:行已提交并已列出的 `session.create`、成员创建或分叉 | 创建从其行提交之前起持有新 id 的准入门,直到 Session 发布、协议版本记下为止(D6)。删除等待,然后关闭已发布的 Session 并删除其行。创建失败时回滚它的行,删除什么也找不到 | | 删除与 attach、submit 或 Session 方法 | 它们等准入门,然后失败于 `session_closed`;已持有使用权的请求随关闭结束 | | 删除与该 Session 自己的追加 | 关闭结算它们;行事务在 Timeline 写线程上排在所有已排队的追加之后 | -| 分叉与对源的追加 | `at` 及之前的行不变,分叉也不复制其后的任何行:子分支目录不带事件 | +| 分叉与对源的追加 | `at` 及之前的行不变,分叉也不复制其后的任何行:它复制每条线的目录,并在 F 自己的行里结束切点处仍打开的线 | | 删除 Collaboration leader | 关闭它会停止其成员请求,随后 Agents 随它删除 Team:它领导的成员与它拥有的 Agent([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命)) | | 删除成员 | leader 对它的请求像如今一样以成员已关闭结算 | | 对同一源的两次分叉 | 两个独立的 Session,各自拥有共享的文件 | @@ -371,7 +386,7 @@ S5c 中被否决:在 S 的分叉都删除之前保留 S 的命令输出。ADR [ADR 013](../../../adr/013-command-output-ownership.md) 在 v29 新增 `session_output_owners`;本页的删除与分叉步骤读写该表的行。 - 删除从现有表中删行,包括 `session_file_owners` 与 `session_output_owners`,以及 [#556 的目录投影](../../../design/appserver/native-storage-format.md#556-v23-格式决定)的派生行 `session_catalog`。 -- 分叉向现有表插入行,按字节复制存储的文本,然后在 `at + 1` 插入一行 `session/forked`(数据为空),并在同一事务内按它写入的行写下 F 的 `session_catalog` 行。头部为 0、没有事件的子分支目录是存储已经接受的状态:子分支尚未开始的创建。 +- 分叉向现有表插入行,按字节复制存储的文本,然后在 `at + 1` 插入一行 `session/forked`(数据为空),并在同一事务内按它写入的行写下 F 的 `session_catalog` 行。它写的分支目录是 `main` 那一行和每条子分支的目录;打开分叉时,切点处仍打开的子分支被结束(§6.3)。 - 事件 id 在所属 Session 内唯一,分叉在另一个 Session 中重复源的 id。存储本就按 Session 检查和索引 id;S5c 把这一点写明为不变量,不是格式变化。 - 不加来源列、不写墓碑,原因见 §4 和 §6.6。 - **兼容性(开发阶段,随 #222 决定)。** `EventKind` 是封闭列表,所以在 `session/forked` 出现之前构建的守护进程无法解码这一行,也就无法恢复由新版守护进程分叉出的 Session。这一点被接受:原生格式在首次发布前不承诺兼容,因此不升版本号,也不加回退解码或迁移。在 `0` 处分叉的 Session,以及从未被分叉的 Session,都没有这一行。已删除的 Session 读起来如同从未存在。 @@ -419,7 +434,7 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 | 规则 | 回答 | | --- | --- | -| 原则 §4 第 1 条(改别人的状态写指令) | 删除和分叉只改 Agents 与 SessionStore 自己的状态:Session 记录和行。分叉复制存储的字节,并写一条自己的事实 `session/forked`,不替其他所有者写事实;F 打开时写出的事实来自各自的所有者(TimelineTree 的 `branch/resume` 与 `branch/create-failed`、Collaboration 的失败结果)。Goal 自己依据 `session/forked` 做决定(A11)。预设是复制,不是重置(#26) | +| 原则 §4 第 1 条(改别人的状态写指令) | 删除和分叉只改 Agents 与 SessionStore 自己的状态:Session 记录和行。分叉复制存储的字节,并写一条自己的事实 `session/forked`,不替其他所有者写事实;F 打开时写出的事实来自各自的所有者(TimelineTree 的 `branch/resume` 以及它为结束复制来的线而写的 `branch/end`、Collaboration 的失败结果)。Goal 自己依据 `session/forked` 做决定(A11)。预设是复制,不是重置(#26) | | 原则 §4 第 2 条(交接) | 不适用:没有交接任何东西 | | 原则 §4 第 3 条(before 只做变换) | 没有 before 回调。Rpc 检查参数格式和 Session 的版本;切点检查是 `session.branch_create` 现有的检查加上静止点,两者都只读固定前缀 | | 原则 §4 第 4 条(核心不带业务含义) | Timeline、Dispatcher、before 和批次不变。TimelineTree 现有的规则(有事件的根分支以 resume 打开,缺少 start 的子分支是失败的创建)原样适用 | @@ -454,8 +469,8 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 1. 删除一个正在运行轮次、并有客户端附着的已加载 Session:客户端收到 `session.closed`,回复为 `{deleted: true}`,`session.summaries` 不再列出它,`session.attach` 失败于 `session_closed`。任何表中都不再有它 id 的行,`command-output//` 已移除,它的 Session 文件由清扫移除。第二次删除回复 `{deleted: false}`。 2. 删除未加载的 Session,以及行校验失败的 Session:都回复 `{deleted: true}`,不留任何行。 -3. 在 `main` 的静止点处分叉,一个子分支在切点之前创建、一个在之后:F 的 `main` 含有源截至 `at` 的事件且 id 相同,之后是 `session/forked`、`branch/resume` 和为第一个子分支写的一条 `branch/create-failed`;F 有第一个子分支的目录、没有其事件,不含第二个子分支的任何东西;F 只有其 `main` 事件引用的内容行和快照;重启后重新加载,不再写第二条 `session/forked` 或 `branch/create-failed`。在 `0` 处分叉以 `branch/start` 打开,没有 `session/forked`。 -4. §6.5 的几种情况:子分支在切点之后完成时分叉,子分支有未结束的轮次、工具批次和后台任务时分叉,客户端在切点之后给子分支发 steer 时分叉。每种情况下 F 的子分支都没有事件;客户端给 F 提交输入之前,F 不记录任何 `turn/start`、模型调用、工具执行或 `exec/started`;源的子分支不受影响地继续。 +3. 在 `main` 的静止点处分叉,一个子分支在切点之前创建、一个在之后:F 的 `main` 含有源截至 `at` 的事件且 id 相同,之后是 `session/forked` 和 `branch/resume`,没有 `branch/create-failed`;F 有每条子分支的目录,切点处仍打开的那条持有一条分叉写的 `branch/end` 及其在 `main` 上的 `branch/ended`,切点之后创建的那条不存在;F 只有其 `main` 事件引用的内容行和快照;重启后重新加载,不再写第二条 `session/forked`、`branch/end` 或 `branch/create-failed`。在 `0` 处分叉以 `branch/start` 打开,没有 `session/forked`。 +4. §6.5 的几种情况:子分支在切点之后完成时分叉,子分支有未结束的轮次、工具批次和后台任务时分叉,客户端在切点之后给子分支发 steer 时分叉。每种情况下 F 都结束这条子分支;客户端给 F 提交输入之前,F 不记录任何 `turn/start`、模型调用、工具执行或 `exec/started`;源的子分支不受影响地继续,仍接受输入,且没有自己的结束。 5. 分叉的 `SessionConfig` 文本与源相同,包括 `"interactive": false`。切点之前在源上设置的权限预设和模型就是 F 的预设和模型。 6. `at` 超过头部、位于批次内部、不在上下文边界或不是静止点(在轮次之内、有未消费的 Queue 或 Steer 输入、有运行中的后台任务或其唤醒未消费),源未知,以及 v2 连接:分叉都被拒绝,什么都没创建。 7. 在 leader 对成员的请求未结束时分叉:F 记录失败结果,不投递报告输入,不启动轮次,源的成员继续运行([#127](https://github.com/arcships/dim/issues/127))。