Persist loaded threads before managed daemon shutdown (#44283)

## Why

Loaded threads, including idle threads whose rollout files are still deferred, need to survive a managed daemon restart. Shutdown must also remain forceable when rollout I/O is blocked.

## What changed

- Add a hidden `--managed-daemon` option for app-server Unix socket transports. After active turns and admitted requests drain, save loaded persistent root threads before exiting.
- Skip ephemeral threads, non-root agent threads, and threads pending unload. Log persistence failures and continue saving other threads.
- Apply shutdown admission checks to thread and turn settings updates, thread deletion, and archiving.
- Keep force signals and daemon shutdown requests responsive during persistence. Return `AppServerExit::Forced` so executables can exit without waiting for runtime teardown.

## Testing

Add integration coverage for resuming active and idle threads after restart, forcing shutdown during active work, and forcing shutdown with a blocked rollout writer. Extend shutdown rejection coverage to deletion and settings updates.

GitOrigin-RevId: 4344e97d39f9f80c5d84c41c17300fd6aa99b4cc
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-09 19:22:22 +00:00
1 parent fcd90d8f07
commit c1840dc55e
12 files changed
+465 -16

No files matched your search

+57 -11
View File
@@ -445,6 +445,15 @@ pub async fn run_main(
AppServerRuntimeOptions::default(),
)
.await
.map(|_| ())
}
/// Reports whether shutdown finished or the managed daemon must exit without waiting for I/O.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppServerExit {
Graceful,
/// Executables should exit before dropping their runtime; libraries must not exit their host.
Forced,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -459,6 +468,7 @@ pub struct AppServerRuntimeOptions {
pub plugin_startup_tasks: PluginStartupTasks,
pub remote_control_startup_mode: RemoteControlStartupMode,
pub install_shutdown_signal_handler: bool,
pub managed_daemon: bool,
}
impl Default for AppServerRuntimeOptions {
@@ -468,6 +478,7 @@ impl Default for AppServerRuntimeOptions {
plugin_startup_tasks: PluginStartupTasks::Start,
remote_control_startup_mode: RemoteControlStartupMode::ResolvePersisted,
install_shutdown_signal_handler: true,
managed_daemon: false,
}
}
}
@@ -483,7 +494,7 @@ pub async fn run_main_with_transport_options(
session_source: SessionSource,
auth: AppServerWebsocketAuthSettings,
runtime_options: AppServerRuntimeOptions,
) -> IoResult<()> {
) -> IoResult<AppServerExit> {
let loader_overrides = loader_overrides_with_test_user_config_file(
loader_overrides,
test_user_config_file_from_env(),
@@ -741,6 +752,8 @@ pub async fn run_main_with_transport_options(
let single_client_mode = matches!(&transport, AppServerTransport::Stdio);
let graceful_signal_restart_enabled =
runtime_options.install_shutdown_signal_handler && !single_client_mode;
let managed_daemon = matches!(&transport, AppServerTransport::UnixSocket { .. })
&& runtime_options.managed_daemon;
let mut app_server_client_name_rx = None;
match &transport {
@@ -970,24 +983,43 @@ pub async fn run_main_with_transport_options(
let transport_shutdown_token = transport_shutdown_token.clone();
async move {
let mut listen_for_threads = true;
// Keep force signals and daemon control events responsive while saving.
let mut snapshot = Box::pin(processor.persist_daemon_threads());
let mut snapshot_finished = !managed_daemon;
let mut clients_disconnected = false;
let mut shutdown_state = ShutdownState::default();
let exit_reason = loop {
// Sample submissions first: one can publish a running turn before
// releasing its permit, and shutdown must observe that new turn.
let active_admissions = *active_admissions_rx.borrow_and_update();
let running_turn_count = *running_turn_count_rx.borrow_and_update();
if matches!(
let ready_to_exit = matches!(
shutdown_state.update(running_turn_count, active_admissions, connections.len()),
ShutdownAction::Finish
) {
transport_shutdown_token.cancel();
let _ = outbound_control_tx
.send(OutboundControlEvent::DisconnectAll)
.await;
break "shutdown_requested";
);
if ready_to_exit {
let finished = snapshot_finished || shutdown_state.forced();
if finished {
transport_shutdown_token.cancel();
}
if managed_daemon && shutdown_state.forced() {
break "forced_shutdown_requested";
}
if !clients_disconnected {
let _ = outbound_control_tx
.send(OutboundControlEvent::DisconnectAll)
.await;
clients_disconnected = true;
}
if finished {
break "shutdown_requested";
}
}
tokio::select! {
_ = &mut snapshot, if ready_to_exit && !snapshot_finished => {
snapshot_finished = true;
}
shutdown_signal_result = shutdown_signal(), if graceful_signal_restart_enabled && !shutdown_state.forced() => {
let signal = match shutdown_signal_result {
Ok(signal) => signal,
@@ -1013,6 +1045,12 @@ pub async fn run_main_with_transport_options(
let Some(event) = event else {
break "transport_channel_closed";
};
if ready_to_exit && !matches!(event, TransportEvent::DaemonShutdown) {
if let TransportEvent::ConnectionOpened { disconnect_sender: Some(token), .. } = event {
token.cancel();
}
continue;
}
match event {
TransportEvent::DaemonShutdown => {
shutdown_state.on_signal(ShutdownSignal::Forceable, connections.len(), *running_turn_count_rx.borrow(), &processor.turn_admission);
@@ -1188,7 +1226,7 @@ pub async fn run_main_with_transport_options(
.send_server_notification(notification)
.await;
}
created = thread_created_rx.recv(), if listen_for_threads => {
created = thread_created_rx.recv(), if listen_for_threads && !ready_to_exit => {
match created {
Ok(thread_id) => {
let mut initialized_connection_ids = Vec::new();
@@ -1219,6 +1257,7 @@ pub async fn run_main_with_transport_options(
}
};
drop(snapshot);
if !shutdown_state.forced() {
futures::future::join_all(connections.iter().map(
|(&connection_id, connection_state)| {
@@ -1238,12 +1277,19 @@ pub async fn run_main_with_transport_options(
shutdown_forced = shutdown_state.forced(),
"processor task exited"
);
if managed_daemon && shutdown_state.forced() {
AppServerExit::Forced
} else {
AppServerExit::Graceful
}
}
});
drop(transport_event_tx);
let _ = processor_handle.await;
if matches!(processor_handle.await, Ok(AppServerExit::Forced)) {
return Ok(AppServerExit::Forced);
}
let _ = outbound_handle.await;
transport_shutdown_token.cancel();
@@ -1252,7 +1298,7 @@ pub async fn run_main_with_transport_options(
let _ = handle.await;
}
Ok(())
Ok(AppServerExit::Graceful)
}
struct SqliteRecoveryNotice {