From 6dd9d3db9f4816dd8ff323553c05eb425ab352b3 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:59:05 +0800 Subject: [PATCH 01/10] fix(runtime): report Session restore progress and name its timeout phase A Session restore runs its store reads and line builds after every row is already Active, so the opening's inactivity bound saw no progress: a slow store made the Session fail to open, and the error ended at `initialization timed out: ` with neither a row nor a phase to act on (Refs #2038). Every TimelineTree restore step now reports opening progress with `opening_advanced` after it finishes, so a read or a line's build that runs long renews the bound instead of looking idle. When the bound still lapses with no non-Active row, the message names the phase that was running: `initialization timed out: no row pending; still running: restore`. The startup bound and the restore's behavior and step order are unchanged. A stuck required row keeps the message that lists its name, state and unmet dependencies. The tests in storage_flow cover a silent restore that names its phase and a slow restore whose steps each stay inside the bound while their total outlasts it. --- .../src/timeline_tree.rs | 130 ++++++++++++++---- crates/dim-agent-runtime/src/assembly.rs | 40 ++++-- crates/dim-app-server/tests/storage_flow.rs | 125 ++++++++++++++++- .../rust-agent/plugins/TimelineTree.md | 6 +- 4 files changed, 259 insertions(+), 42 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index deb7ef1ff7..8fa1c5c4f0 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -190,6 +190,48 @@ pub mod testing { } } } + + static RESTORE_DELAYS: Mutex> = Mutex::new(Vec::new()); + + /// Slows every restore step of one Session until dropped, so a flow test + /// can make a restore outlast a short opening bound. + pub struct SlowRestore { + session: String, + } + impl Drop for SlowRestore { + fn drop(&mut self) { + let session = std::mem::take(&mut self.session); + RESTORE_DELAYS + .lock() + .unwrap() + .retain(|(held, _)| *held != session); + } + } + + /// Slows every restore step of `session_id` by `delay`. The tests of one + /// process run in parallel, so the key is the Session. + pub fn slow_restore_steps(session_id: &str, delay: std::time::Duration) -> SlowRestore { + RESTORE_DELAYS + .lock() + .unwrap() + .push((session_id.to_owned(), delay)); + SlowRestore { + session: session_id.to_owned(), + } + } + + pub(crate) async fn restore_step(session_id: &str) { + let delay = { + let delays = RESTORE_DELAYS.lock().unwrap(); + delays + .iter() + .find(|(held, _)| held == session_id) + .map(|(_, delay)| *delay) + }; + if let Some(delay) = delay { + tokio::time::sleep(delay).await; + } + } } /// How a loaded branch begins on its Timeline. @@ -294,6 +336,9 @@ pub struct TimelineTree { factory: Arc, store: Arc, session_id: String, + /// The plugin's context, which reports a restore's progress to the + /// Session opening that waits for it. + ctx: Ctx, cancel: CancellationToken, builds: TaskTracker, close_result: watch::Sender>>, @@ -855,15 +900,19 @@ impl TimelineTree { .parent .clone() .expect("a stored descendant has a parent"); - if matches!( + let ended = matches!( self.child_terminal(&parent, &id, stored[&parent].sequence) .await?, Some(ChildTerminal::Ended(_)) - ) { + ); + self.step_finished().await; + if ended { continue; } let head = stored[&id].sequence; - let Some((end_event, data)) = self.own_end(&id, head).await? else { + let own_end = self.own_end(&id, head).await?; + self.step_finished().await; + let Some((end_event, data)) = own_end else { continue; }; let parent_head = stored[&parent].sequence; @@ -879,6 +928,7 @@ impl TimelineTree { }, ) .await?; + self.step_finished().await; stored .get_mut(&parent) .expect("the parent is stored") @@ -1018,6 +1068,7 @@ impl TimelineTree { factory: Arc, store: Arc, session_id: String, + ctx: Ctx, ) -> Arc { Arc::new_cyclic(|weak| Self { weak: weak.clone(), @@ -1035,6 +1086,7 @@ impl TimelineTree { factory, store, session_id, + ctx, cancel: CancellationToken::new(), builds: TaskTracker::new(), close_result: watch::channel(None).0, @@ -2621,6 +2673,15 @@ impl TimelineTree { }); *self.close_task.lock().unwrap() = Some(task); } + /// Reports the restore step that just finished as opening progress, so a + /// store read or a line's build that runs long renews the Session opening's + /// inactivity bound instead of looking idle. A `testing` build pauses here + /// first, so a flow test can make a restore outlast a short bound. + async fn step_finished(&self) { + #[cfg(feature = "testing")] + testing::restore_step(&self.session_id).await; + dim_agent_runtime::opening_advanced(&self.ctx); + } /// The default branch the root's stored facts name, or the root: the /// newest `branch/default` or `session/forked` on the root, by the same /// kind index the writer's cache uses (design §5, §20.20). A @@ -2822,17 +2883,22 @@ impl TimelineTreeControl for TimelineTree { self.create_main().await?; return Ok(()); } - let restored = match branches.len() { - 1 => None, - _ => self.recorded_default(&branches).await?, + let restored = if branches.len() > 1 { + let restored = self.recorded_default(&branches).await?; + self.step_finished().await; + restored + } else { + None }; // The fact as of load is the tree's default before any line loads: // BranchLine reconciles its note in `apply`, which runs before the // line is ready and the Session publishes (design §5, §20.24a). - if let Some(default) = &restored - && self.restorable_default(&branches, default).await? - { - self.state.lock().unwrap().default = default.clone(); + if let Some(default) = &restored { + let restorable = self.restorable_default(&branches, default).await?; + self.step_finished().await; + if restorable { + self.state.lock().unwrap().default = default.clone(); + } } let mut remaining: BTreeMap<_, _> = branches .into_iter() @@ -2874,7 +2940,9 @@ impl TimelineTreeControl for TimelineTree { let mut next: TimelineInfo = stored.info.into(); let terminal = if let Some(parent) = &next.parent { let head = self.head(parent).unwrap_or(0); - self.child_terminal(parent, &next.id, head).await? + let terminal = self.child_terminal(parent, &next.id, head).await?; + self.step_finished().await; + terminal } else { None }; @@ -2902,6 +2970,7 @@ impl TimelineTreeControl for TimelineTree { { let (opening, end_event) = self.lifecycle(&next.id, stored.sequence).await?; + self.step_finished().await; if opening.is_some() { self.state.lock().unwrap().ended.insert( next.id.clone(), @@ -2917,21 +2986,29 @@ impl TimelineTreeControl for TimelineTree { inactive.insert(next.id); continue; } - let own_end = if next.parent.is_some() - && self.lifecycle(&next.id, stored.sequence).await?.1.is_some() - { - self.own_end(&next.id, stored.sequence).await? + let own_end = if next.parent.is_some() { + let ended = self.lifecycle(&next.id, stored.sequence).await?; + self.step_finished().await; + if ended.1.is_some() { + let own_end = self.own_end(&next.id, stored.sequence).await?; + self.step_finished().await; + own_end + } else { + None + } } else { None }; if let Some((end_event, data)) = own_end { self.complete_stored_ends(&next, &mut remaining).await?; + self.step_finished().await; if let (Some(message), Some(parent)) = (&data.final_message, next.parent.as_deref()) && self.owned_context(parent).is_some() { self.deliver_final(parent, &next.id, message, end_event) .await?; + self.step_finished().await; } let head = remaining[&next.id].sequence; self.complete_end(&next, end_event, data)?; @@ -2947,13 +3024,18 @@ impl TimelineTreeControl for TimelineTree { inactive.insert(next.id); continue; } - if next.parent.is_some() && !self.created(&next.id, stored.sequence).await? { - 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; + if next.parent.is_some() { + 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)?; + remaining.remove(&next.id); + inactive.insert(next.id); + continue; + } } if let Some(parent) = &next.parent { next.source = self @@ -2963,6 +3045,7 @@ impl TimelineTreeControl for TimelineTree { next.create_anchor.expect("child creation position"), ) .await?; + self.step_finished().await; } let ancestors = match &next.parent { Some(parent) => { @@ -2993,6 +3076,7 @@ impl TimelineTreeControl for TimelineTree { ready }; Self::await_branch(ready).await?; + self.step_finished().await; remaining.remove(&next.id); } if let Some(default) = restored.filter(|default| self.selectable_now(default)) { @@ -3241,7 +3325,7 @@ impl DynPlugin for TimelineTreePlugin { text: PARENT_ENTRY.into(), }, )?; - let tree = TimelineTree::new(factory, store, identity.session_id.clone()); + let tree = TimelineTree::new(factory, store, identity.session_id.clone(), ctx.clone()); let owner = tree.clone(); ctx.effect(move || async move { owner.close().await.map_err(Into::into) })?; let commands = Arc::new(TreeCommands { diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index fd1b06275f..5384740ea3 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -34,12 +34,13 @@ impl rutis::Event for OpeningAdvanced { } /// Reports that the opening this context's plugin belongs to advanced: the -/// plugin made real progress in its `apply`. Any plugin whose opening can run -/// long may call it; it renews the [`StartupProgress`] inactivity interval of -/// every opening whose subtree contains the plugin's row, and changes nothing -/// else about the opening. A report is a synchronous event, so a plugin whose -/// work runs on a blocking thread reports from there. A context whose plugin -/// has no live fiber reports nothing: the report would be dropped anyway. +/// plugin made real progress in work the opening waits for, its own `apply` or +/// a restore of the lines it owns. Any plugin whose opening can run long may +/// call it; it renews the [`StartupProgress`] inactivity interval of every +/// opening whose subtree contains the plugin's row, and changes nothing else +/// about the opening. A report is a synchronous event, so a plugin whose work +/// runs on a blocking thread reports from there. A context whose plugin has no +/// live fiber reports nothing: the report would be dropped anyway. pub fn opening_advanced(ctx: &Ctx) { let instance = ctx.instance(); let id = ctx @@ -1588,7 +1589,7 @@ async fn create_instance( .and_then(|instance| locate(loader, ctx, instance)); let error = match &found { _ if cancel.is_cancelled() => AgentError::Cancelled("initialization".into()), - Some(created) => timed_out(ctx, &created.children), + Some(created) => timed_out(ctx, &created.children, "instance creation"), None => AgentError::Build(format!("initialization timed out: {group}")), }; if found.is_none() { @@ -1630,7 +1631,7 @@ async fn create_instance( let mut ready = progress .wait(active_rows(&group, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &group))); + .unwrap_or_else(|| Err(timed_out(ctx, &group, "instance creation"))); // Read after the group is Active: a settle can return while it still waits, // and its rows are the ones the required-row wait has to name. let mut waiting: Vec = loader @@ -1643,7 +1644,7 @@ async fn create_instance( ready = progress .wait(active_rows(&waiting, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &waiting))); + .unwrap_or_else(|| Err(timed_out(ctx, &waiting, "instance creation"))); } let mut handed = Handed::default(); if ready.is_ok() { @@ -1654,7 +1655,7 @@ async fn create_instance( vec![created.view.id] }) .await - .unwrap_or_else(|| Err(timed_out(ctx, &handed.required))); + .unwrap_or_else(|| Err(timed_out(ctx, &handed.required, "instance creation"))); if let Err(error) = &ready && failed_mounter(&handed.required).is_some() { @@ -1667,7 +1668,7 @@ async fn create_instance( ready = progress .wait(active_rows(&parts, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &parts))); + .unwrap_or_else(|| Err(timed_out(ctx, &parts, "instance creation"))); } // Parts create nested instances while they load, and their rows are this // creation's members: read them once the waits above are done. @@ -1699,7 +1700,7 @@ async fn create_instance( || vec![created.view.id], ) .await - .unwrap_or_else(|| Err(timed_out(ctx, &created.children))); + .unwrap_or_else(|| Err(timed_out(ctx, &created.children, "instance creation"))); match settled { Ok(()) => Ok(created), Err(error) => Err((error, Some(created))), @@ -1880,6 +1881,10 @@ pub(crate) async fn build_session( &session.ctx, session.scope.key::(), )?; + let phase = match &initialization { + SessionInitialization::Prepared(_) | SessionInitialization::Restore(_) => "restore", + SessionInitialization::New => "Session creation", + }; let initialize = async { match initialization { SessionInitialization::Prepared(branches) @@ -1894,7 +1899,7 @@ pub(crate) async fn build_session( match result { Some(result) => result, None => { - let error = timed_out(host, std::slice::from_ref(&created.view)); + let error = timed_out(host, std::slice::from_ref(&created.view), phase); tree.begin_close(); let _ = initialize.await; Err(error) @@ -1989,7 +1994,7 @@ pub async fn wait_active( views.iter().map(|view| view.id).collect() }) .await - .unwrap_or_else(|| Err(timed_out(ctx, views))) + .unwrap_or_else(|| Err(timed_out(ctx, views, "row activation"))) } async fn active_rows(views: &[FiberView], cancel: &CancellationToken) -> Result<()> { @@ -2036,7 +2041,7 @@ async fn active_rows(views: &[FiberView], cancel: &CancellationToken) -> Result< } } } -fn timed_out(ctx: &Ctx, views: &[FiberView]) -> AgentError { +fn timed_out(ctx: &Ctx, views: &[FiberView], phase: &str) -> AgentError { let snapshot = ctx.diagnostics(); let ids: HashSet<_> = views .iter() @@ -2056,6 +2061,11 @@ fn timed_out(ctx: &Ctx, views: &[FiberView]) -> AgentError { format!("{} {:?} [{}]", p.name, p.state, unmet.join(", ")) }) .collect(); + if pending.is_empty() { + return AgentError::Build(format!( + "initialization timed out: no row pending; still running: {phase}" + )); + } AgentError::Build(format!("initialization timed out: {}", pending.join("; "))) } diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 99f561e6af..212c8d3f9a 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -14,9 +14,9 @@ use dim_agent_capabilities::file_storage::FileStoragePlugin; use dim_agent_capabilities::history::HistoryRenderer; use dim_agent_runtime::testing::{chain_events, timeline_events}; use dim_agent_runtime::{ - AgentBuilder, AgentConfig, AgentError, MemoryTimelineStore, SessionConfig, StoredEvent, - Timeline, TimelineKey, TimelineQueryScope, TimelineStore, TimelineTrace, TraceStep, - testing::MinimalHost, + AgentBuilder, AgentConfig, AgentError, BranchOptions, MemoryTimelineStore, SessionConfig, + StoredEvent, Timeline, TimelineKey, TimelineQueryScope, TimelineStore, TimelineTrace, + TraceStep, testing::MinimalHost, }; use dim_agent_types::{ grant::{GrantKind, GrantMode, SessionGrant}, @@ -2319,6 +2319,125 @@ async fn branch_end_events_restore_unchanged_and_the_line_stays_ended() { db.close().await.unwrap(); } +/// A stored Session on its root and one open child line, as the next process +/// finds it: the Session id and the child line's id, with the database closed. +async fn stored_two_line_session(database: &Database) -> (String, String) { + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let mut builder = AgentBuilder::new(AgentConfig::default()); + dim_agent_capabilities::defaults::mock_hosts(&mut builder); + dim_agent_capabilities::defaults::install(&mut builder); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); + let agent = MinimalHost::start(&builder).await.unwrap(); + let session = settled( + "the Session opens", + agent.create_session(SessionConfig::default()), + ) + .await + .unwrap(); + settled("the root line idles", session.idle("main")) + .await + .unwrap(); + let cut = session.sequence("main").unwrap(); + let child = settled( + "the child line opens", + session.branch( + "main".into(), + cut, + BranchOptions { + prompt: "child work".into(), + source: BranchSource::Host { + operation_id: "restore-progress".into(), + }, + }, + ), + ) + .await + .unwrap(); + settled("the child line idles", session.idle(&child)) + .await + .unwrap(); + let id = session.id().to_owned(); + settled("the first host closes", agent.close()) + .await + .unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); + (id, child) +} + +/// The host that restores a stored Session, its opening bounded by `bound`. +async fn restoring_host( + database: &Database, + bound: Duration, +) -> (MinimalHost, Arc, Arc) { + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let mut builder = AgentBuilder::new(AgentConfig::default()); + dim_agent_capabilities::defaults::mock_hosts(&mut builder); + dim_agent_capabilities::defaults::install(&mut builder); + builder.startup_timeout(bound); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); + let agent = MinimalHost::start(&builder).await.unwrap(); + (agent, store, db) +} + +/// A restore that reports no progress for longer than `startup_timeout` still +/// names what it was running: every row is Active, so the message cannot list +/// one. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_silent_restore_times_out_naming_the_restore_phase() { + use dim_agent_capabilities::timeline_tree::testing::slow_restore_steps; + let database = Database::new(); + let (id, _) = stored_two_line_session(&database).await; + let _slow = slow_restore_steps(&id, Duration::from_millis(1500)); + let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; + let error = match settled("the silent restore times out", agent.restore_session(id)).await { + Ok(_) => panic!("a restore silent past the bound must fail the opening"), + Err(error) => error, + }; + let message = error.to_string(); + assert!(message.contains("initialization timed out"), "{message}"); + assert!( + message.contains("restore"), + "the message names the phase still running: {message}" + ); + settled("the host closes", agent.close()).await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +/// Each restore step reports opening progress, so a restore whose steps are +/// each shorter than `startup_timeout` and together longer still completes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_slow_restore_reports_progress_and_keeps_the_opening_alive() { + use dim_agent_capabilities::timeline_tree::testing::slow_restore_steps; + let database = Database::new(); + let (id, child) = stored_two_line_session(&database).await; + let bound = Duration::from_secs(1); + let _slow = slow_restore_steps(&id, Duration::from_millis(250)); + let (agent, store, db) = restoring_host(&database, bound).await; + let started = Instant::now(); + let session = settled("the slow restore completes", agent.restore_session(id)) + .await + .expect("reported progress renews the opening's inactivity bound"); + let elapsed = started.elapsed(); + assert!( + elapsed > bound, + "the restore must outlast the bound to exercise renewal: {elapsed:?}" + ); + let branches = session.branches(); + let ids = branches + .iter() + .map(|info| info.id.as_str()) + .collect::>(); + assert!(ids.contains(&"main"), "{ids:?}"); + assert!(ids.contains(&child.as_str()), "{ids:?}"); + settled("the host closes", agent.close()).await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + /// A history whose requests cover every list case: a new list after a /// compaction, a request keeping part and one keeping all of the previous /// one, `tools` and `system` absent, reused and changed, request drafts, and diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index 29cff9be40..168996336d 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -69,7 +69,7 @@ keyed input and reads only its keys and retire flags. Candidate branches remain receipts/dispatch fences and initial input acceptance succeed. Creation retains its fixed ancestry cut even if a waiter disappears. One opening budget requests cancellation; rollback and accepted host work must still settle. Cleanup closes -the tree, cancels reservations, joins builds and closes branch contexts. Restore settles interrupted creates without replaying external work. It selects each child's terminal kind and end position, preserving that end identity even if a fork has no own history for the child. Only a line that will mount reads its creation source at the known anchor. Accepted ancestry cuts use the directory directly; only a new cut is checked against context during creation. Tool-call +the tree, cancels reservations, joins builds and closes branch contexts. Restore settles interrupted creates without replaying external work. It selects each child's terminal kind and end position, preserving that end identity even if a fork has no own history for the child. Every restore step reports `opening_advanced`, so a store read or a line's build that runs long renews the Session opening's inactivity bound, and a timeout with every row already Active names `restore` as the phase still running. Only a line that will mount reads its creation source at the known anchor. Accepted ancestry cuts use the directory directly; only a new cut is checked against context during creation. Tool-call ancestry cuts cannot split required result relationships. Client detach is not Session close, and closing is not deletion of persisted history. @@ -92,6 +92,10 @@ Session close, and closing is not deletion of persisted history. `a_default_branch_that_was_a_tool_line_stops_sending_its_idle_notice`, `a_switched_line_keeps_its_identity_after_a_compaction`. +[storage_flow.rs](../../../../crates/dim-app-server/tests/storage_flow.rs): +`a_silent_restore_times_out_naming_the_restore_phase`, +`a_slow_restore_reports_progress_and_keeps_the_opening_alive`. + | 项 | 值 | | --- | --- | From ac74e42a3ee9dd23d2f85cfc870d8b028b7f91fc Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 03:48:42 +0800 Subject: [PATCH 02/10] fix(runtime): name only the restore phase and pin its timeout message The timeout fallback named a phase for every opening wait, but only the restore has a scenario that emits it; the instance-creation, row-activation and new-Session waits now keep their previous message, so each new text in this change is reached by a test. The fallback covers the rows the wait actually watches: a restore can be building a line that the wait does not include, so the message says "no pending row in this wait" instead of claiming nothing is pending. Only the restore passes a phase, `restore`, and the silent-restore test asserts the whole clause. The design document now says a restore of the lines a plugin owns may report opening progress, the same as its own long `apply`. --- crates/dim-agent-runtime/src/assembly.rs | 28 ++++++++++++--------- crates/dim-app-server/tests/storage_flow.rs | 5 ++-- docs/design/rutis-usage.md | 6 ++--- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 5384740ea3..aa592a3b5a 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -1589,7 +1589,7 @@ async fn create_instance( .and_then(|instance| locate(loader, ctx, instance)); let error = match &found { _ if cancel.is_cancelled() => AgentError::Cancelled("initialization".into()), - Some(created) => timed_out(ctx, &created.children, "instance creation"), + Some(created) => timed_out(ctx, &created.children, None), None => AgentError::Build(format!("initialization timed out: {group}")), }; if found.is_none() { @@ -1631,7 +1631,7 @@ async fn create_instance( let mut ready = progress .wait(active_rows(&group, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &group, "instance creation"))); + .unwrap_or_else(|| Err(timed_out(ctx, &group, None))); // Read after the group is Active: a settle can return while it still waits, // and its rows are the ones the required-row wait has to name. let mut waiting: Vec = loader @@ -1644,7 +1644,7 @@ async fn create_instance( ready = progress .wait(active_rows(&waiting, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &waiting, "instance creation"))); + .unwrap_or_else(|| Err(timed_out(ctx, &waiting, None))); } let mut handed = Handed::default(); if ready.is_ok() { @@ -1655,7 +1655,7 @@ async fn create_instance( vec![created.view.id] }) .await - .unwrap_or_else(|| Err(timed_out(ctx, &handed.required, "instance creation"))); + .unwrap_or_else(|| Err(timed_out(ctx, &handed.required, None))); if let Err(error) = &ready && failed_mounter(&handed.required).is_some() { @@ -1668,7 +1668,7 @@ async fn create_instance( ready = progress .wait(active_rows(&parts, cancel), || vec![created.view.id]) .await - .unwrap_or_else(|| Err(timed_out(ctx, &parts, "instance creation"))); + .unwrap_or_else(|| Err(timed_out(ctx, &parts, None))); } // Parts create nested instances while they load, and their rows are this // creation's members: read them once the waits above are done. @@ -1700,7 +1700,7 @@ async fn create_instance( || vec![created.view.id], ) .await - .unwrap_or_else(|| Err(timed_out(ctx, &created.children, "instance creation"))); + .unwrap_or_else(|| Err(timed_out(ctx, &created.children, None))); match settled { Ok(()) => Ok(created), Err(error) => Err((error, Some(created))), @@ -1882,8 +1882,10 @@ pub(crate) async fn build_session( session.scope.key::(), )?; let phase = match &initialization { - SessionInitialization::Prepared(_) | SessionInitialization::Restore(_) => "restore", - SessionInitialization::New => "Session creation", + SessionInitialization::Prepared(_) | SessionInitialization::Restore(_) => { + Some("restore") + } + SessionInitialization::New => None, }; let initialize = async { match initialization { @@ -1994,7 +1996,7 @@ pub async fn wait_active( views.iter().map(|view| view.id).collect() }) .await - .unwrap_or_else(|| Err(timed_out(ctx, views, "row activation"))) + .unwrap_or_else(|| Err(timed_out(ctx, views, None))) } async fn active_rows(views: &[FiberView], cancel: &CancellationToken) -> Result<()> { @@ -2041,7 +2043,7 @@ async fn active_rows(views: &[FiberView], cancel: &CancellationToken) -> Result< } } } -fn timed_out(ctx: &Ctx, views: &[FiberView], phase: &str) -> AgentError { +fn timed_out(ctx: &Ctx, views: &[FiberView], phase: Option<&str>) -> AgentError { let snapshot = ctx.diagnostics(); let ids: HashSet<_> = views .iter() @@ -2061,9 +2063,11 @@ fn timed_out(ctx: &Ctx, views: &[FiberView], phase: &str) -> AgentError { format!("{} {:?} [{}]", p.name, p.state, unmet.join(", ")) }) .collect(); - if pending.is_empty() { + if pending.is_empty() + && let Some(phase) = phase + { return AgentError::Build(format!( - "initialization timed out: no row pending; still running: {phase}" + "initialization timed out: no pending row in this wait; still running: {phase}" )); } AgentError::Build(format!("initialization timed out: {}", pending.join("; "))) diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 212c8d3f9a..d8c34771be 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -2397,9 +2397,10 @@ async fn a_silent_restore_times_out_naming_the_restore_phase() { Err(error) => error, }; let message = error.to_string(); - assert!(message.contains("initialization timed out"), "{message}"); assert!( - message.contains("restore"), + message.contains( + "initialization timed out: no pending row in this wait; still running: restore" + ), "the message names the phase still running: {message}" ); settled("the host closes", agent.close()).await.unwrap(); diff --git a/docs/design/rutis-usage.md b/docs/design/rutis-usage.md index 143ade3c18..1ccc0cef35 100644 --- a/docs/design/rutis-usage.md +++ b/docs/design/rutis-usage.md @@ -506,9 +506,9 @@ Carried from [#6](https://github.com/arcships/dim/issues/6): reconcile, required rows becoming Active and opening replay. A row's first activation during the opening, advancement of its branch's dispatch sequence, or completion of an opening receipt resets that interval. Restarting the same row does not renew it; activity in another Session does not. - A plugin whose own `apply` runs long may report real progress with `opening_advanced(ctx)` - (`dim_agent_runtime::assembly`), which resets the same interval; a plugin whose work runs on a - blocking thread reports from there. + A plugin whose own `apply`, or a restore of the lines it owns, runs long may report real progress + with `opening_advanced(ctx)` (`dim_agent_runtime::assembly`), which resets the same interval; a + plugin whose work runs on a blocking thread reports from there. There is no fixed total startup deadline. The same rule applies to Session and branch opening, process startup and restart. A branch waiting for its parent follows that parent's bounded opening rather than imposing another total deadline. From 8557ee4d91f9a61c53998f6b472967ea0fea5300 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 04:42:23 +0800 Subject: [PATCH 03/10] perf(runtime): resolve the restore reporting identity once `opening_advanced` builds a complete Rutis diagnostics snapshot to find the plugin id it reports under, and `TimelineTree::step_finished` called it after each restore step. The tree now resolves the id once on its first finished step through `OpeningReporter` and reuses it at every step, so a restore costs one snapshot per tree instead of one per step, and a Session that never restores costs none. The new flow test restores a stored Session and asserts that its tree resolved the identity exactly once, a count that does not depend on timing. The design documents state that progress reporting bounds only the gaps between steps, not a single store read. --- .../src/timeline_tree.rs | 82 +++++++++++++++++-- crates/dim-agent-runtime/src/assembly.rs | 50 +++++++++-- crates/dim-app-server/tests/storage_flow.rs | 23 ++++++ .../rust-agent/plugins/TimelineTree.md | 5 +- docs/design/rutis-usage.md | 3 +- 5 files changed, 145 insertions(+), 18 deletions(-) diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 8fa1c5c4f0..194c6d7cdf 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -7,8 +7,8 @@ use crate::{ }; use dim_agent_runtime::{ AgentError, Branch, BranchDirectoryEntry, BranchDirectoryState, BranchLifecycle, BranchOptions, - BranchRefusal, Dispatcher, Names, QueryComparison, QueryFilter, QueryOperand, QueryOutput, - QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Result, SessionIdentity, + BranchRefusal, Dispatcher, Names, OpeningReporter, QueryComparison, QueryFilter, QueryOperand, + QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Result, SessionIdentity, StoredBranch, StoredEvent, Timeline, TimelineContext, TimelineFactory, TimelineIdentity, TimelineInfo, TimelineKey, TimelineQuery, TimelineQueryReply, TimelineQueryScope, TimelineStore, TimelineTreeControl, @@ -24,7 +24,7 @@ use std::{ num::NonZeroU64, panic::AssertUnwindSafe, sync::{ - Arc, Mutex, Weak, + Arc, Mutex, OnceLock, Weak, atomic::{AtomicBool, Ordering}, }, }; @@ -39,7 +39,9 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker}; /// its writer starting. Feature `testing` only: a production build has no hook. #[cfg(feature = "testing")] pub mod testing { + use std::sync::Arc; use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::{mpsc, watch}; type Hold = (String, mpsc::UnboundedSender, watch::Receiver); @@ -232,6 +234,58 @@ pub mod testing { tokio::time::sleep(delay).await; } } + + static IDENTITY_RESOLUTIONS: Mutex)>> = Mutex::new(Vec::new()); + + /// Counts how often one Session's tree resolves the identity its opening + /// progress is reported under, until dropped. A restore resolves it once, + /// so the count does not grow with the restore's steps. + pub struct IdentityResolutions { + session: String, + count: Arc, + } + impl IdentityResolutions { + /// The resolutions of `session_id`'s tree since this was armed. + pub fn count(&self) -> usize { + self.count.load(Ordering::Relaxed) + } + } + impl Drop for IdentityResolutions { + fn drop(&mut self) { + let session = std::mem::take(&mut self.session); + IDENTITY_RESOLUTIONS + .lock() + .unwrap() + .retain(|(held, _)| *held != session); + } + } + + /// Counts the opening report identity resolutions of `session_id`'s tree. + /// The tests of one process run in parallel, so the key is the Session. + pub fn count_identity_resolutions(session_id: &str) -> IdentityResolutions { + let count = Arc::new(AtomicUsize::new(0)); + IDENTITY_RESOLUTIONS + .lock() + .unwrap() + .push((session_id.to_owned(), count.clone())); + IdentityResolutions { + session: session_id.to_owned(), + count, + } + } + + pub(crate) fn identity_resolved(session_id: &str) { + let count = { + let resolutions = IDENTITY_RESOLUTIONS.lock().unwrap(); + resolutions + .iter() + .find(|(held, _)| held == session_id) + .map(|(_, count)| count.clone()) + }; + if let Some(count) = count { + count.fetch_add(1, Ordering::Relaxed); + } + } } /// How a loaded branch begins on its Timeline. @@ -336,9 +390,12 @@ pub struct TimelineTree { factory: Arc, store: Arc, session_id: String, - /// The plugin's context, which reports a restore's progress to the - /// Session opening that waits for it. + /// The plugin's context; the restore resolves the identity it reports + /// progress under from it once. ctx: Ctx, + /// The restore's reporting identity, resolved on the first finished step + /// so a Session that never restores costs no diagnostics snapshot. + reporter: OnceLock>, cancel: CancellationToken, builds: TaskTracker, close_result: watch::Sender>>, @@ -1087,6 +1144,7 @@ impl TimelineTree { store, session_id, ctx, + reporter: OnceLock::new(), cancel: CancellationToken::new(), builds: TaskTracker::new(), close_result: watch::channel(None).0, @@ -2680,7 +2738,19 @@ impl TimelineTree { async fn step_finished(&self) { #[cfg(feature = "testing")] testing::restore_step(&self.session_id).await; - dim_agent_runtime::opening_advanced(&self.ctx); + let reporter = self.reporter.get_or_init(|| { + let reporter = OpeningReporter::new(&self.ctx); + #[cfg(feature = "testing")] + { + if reporter.is_some() { + testing::identity_resolved(&self.session_id); + } + } + reporter + }); + if let Some(reporter) = reporter { + reporter.report(); + } } /// The default branch the root's stored facts name, or the root: the /// newest `branch/default` or `session/forked` on the root, by the same diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index aa592a3b5a..d37419fac5 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -41,16 +41,48 @@ impl rutis::Event for OpeningAdvanced { /// about the opening. A report is a synchronous event, so a plugin whose work /// runs on a blocking thread reports from there. A context whose plugin has no /// live fiber reports nothing: the report would be dropped anyway. +/// +/// Each call takes a process diagnostics snapshot to find the plugin's id; +/// resolve it once with [`OpeningReporter::new`] where a task reports at many +/// steps. pub fn opening_advanced(ctx: &Ctx) { - let instance = ctx.instance(); - let id = ctx - .diagnostics() - .plugins - .into_iter() - .find(|plugin| plugin.instance == instance) - .map(|plugin| plugin.id); - if let Some(id) = id { - let _ = ctx.emit(OpeningAdvanced(id)); + if let Some(reporter) = OpeningReporter::new(ctx) { + reporter.report(); + } +} + +/// The identity an opening report is attributed to, resolved once and reused at +/// every report. A task that reports at many steps, such as a restore after +/// each read, costs one process diagnostics snapshot for the whole task instead +/// of one per step. +/// +/// Every report still counts only the openings whose subtree contains the row +/// when they read it; a report after the row has ended extends no opening. +pub struct OpeningReporter { + ctx: Ctx, + id: PluginId, +} + +impl OpeningReporter { + /// Resolves the plugin id of `ctx`'s plugin, or none when no live fiber has + /// that instance. + pub fn new(ctx: &Ctx) -> Option { + let instance = ctx.instance(); + let id = ctx + .diagnostics() + .plugins + .into_iter() + .find(|plugin| plugin.instance == instance) + .map(|plugin| plugin.id)?; + Some(Self { + ctx: ctx.clone(), + id, + }) + } + + /// Reports real progress; see [`opening_advanced`]. + pub fn report(&self) { + let _ = self.ctx.emit(OpeningAdvanced(self.id)); } } diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index d8c34771be..463b99dd92 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -2439,6 +2439,29 @@ async fn a_slow_restore_reports_progress_and_keeps_the_opening_alive() { db.close().await.unwrap(); } +/// A restore resolves the identity its opening progress is reported under once +/// per tree, not once per step: the steps of a stored Session cost no complete +/// process diagnostics snapshot each. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_restore_resolves_its_reporting_identity_once() { + use dim_agent_capabilities::timeline_tree::testing::count_identity_resolutions; + let database = Database::new(); + let (id, _) = stored_two_line_session(&database).await; + let resolutions = count_identity_resolutions(&id); + let (agent, store, db) = restoring_host(&database, Duration::from_secs(10)).await; + settled("the restore completes", agent.restore_session(id)) + .await + .expect("a restore within its opening bound completes"); + assert_eq!( + resolutions.count(), + 1, + "the restore resolves the identity it reports progress under once" + ); + settled("the host closes", agent.close()).await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + /// A history whose requests cover every list case: a new list after a /// compaction, a request keeping part and one keeping all of the previous /// one, `tools` and `system` absent, reused and changed, request drafts, and diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index 168996336d..109a71d2c2 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -69,7 +69,7 @@ keyed input and reads only its keys and retire flags. Candidate branches remain receipts/dispatch fences and initial input acceptance succeed. Creation retains its fixed ancestry cut even if a waiter disappears. One opening budget requests cancellation; rollback and accepted host work must still settle. Cleanup closes -the tree, cancels reservations, joins builds and closes branch contexts. Restore settles interrupted creates without replaying external work. It selects each child's terminal kind and end position, preserving that end identity even if a fork has no own history for the child. Every restore step reports `opening_advanced`, so a store read or a line's build that runs long renews the Session opening's inactivity bound, and a timeout with every row already Active names `restore` as the phase still running. Only a line that will mount reads its creation source at the known anchor. Accepted ancestry cuts use the directory directly; only a new cut is checked against context during creation. Tool-call +the tree, cancels reservations, joins builds and closes branch contexts. Restore settles interrupted creates without replaying external work. It selects each child's terminal kind and end position, preserving that end identity even if a fork has no own history for the child. Each finished restore step reports opening progress under an identity the tree resolves once, so the gaps between steps renew the Session opening's inactivity bound, and a timeout with every row already Active names `restore` as the phase still running. That bound covers only those gaps: a single store read the restore awaits, and the branch-directory read before its first report, can still outlast it. Only a line that will mount reads its creation source at the known anchor. Accepted ancestry cuts use the directory directly; only a new cut is checked against context during creation. Tool-call ancestry cuts cannot split required result relationships. Client detach is not Session close, and closing is not deletion of persisted history. @@ -94,7 +94,8 @@ Session close, and closing is not deletion of persisted history. [storage_flow.rs](../../../../crates/dim-app-server/tests/storage_flow.rs): `a_silent_restore_times_out_naming_the_restore_phase`, -`a_slow_restore_reports_progress_and_keeps_the_opening_alive`. +`a_slow_restore_reports_progress_and_keeps_the_opening_alive`, +`a_restore_resolves_its_reporting_identity_once`. | 项 | 值 | diff --git a/docs/design/rutis-usage.md b/docs/design/rutis-usage.md index 1ccc0cef35..efd7d4bf2d 100644 --- a/docs/design/rutis-usage.md +++ b/docs/design/rutis-usage.md @@ -508,7 +508,8 @@ Carried from [#6](https://github.com/arcships/dim/issues/6): that interval. Restarting the same row does not renew it; activity in another Session does not. A plugin whose own `apply`, or a restore of the lines it owns, runs long may report real progress with `opening_advanced(ctx)` (`dim_agent_runtime::assembly`), which resets the same interval; a - plugin whose work runs on a blocking thread reports from there. + plugin whose work runs on a blocking thread reports from there. A report bounds the gap since the + previous one, not any single await: work that stalls without reporting still times out. There is no fixed total startup deadline. The same rule applies to Session and branch opening, process startup and restart. A branch waiting for its parent follows that parent's bounded opening rather than imposing another total deadline. From 26b10c12a14680fd96416942dd2b23caebee479d Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 05:10:54 +0800 Subject: [PATCH 04/10] test(app-server): bound the restore identity test like its siblings The restore identity test restored a stored Session under a ten-second opening bound that no other restore test uses. It now passes the same one-second bound as the silent and the slow restore tests, so restore tests share one opening bound and the file gains no new duration. --- crates/dim-app-server/tests/storage_flow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 463b99dd92..a984d65f98 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -2448,7 +2448,7 @@ async fn a_restore_resolves_its_reporting_identity_once() { let database = Database::new(); let (id, _) = stored_two_line_session(&database).await; let resolutions = count_identity_resolutions(&id); - let (agent, store, db) = restoring_host(&database, Duration::from_secs(10)).await; + let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; settled("the restore completes", agent.restore_session(id)) .await .expect("a restore within its opening bound completes"); From 42a45b65d23cad6a0913e1388d83d18918d78586 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 05:10:54 +0800 Subject: [PATCH 05/10] docs(rutis): state in the Chinese guide that progress reports bound only the gaps between steps The Chinese guide now carries the sentence its English counterpart already has: a report bounds the gap since the previous one, not any single await, so work that stalls without reporting still times out. --- docs/zh/design/rutis-usage.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/zh/design/rutis-usage.md b/docs/zh/design/rutis-usage.md index 5a8dee4014..5db07c0d09 100644 --- a/docs/zh/design/rutis-usage.md +++ b/docs/zh/design/rutis-usage.md @@ -393,6 +393,7 @@ Agent(`AgentBuilder::build`),宿主以 `partRegistry` 把它提供给自 组合检查此时也覆盖它;缺少它也能工作的依赖用 `get_at` 读取,不列在 `injects` 中。它的名称仍须登记。 - **启动进展。** `startup_timeout` 限制 loader 启动、reconcile、必需行就绪和打开重放期间连续没有进展的时间。本次打开中一行的首次激活、分支派发序号前进或一份打开回执完成会重置间隔;同一行反复重启不算新的进展。 `apply` 运行较久的插件可用 `opening_advanced(ctx)`(`dim_agent_runtime::assembly`)报告真实进展,同样重置该间隔;工作在阻塞线程上运行的插件从那里报告。 + 这个界限只覆盖步骤之间的间隔,而不是任何单次 await:不上报就停滞的工作仍然会超时。 只计本次打开范围内的进展,其他 Session 的活动不算;不设固定总时限。 Session、分支、进程启动和 restart 使用同一规则。分支等待父分支时跟随父分支自身受限的打开过程, 不另加总时限。没有进展时列出未 Active 的行及缺少的依赖并失败;组合错误或必需提供者失败立即返回。 From 2920490deb2f7e970cf107f9648110052a2888d6 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 05:20:09 +0800 Subject: [PATCH 06/10] docs(rutis): mirror the restore clause and name the scoped reporter The Chinese guide was missing the English clause about a restore of the lines a plugin owns, so a plugin whose restore runs long had no stated way to report that it advanced. Both guides named only `opening_advanced`, which resolves the reporting identity on every call. They now say that a multi-step process such as a restore resolves it once with `OpeningReporter::new` and reports through the same reporter at every step, taking one process diagnostics snapshot instead of one per step. --- docs/design/rutis-usage.md | 3 +++ docs/zh/design/rutis-usage.md | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/design/rutis-usage.md b/docs/design/rutis-usage.md index efd7d4bf2d..735ac73653 100644 --- a/docs/design/rutis-usage.md +++ b/docs/design/rutis-usage.md @@ -510,6 +510,9 @@ Carried from [#6](https://github.com/arcships/dim/issues/6): with `opening_advanced(ctx)` (`dim_agent_runtime::assembly`), which resets the same interval; a plugin whose work runs on a blocking thread reports from there. A report bounds the gap since the previous one, not any single await: work that stalls without reporting still times out. + A multi-step process such as a restore resolves its reporting identity once with + `OpeningReporter::new` (`dim_agent_runtime`) and reports through the same reporter at every step, + so it takes one process diagnostics snapshot instead of one per step. There is no fixed total startup deadline. The same rule applies to Session and branch opening, process startup and restart. A branch waiting for its parent follows that parent's bounded opening rather than imposing another total deadline. diff --git a/docs/zh/design/rutis-usage.md b/docs/zh/design/rutis-usage.md index 5db07c0d09..dc36b42096 100644 --- a/docs/zh/design/rutis-usage.md +++ b/docs/zh/design/rutis-usage.md @@ -392,8 +392,9 @@ Agent(`AgentBuilder::build`),宿主以 `partRegistry` 把它提供给自 - **可选依赖与由配置选择的依赖。** 同 §3.5:由配置选择的依赖在被选中时门控(工厂填的 `Option>`), 组合检查此时也覆盖它;缺少它也能工作的依赖用 `get_at` 读取,不列在 `injects` 中。它的名称仍须登记。 - **启动进展。** `startup_timeout` 限制 loader 启动、reconcile、必需行就绪和打开重放期间连续没有进展的时间。本次打开中一行的首次激活、分支派发序号前进或一份打开回执完成会重置间隔;同一行反复重启不算新的进展。 - `apply` 运行较久的插件可用 `opening_advanced(ctx)`(`dim_agent_runtime::assembly`)报告真实进展,同样重置该间隔;工作在阻塞线程上运行的插件从那里报告。 + 自身 `apply` 或它拥有的行的恢复运行较久的插件,可用 `opening_advanced(ctx)`(`dim_agent_runtime::assembly`)报告真实进展,同样重置该间隔;工作在阻塞线程上运行的插件从那里报告。 这个界限只覆盖步骤之间的间隔,而不是任何单次 await:不上报就停滞的工作仍然会超时。 + 恢复这类多步过程用 `OpeningReporter::new`(`dim_agent_runtime`)只解析一次身份,之后每一步通过同一个上报器上报,整个任务只取一份进程诊断快照,而不是每一步一份。 只计本次打开范围内的进展,其他 Session 的活动不算;不设固定总时限。 Session、分支、进程启动和 restart 使用同一规则。分支等待父分支时跟随父分支自身受限的打开过程, 不另加总时限。没有进展时列出未 Active 的行及缺少的依赖并失败;组合错误或必需提供者失败立即返回。 From 5de6f31c817a3185461a791f9696c2df3607dd82 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 06:16:23 +0800 Subject: [PATCH 07/10] test(runtime): resolve the reporting identity per tree generation Each tree resolves the reporting identity its reports are attributed to when it first reports, and the copy that creates the tree is the one that closes it: the owning row's unload withdraws the part registration, disposes every copy, and only then does the next generation apply and create its own tree. A row reload therefore rebuilds the tree and its cached identity together instead of leaving a stale one behind. The flow test restores a stored Session, closes it, restores it again, and pins that the two trees resolved different fibers and that the second one is live, so each tree reports under its own generation and no report is attributed to a fiber that has gone. The suite cannot reload the row while a Session stays open. Restarting the feature row withdraws its registration and disposes the tree copy, and a tree mounted into an open Session is never restored, so no report follows. The test moves between generations by restoring the Session, and the row-reload path is stated by the code that creates and disposes the tree. The capabilities testing feature now enables the runtime testing feature: the identity hook reads the reporter's resolved fiber through the runtime API that only exists in testing builds, and the library must compile when its testing feature is on by itself. --- crates/dim-agent-capabilities/Cargo.toml | 6 +- .../src/timeline_tree.rs | 52 +++++++++------- crates/dim-agent-runtime/src/assembly.rs | 7 +++ crates/dim-app-server/tests/storage_flow.rs | 59 ++++++++++++++++++- 4 files changed, 101 insertions(+), 23 deletions(-) diff --git a/crates/dim-agent-capabilities/Cargo.toml b/crates/dim-agent-capabilities/Cargo.toml index fc37b6d454..d19d17f453 100644 --- a/crates/dim-agent-capabilities/Cargo.toml +++ b/crates/dim-agent-capabilities/Cargo.toml @@ -45,8 +45,10 @@ libc = "0.2.189" windows-sys = { version = "0.61.2", features = ["Wdk_Foundation", "Wdk_Storage_FileSystem", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Com", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_SystemServices", "Win32_System_Threading", "Win32_UI_Shell"] } [features] -# Hooks that race flow tests use to hold an operation open. -testing = [] +# Hooks that race flow tests use to hold an operation open. They read the +# runtime's testing-only APIs, so the feature enables it for this crate's build +# too, not just for the test that links both. +testing = ["dim-agent-runtime/testing"] [dev-dependencies] dim-agent-runtime = { workspace = true, features = ["testing"] } diff --git a/crates/dim-agent-capabilities/src/timeline_tree.rs b/crates/dim-agent-capabilities/src/timeline_tree.rs index 194c6d7cdf..591f9c90eb 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree.rs @@ -39,9 +39,9 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker}; /// its writer starting. Feature `testing` only: a production build has no hook. #[cfg(feature = "testing")] pub mod testing { + use rutis::host::PluginId; use std::sync::Arc; use std::sync::Mutex; - use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::{mpsc, watch}; type Hold = (String, mpsc::UnboundedSender, watch::Receiver); @@ -235,19 +235,26 @@ pub mod testing { } } - static IDENTITY_RESOLUTIONS: Mutex)>> = Mutex::new(Vec::new()); + type Resolutions = Arc>>; + static IDENTITY_RESOLUTIONS: Mutex> = Mutex::new(Vec::new()); - /// Counts how often one Session's tree resolves the identity its opening - /// progress is reported under, until dropped. A restore resolves it once, - /// so the count does not grow with the restore's steps. + /// Counts how often one Session's trees resolve the identity their opening + /// progress is reported under, and names the fibers they resolved, until + /// dropped. A restore resolves it once, so the list does not grow with the + /// restore's steps. pub struct IdentityResolutions { session: String, - count: Arc, + ids: Resolutions, } impl IdentityResolutions { - /// The resolutions of `session_id`'s tree since this was armed. + /// The fibers the trees of `session_id` resolved since this was armed, + /// oldest first. + pub fn ids(&self) -> Vec { + self.ids.lock().unwrap().clone() + } + /// The resolutions of `session_id`'s trees since this was armed. pub fn count(&self) -> usize { - self.count.load(Ordering::Relaxed) + self.ids.lock().unwrap().len() } } impl Drop for IdentityResolutions { @@ -260,30 +267,30 @@ pub mod testing { } } - /// Counts the opening report identity resolutions of `session_id`'s tree. + /// Counts the opening report identity resolutions of `session_id`'s trees. /// The tests of one process run in parallel, so the key is the Session. pub fn count_identity_resolutions(session_id: &str) -> IdentityResolutions { - let count = Arc::new(AtomicUsize::new(0)); + let ids = Arc::new(Mutex::new(Vec::new())); IDENTITY_RESOLUTIONS .lock() .unwrap() - .push((session_id.to_owned(), count.clone())); + .push((session_id.to_owned(), ids.clone())); IdentityResolutions { session: session_id.to_owned(), - count, + ids, } } - pub(crate) fn identity_resolved(session_id: &str) { - let count = { + pub(crate) fn identity_resolved(session_id: &str, id: PluginId) { + let ids = { let resolutions = IDENTITY_RESOLUTIONS.lock().unwrap(); resolutions .iter() .find(|(held, _)| held == session_id) - .map(|(_, count)| count.clone()) + .map(|(_, ids)| ids.clone()) }; - if let Some(count) = count { - count.fetch_add(1, Ordering::Relaxed); + if let Some(ids) = ids { + ids.lock().unwrap().push(id); } } } @@ -394,7 +401,12 @@ pub struct TimelineTree { /// progress under from it once. ctx: Ctx, /// The restore's reporting identity, resolved on the first finished step - /// so a Session that never restores costs no diagnostics snapshot. + /// so a Session that never restores costs no diagnostics snapshot. It is + /// the id of the copy that creates this tree and closes it again + /// (`TimelineTreePlugin::apply` below); the owning row's unload disposes + /// that copy, and so the tree, before the next generation applies + /// (`PartRegistry::register`), so a row reload rebuilds the tree and its id + /// rather than leaving a stale one behind. reporter: OnceLock>, cancel: CancellationToken, builds: TaskTracker, @@ -2742,8 +2754,8 @@ impl TimelineTree { let reporter = OpeningReporter::new(&self.ctx); #[cfg(feature = "testing")] { - if reporter.is_some() { - testing::identity_resolved(&self.session_id); + if let Some(reporter) = &reporter { + testing::identity_resolved(&self.session_id, reporter.id()); } } reporter diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index d37419fac5..45252e81a7 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -84,6 +84,13 @@ impl OpeningReporter { pub fn report(&self) { let _ = self.ctx.emit(OpeningAdvanced(self.id)); } + + /// The fiber this reporter's reports are attributed to. Feature `testing` + /// only: a flow test asserts which tree's fiber a report lands on. + #[cfg(feature = "testing")] + pub fn id(&self) -> PluginId { + self.id + } } type ProgressReport = Arc; diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index a984d65f98..c033b6143f 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -27,7 +27,7 @@ use dim_app_server::storage::{ NodeLoads, STORE_FORMAT, SqliteStorage, SqliteTimelineStore, vacuum_store, }; use rusqlite::{Connection, OptionalExtension, params}; -use rutis::host::CtxHost; +use rutis::host::{CtxHost, FiberState}; use std::{ path::PathBuf, sync::Arc, @@ -2462,6 +2462,63 @@ async fn a_restore_resolves_its_reporting_identity_once() { db.close().await.unwrap(); } +/// Each tree resolves the identity its opening progress is reported under +/// within its own generation: a Session whose tree closed and was restored +/// again reports under the new tree's live fiber, never the previous one's. A +/// row reload rebuilds the tree by the same path (`TimelineTreePlugin::apply` +/// creates it, and the owning row's unload withdraws the registration that +/// disposes every copy), but the suite can only move to another generation by +/// restoring the Session. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn each_tree_generation_resolves_its_own_reporting_identity() { + use dim_agent_capabilities::timeline_tree::testing::count_identity_resolutions; + let database = Database::new(); + let (id, _) = stored_two_line_session(&database).await; + let resolutions = count_identity_resolutions(&id); + let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; + let session = settled( + "the first restore completes", + agent.restore_session(id.clone()), + ) + .await + .expect("a restore within its opening bound completes"); + settled("the first Session closes", session.close()) + .await + .unwrap(); + let second = settled("the second restore completes", agent.restore_session(id)) + .await + .expect("a restore within its opening bound completes"); + let ids = resolutions.ids(); + assert_eq!( + ids.len(), + 2, + "each tree resolves the identity its reports are attributed to" + ); + assert_ne!( + ids[0], ids[1], + "the second tree resolves its own fiber, not the previous generation's" + ); + let live = second.diagnostics().unwrap().plugins; + assert!( + live.iter().any(|plugin| plugin.id == ids[1] + && plugin.name == "TimelineTree" + && plugin.state == FiberState::Active), + "the second tree reports under its own live fiber" + ); + assert!( + !agent + .root() + .diagnostics() + .plugins + .iter() + .any(|plugin| plugin.id == ids[0] && plugin.state == FiberState::Active), + "the first tree's fiber is gone, so a report under it would be dropped" + ); + settled("the host closes", agent.close()).await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + /// A history whose requests cover every list case: a new list after a /// compaction, a request keeping part and one keeping all of the previous /// one, `tools` and `system` absent, reused and changed, request drafts, and From 0b2fbe0cd183411f854db38902f3e5d2971e9748 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 07:07:58 +0800 Subject: [PATCH 08/10] test(runtime): cover the reporting identity across a row reload `a_row_reload_resolves_the_new_tree_reporting_identity` reloads the `TimelineTree` feature row of a host whose Session is already open. A test-only Session part declares the tree's name, so it reloads with the row and captures the tree each generation mounts. The flow restores the stored branch directory on the reloaded tree, then asserts that the two generations resolved different fibers, that the second one is the reloaded tree's live `TimelineTree` fiber, and that the disposed copy's fiber is no longer Active. The restore-generation test and its comment stay; the comment no longer claims that restoring the Session is the only way the suite can reach another tree. The plugins page lists both tests. --- crates/dim-app-server/tests/storage_flow.rs | 135 ++++++++++++++++-- .../rust-agent/plugins/TimelineTree.md | 4 +- 2 files changed, 130 insertions(+), 9 deletions(-) diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index c033b6143f..b4eb712e6b 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -14,9 +14,9 @@ use dim_agent_capabilities::file_storage::FileStoragePlugin; use dim_agent_capabilities::history::HistoryRenderer; use dim_agent_runtime::testing::{chain_events, timeline_events}; use dim_agent_runtime::{ - AgentBuilder, AgentConfig, AgentError, BranchOptions, MemoryTimelineStore, SessionConfig, - StoredEvent, Timeline, TimelineKey, TimelineQueryScope, TimelineStore, TimelineTrace, - TraceStep, testing::MinimalHost, + AgentBuilder, AgentConfig, AgentError, BranchOptions, Feature, MemoryTimelineStore, + SessionConfig, StoredEvent, Timeline, TimelineKey, TimelineQueryScope, TimelineStore, + TimelineTrace, TimelineTreeControl, TraceStep, testing::MinimalHost, }; use dim_agent_types::{ grant::{GrantKind, GrantMode, SessionGrant}, @@ -2464,11 +2464,7 @@ async fn a_restore_resolves_its_reporting_identity_once() { /// Each tree resolves the identity its opening progress is reported under /// within its own generation: a Session whose tree closed and was restored -/// again reports under the new tree's live fiber, never the previous one's. A -/// row reload rebuilds the tree by the same path (`TimelineTreePlugin::apply` -/// creates it, and the owning row's unload withdraws the registration that -/// disposes every copy), but the suite can only move to another generation by -/// restoring the Session. +/// again reports under the new tree's live fiber, never the previous one's. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn each_tree_generation_resolves_its_own_reporting_identity() { use dim_agent_capabilities::timeline_tree::testing::count_identity_resolutions; @@ -2519,6 +2515,129 @@ async fn each_tree_generation_resolves_its_own_reporting_identity() { db.close().await.unwrap(); } +/// A Session part that hands the flow the tree copy its Session's row mounts. +/// Its declared inject makes it reload with that copy, so every tree it +/// captures belongs to the generation that just applied. +struct CaptureTree { + tree: rutis::host::Key, + captured: tokio::sync::mpsc::UnboundedSender>, +} +impl CaptureTree { + fn new( + names: &dim_agent_runtime::Names<'_>, + captured: tokio::sync::mpsc::UnboundedSender>, + ) -> rutis::Result { + Ok(Self { + tree: names.key()?, + captured, + }) + } +} +impl rutis::host::DynPlugin for CaptureTree { + fn name(&self) -> &str { + "test.capture-tree" + } + fn injects(&self) -> Vec { + vec![self.tree.erase()] + } + fn apply<'a>( + &'a self, + ctx: &'a rutis::Ctx, + ) -> rutis::host::BoxFuture<'a, rutis::Result> { + Box::pin(async move { + let tree = ctx.require_at(&self.tree)?; + let _ = self.captured.send(tree); + Ok(rutis::host::Effect::Done) + }) + } +} + +/// A row reload rebuilds the tree for the Session that is already open: the +/// new copy's tree reports under its own live fiber, and the disposed copy's +/// fiber is no longer Active. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_row_reload_resolves_the_new_tree_reporting_identity() { + use dim_agent_capabilities::timeline_tree::testing::count_identity_resolutions; + let database = Database::new(); + let (id, _) = stored_two_line_session(&database).await; + let resolutions = count_identity_resolutions(&id); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let (captured, mut trees) = tokio::sync::mpsc::unbounded_channel(); + let mut builder = AgentBuilder::new(AgentConfig::default()); + dim_agent_capabilities::defaults::mock_hosts(&mut builder); + dim_agent_capabilities::defaults::install(&mut builder); + builder.require_feature( + Feature::new("test.capture-tree").session("test.capture-tree", move |names| { + Ok(Box::new(CaptureTree::new(names, captured.clone())?)) + }), + ); + builder.startup_timeout(Duration::from_secs(1)); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); + let agent = MinimalHost::start(&builder).await.unwrap(); + let session = settled( + "the first restore completes", + agent.restore_session(id.clone()), + ) + .await + .expect("a restore within its opening bound completes"); + let first = settled("the first tree is captured", async { + trees.recv().await.expect("a mounted tree copy") + }) + .await; + settled( + "the TimelineTree row reloads", + agent.loader().restart("TimelineTree"), + ) + .await + .expect("the row's copies reload"); + let second = settled("the reloaded tree is captured", async { + loop { + let tree = trees.recv().await.expect("a mounted tree copy"); + if !Arc::ptr_eq(&tree, &first) { + break tree; + } + } + }) + .await; + let branches = store.branches(&id).await.unwrap(); + settled( + "the reloaded tree restores the stored Session", + second.restore(branches), + ) + .await + .expect("the reloaded tree restores the stored branches"); + let ids = resolutions.ids(); + assert_eq!( + ids.len(), + 2, + "each tree resolves the identity its reports are attributed to" + ); + assert_ne!( + ids[0], ids[1], + "the reloaded tree resolves its own fiber, not the disposed copy's" + ); + let live = session.diagnostics().unwrap().plugins; + assert!( + live.iter().any(|plugin| plugin.id == ids[1] + && plugin.name == "TimelineTree" + && plugin.state == FiberState::Active), + "the reloaded tree reports under its own live fiber" + ); + assert!( + !agent + .root() + .diagnostics() + .plugins + .iter() + .any(|plugin| plugin.id == ids[0] && plugin.state == FiberState::Active), + "the reloaded row disposed the first tree's fiber" + ); + settled("the host closes", agent.close()).await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + /// A history whose requests cover every list case: a new list after a /// compaction, a request keeping part and one keeping all of the previous /// one, `tools` and `system` absent, reused and changed, request drafts, and diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index 109a71d2c2..c1ec933721 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -95,7 +95,9 @@ Session close, and closing is not deletion of persisted history. [storage_flow.rs](../../../../crates/dim-app-server/tests/storage_flow.rs): `a_silent_restore_times_out_naming_the_restore_phase`, `a_slow_restore_reports_progress_and_keeps_the_opening_alive`, -`a_restore_resolves_its_reporting_identity_once`. +`a_restore_resolves_its_reporting_identity_once`, +`each_tree_generation_resolves_its_own_reporting_identity`, +`a_row_reload_resolves_the_new_tree_reporting_identity`. | 项 | 值 | From 51eb213b05186e4690b1c5e988e9e48cc9c96711 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 07:22:27 +0800 Subject: [PATCH 09/10] test(app-server): drop the row reload test's own opening bound The row reload test wraps every wait in `settled` and opens under the default Session bound, so it needs no bound of its own; the removed one-second bound served no assertion and was a new limit. --- crates/dim-app-server/tests/storage_flow.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index b4eb712e6b..6950c21e78 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -2572,7 +2572,6 @@ async fn a_row_reload_resolves_the_new_tree_reporting_identity() { Ok(Box::new(CaptureTree::new(names, captured.clone())?)) }), ); - builder.startup_timeout(Duration::from_secs(1)); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = settled( From a4b7ec46a9446a3c469663e00e18585e43383301 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 08:48:20 +0800 Subject: [PATCH 10/10] test(app-server): open the reporting identity tests under the default bound `a_restore_resolves_its_reporting_identity_once` and `each_tree_generation_resolves_its_own_reporting_identity` assert identity counts and plugin ids, not time, so the one-second opening bound they passed served no assertion and was a new limit. They now open under the Session's default bound, with their assertions and the bounds of the two tests that measure the restore's inactivity unchanged. --- crates/dim-app-server/tests/storage_flow.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index 6950c21e78..8e14cfdd7f 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -2366,17 +2366,20 @@ async fn stored_two_line_session(database: &Database) -> (String, String) { (id, child) } -/// The host that restores a stored Session, its opening bounded by `bound`. +/// The host that restores a stored Session, its opening bounded by `bound`, or +/// by the Session's default bound when `None`. async fn restoring_host( database: &Database, - bound: Duration, + bound: Option, ) -> (MinimalHost, Arc, Arc) { let db = SqliteStorage::open(database.0.clone()).unwrap(); let store = SqliteTimelineStore::new(db.clone()); let mut builder = AgentBuilder::new(AgentConfig::default()); dim_agent_capabilities::defaults::mock_hosts(&mut builder); dim_agent_capabilities::defaults::install(&mut builder); - builder.startup_timeout(bound); + if let Some(bound) = bound { + builder.startup_timeout(bound); + } builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); (agent, store, db) @@ -2391,7 +2394,7 @@ async fn a_silent_restore_times_out_naming_the_restore_phase() { let database = Database::new(); let (id, _) = stored_two_line_session(&database).await; let _slow = slow_restore_steps(&id, Duration::from_millis(1500)); - let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; + let (agent, store, db) = restoring_host(&database, Some(Duration::from_secs(1))).await; let error = match settled("the silent restore times out", agent.restore_session(id)).await { Ok(_) => panic!("a restore silent past the bound must fail the opening"), Err(error) => error, @@ -2417,7 +2420,7 @@ async fn a_slow_restore_reports_progress_and_keeps_the_opening_alive() { let (id, child) = stored_two_line_session(&database).await; let bound = Duration::from_secs(1); let _slow = slow_restore_steps(&id, Duration::from_millis(250)); - let (agent, store, db) = restoring_host(&database, bound).await; + let (agent, store, db) = restoring_host(&database, Some(bound)).await; let started = Instant::now(); let session = settled("the slow restore completes", agent.restore_session(id)) .await @@ -2448,7 +2451,7 @@ async fn a_restore_resolves_its_reporting_identity_once() { let database = Database::new(); let (id, _) = stored_two_line_session(&database).await; let resolutions = count_identity_resolutions(&id); - let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; + let (agent, store, db) = restoring_host(&database, None).await; settled("the restore completes", agent.restore_session(id)) .await .expect("a restore within its opening bound completes"); @@ -2471,7 +2474,7 @@ async fn each_tree_generation_resolves_its_own_reporting_identity() { let database = Database::new(); let (id, _) = stored_two_line_session(&database).await; let resolutions = count_identity_resolutions(&id); - let (agent, store, db) = restoring_host(&database, Duration::from_secs(1)).await; + let (agent, store, db) = restoring_host(&database, None).await; let session = settled( "the first restore completes", agent.restore_session(id.clone()),