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 79c260329e..d6664badb9 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,6 +39,8 @@ 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 tokio::sync::{mpsc, watch}; @@ -190,6 +192,107 @@ 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; + } + } + + type Resolutions = Arc>>; + static IDENTITY_RESOLUTIONS: Mutex> = Mutex::new(Vec::new()); + + /// 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, + ids: Resolutions, + } + impl IdentityResolutions { + /// 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.ids.lock().unwrap().len() + } + } + 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 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 ids = Arc::new(Mutex::new(Vec::new())); + IDENTITY_RESOLUTIONS + .lock() + .unwrap() + .push((session_id.to_owned(), ids.clone())); + IdentityResolutions { + session: session_id.to_owned(), + ids, + } + } + + 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(|(_, ids)| ids.clone()) + }; + if let Some(ids) = ids { + ids.lock().unwrap().push(id); + } + } } /// How a loaded branch begins on its Timeline. @@ -294,6 +397,17 @@ pub struct TimelineTree { factory: Arc, store: Arc, session_id: String, + /// 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. 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, close_result: watch::Sender>>, @@ -855,15 +969,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 +997,7 @@ impl TimelineTree { }, ) .await?; + self.step_finished().await; stored .get_mut(&parent) .expect("the parent is stored") @@ -1018,6 +1137,7 @@ impl TimelineTree { factory: Arc, store: Arc, session_id: String, + ctx: Ctx, ) -> Arc { Arc::new_cyclic(|weak| Self { weak: weak.clone(), @@ -1035,6 +1155,8 @@ impl TimelineTree { factory, store, session_id, + ctx, + reporter: OnceLock::new(), cancel: CancellationToken::new(), builds: TaskTracker::new(), close_result: watch::channel(None).0, @@ -2621,6 +2743,27 @@ 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; + let reporter = self.reporter.get_or_init(|| { + let reporter = OpeningReporter::new(&self.ctx); + #[cfg(feature = "testing")] + { + if let Some(reporter) = &reporter { + testing::identity_resolved(&self.session_id, reporter.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 /// kind index the writer's cache uses (design §5, §20.20). A @@ -2822,17 +2965,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 +3022,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 +3052,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 +3068,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 +3106,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 +3127,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 +3158,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 +3407,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 6ef4c67658..10a4b80194 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -38,18 +38,65 @@ 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. +/// +/// The report is attributed to this context's instance and costs no +/// diagnostics snapshot; a task that reports at many steps may resolve its +/// plugin id once with [`OpeningReporter::new`] and report through it instead. pub fn opening_advanced(ctx: &Ctx) { if !ctx.cancellation_token().is_cancelled() { let _ = ctx.emit(OpeningAdvanced::Instance(ctx.instance().to_string())); } } +/// 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::Plugin(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; fn notify_progress(report: &Mutex>) { @@ -1594,7 +1641,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, None), None => AgentError::Build(format!("initialization timed out: {group}")), }; if found.is_none() { @@ -1636,7 +1683,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, 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 @@ -1649,7 +1696,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, None))); } let mut handed = Handed::default(); if ready.is_ok() { @@ -1660,7 +1707,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, None))); if let Err(error) = &ready && failed_mounter(&handed.required).is_some() { @@ -1673,7 +1720,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, None))); } // Parts create nested instances while they load, and their rows are this // creation's members: read them once the waits above are done. @@ -1705,7 +1752,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, None))); match settled { Ok(()) => Ok(created), Err(error) => Err((error, Some(created))), @@ -1886,6 +1933,12 @@ pub(crate) async fn build_session( &session.ctx, session.scope.key::(), )?; + let phase = match &initialization { + SessionInitialization::Prepared(_) | SessionInitialization::Restore(_) => { + Some("restore") + } + SessionInitialization::New => None, + }; let initialize = async { match initialization { SessionInitialization::Prepared(branches) @@ -1900,7 +1953,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) @@ -1995,7 +2048,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, None))) } async fn active_rows(views: &[FiberView], cancel: &CancellationToken) -> Result<()> { @@ -2042,7 +2095,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: Option<&str>) -> AgentError { let snapshot = ctx.diagnostics(); let ids: HashSet<_> = views .iter() @@ -2062,6 +2115,13 @@ fn timed_out(ctx: &Ctx, views: &[FiberView]) -> AgentError { format!("{} {:?} [{}]", p.name, p.state, unmet.join(", ")) }) .collect(); + if pending.is_empty() + && let Some(phase) = phase + { + return AgentError::Build(format!( + "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 4ad659051a..603bb1cf1f 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, Feature, MemoryTimelineStore, + SessionConfig, StoredEvent, Timeline, TimelineKey, TimelineQueryScope, TimelineStore, + TimelineTrace, TimelineTreeControl, TraceStep, testing::MinimalHost, }; use dim_agent_types::{ grant::{GrantKind, GrantMode, SessionGrant}, @@ -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, @@ -2319,6 +2319,327 @@ 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`, or +/// by the Session's default bound when `None`. +async fn restoring_host( + database: &Database, + 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); + 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) +} + +/// 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, 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, + }; + let message = error.to_string(); + assert!( + 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(); + 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, Some(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 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, None).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(); +} + +/// 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. +#[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, None).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 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.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 29cff9be40..c1ec933721 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. 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. @@ -92,6 +92,13 @@ 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`, +`a_restore_resolves_its_reporting_identity_once`, +`each_tree_generation_resolves_its_own_reporting_identity`, +`a_row_reload_resolves_the_new_tree_reporting_identity`. + | 项 | 值 | | --- | --- | diff --git a/docs/design/rutis-usage.md b/docs/design/rutis-usage.md index 143ade3c18..735ac73653 100644 --- a/docs/design/rutis-usage.md +++ b/docs/design/rutis-usage.md @@ -506,9 +506,13 @@ 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. 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 5a8dee4014..dc36b42096 100644 --- a/docs/zh/design/rutis-usage.md +++ b/docs/zh/design/rutis-usage.md @@ -392,7 +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 的行及缺少的依赖并失败;组合错误或必需提供者失败立即返回。