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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,12 @@ stable error code and a user-facing message:
}
```

A panic inside a request does not cross the C ABI, where it would abort the
host process. The dispatcher catches it and returns `unknown` with details
`request_panicked` and the message `Core request failed unexpectedly`. Core
records the panic as `app.core.panic_interrupted`, with the request's method
and op, before it returns, so the host does not log the panic again.

## Commands

The MCP configuration and library commands were removed with the agent-facing MCP
Expand Down
14 changes: 13 additions & 1 deletion rust/crates/core/src/runtime/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,19 @@ fn execute(request: &str, document: Option<&str>) -> CoreResponse {
};
// The trace spans every scope below and records once, after the final response.
let trace = crate::runtime::request_trace::Request::begin(&parsed);
let response = execute_parsed(parsed, document);
let id = parsed.id.clone();
let method = parsed.command.clone();
// A panic here would otherwise unwind into the host and abort it; the
// boundary has already recorded it as app.core.panic_interrupted.
let response =
crate::runtime::panic_facts::request_boundary(&method, || execute_parsed(parsed, document))
.unwrap_or_else(|| {
CoreResponse::failure(
id,
CoreError::new(ErrorCode::Unknown, "Core request failed unexpectedly")
.with_details("request_panicked"),
)
});
trace.finish(&response);
response
}
Expand Down
4 changes: 3 additions & 1 deletion rust/crates/core/src/runtime/helper_failures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ use std::sync::Once;
static INSTALL: Once = Once::new();

/// Every Core command and direct IDE/AskPass entry calls this before invoking
/// helpers or starting workers. Subsequent calls are cheap.
/// helpers or starting workers. Subsequent calls are cheap. The panic hook is
/// installed here too, because these are the entries that run Core code.
pub(crate) fn install() {
INSTALL.call_once(|| {
super::panic_facts::install();
lithe_git_host::failure_log::install_failure_sink(sink);
lithe_ide_host::failure_log::install_failure_sink(sink);
lithe_remote::failure_log::install_failure_sink(sink);
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
mod dispatcher;
mod ffi;
pub(crate) mod helper_failures;
pub(crate) mod panic_facts;
pub(crate) mod request_trace;

pub(crate) use dispatcher::execute_json;
192 changes: 192 additions & 0 deletions rust/crates/core/src/runtime/panic_facts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
//! Records every Core panic as a catalog fact, and keeps a panic inside a
//! request from unwinding into the host.
//!
//! Core runs inside the host process. A panic that reaches the C ABI aborts
//! that process before the host's log writer drains any queued fact, so the
//! dispatcher runs each request inside [`request_boundary`], which turns a
//! panic into a failed response. Threads Core starts keep the standard
//! behavior: the panic unwinds that thread and its owner decides what happens
//! next. In both cases the hook installed here records one
//! `app.core.panic_interrupted` fact before unwinding starts, then runs the
//! hook that was installed before it, so the standard stderr report remains.

use lithe_diagnostics::core_events;
use serde_json::{json, Value};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::panic::{AssertUnwindSafe, PanicHookInfo};
use std::sync::Once;

const EVENT: &str = "app.core.panic_interrupted";
static INSTALL: Once = Once::new();

thread_local! {
/// Method of the request this thread runs inside [`request_boundary`].
static REQUEST: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Installs the recording hook once per process, in front of the hook that
/// was installed before it. Later calls are cheap.
pub(crate) fn install() {
INSTALL.call_once(|| {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
record(info);
previous(info);
}));
});
}

/// Runs one request so that a panic inside it returns `None` to the
/// dispatcher instead of unwinding across the C ABI.
pub(crate) fn request_boundary<T>(method: &str, run: impl FnOnce() -> T) -> Option<T> {
let enclosing = REQUEST.with(|request| request.replace(Some(method.to_owned())));
// Asserting unwind safety is sound here: the closure's captures are
// consumed by the panicking request and never observed afterwards. State
// shared with later requests sits behind locks; one the panic poisoned
// either recovers or fails the next request the same way, and that panic
// is caught and recorded too.
let result = std::panic::catch_unwind(AssertUnwindSafe(run));
REQUEST.with(|request| request.replace(enclosing));
result.ok()
}

/// Runs inside the panic hook, so it must neither wait for a lock the
/// panicking thread may hold nor panic: a second panic aborts the process.
fn record(info: &PanicHookInfo<'_>) {
let op = lithe_request_context::trace::try_current().and_then(|context| context.op);
core_events::record_without_waiting(EVENT, fields(info, current_method()), op);
}

fn current_method() -> Option<String> {
REQUEST
.try_with(|request| request.try_borrow().ok().and_then(|method| method.clone()))
.ok()
.flatten()
}

fn fields(info: &PanicHookInfo<'_>, method: Option<String>) -> BTreeMap<String, Value> {
let payload = info.payload();
let message = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("Panic payload is not text");
let boundary = if method.is_some() {
"request"
} else {
"thread"
};
let mut fields = BTreeMap::from([
("boundary".to_string(), json!(boundary)),
("panic".to_string(), json!(message)),
]);
if let Some(location) = info.location() {
fields.insert(
"location".into(),
json!(format!(
"{}:{}:{}",
location.file(),
location.line(),
location.column()
)),
);
}
if let Some(method) = method.as_deref().and_then(super::request_trace::token) {
fields.insert("method".into(), json!(method));
}
fields
}

#[cfg(test)]
mod tests {
use super::*;
use lithe_diagnostics::core_events::{capture, CoreEvent};

fn panic_facts(events: Vec<CoreEvent>) -> Vec<CoreEvent> {
events
.into_iter()
.filter(|event| event.event == EVENT)
.collect()
}

#[test]
fn a_panicking_request_is_recorded_and_returns_none() {
install();
let (result, events) = capture::run(false, || {
request_boundary("git.write", || -> i32 { panic!("request broke") })
});
assert!(result.is_none());
let facts = panic_facts(events);
assert_eq!(facts.len(), 1);
let fact = &facts[0];
assert_eq!(fact.channel, "app");
assert_eq!(fact.fields["boundary"], json!("request"));
assert_eq!(fact.fields["method"], json!("git.write"));
assert_eq!(fact.fields["panic"], json!("request broke"));
assert!(fact.fields["location"]
.as_str()
.unwrap()
.contains("panic_facts.rs:"));
assert_eq!(current_method(), None);
}

#[test]
fn a_request_that_returns_keeps_its_value_and_records_nothing() {
install();
let (result, events) = capture::run(false, || request_boundary("git.write", || 7));
assert_eq!(result, Some(7));
assert!(panic_facts(events).is_empty());
}

#[test]
fn a_panic_outside_a_request_is_recorded_as_thread() {
install();
let (result, events) = capture::run(false, || {
std::panic::catch_unwind(|| panic!("{} broke", String::from("worker")))
});
assert!(result.is_err());
let facts = panic_facts(events);
assert_eq!(facts.len(), 1);
assert_eq!(facts[0].fields["boundary"], json!("thread"));
assert_eq!(facts[0].fields["panic"], json!("worker broke"));
assert!(!facts[0].fields.contains_key("method"));
}

#[test]
fn a_panic_payload_that_is_not_text_gets_a_fixed_message() {
install();
let (_, events) = capture::run(false, || {
std::panic::catch_unwind(|| std::panic::panic_any(42_u8))
});
let facts = panic_facts(events);
assert_eq!(facts.len(), 1);
assert_eq!(facts[0].fields["panic"], json!("Panic payload is not text"));
}

#[test]
fn nested_requests_restore_the_enclosing_method() {
install();
let (_, events) = capture::run(false, || {
request_boundary("workspace.repositories", || {
assert!(request_boundary("git.write", || panic!("inner")).is_none());
assert_eq!(current_method().as_deref(), Some("workspace.repositories"));
})
});
let facts = panic_facts(events);
assert_eq!(facts.len(), 1);
assert_eq!(facts[0].fields["method"], json!("git.write"));
assert_eq!(current_method(), None);
}

#[test]
fn a_method_that_is_not_a_token_is_left_out() {
install();
let (_, events) = capture::run(false, || {
request_boundary("not a token", || panic!("odd method"))
});
let facts = panic_facts(events);
assert_eq!(facts[0].fields["boundary"], json!("request"));
assert!(!facts[0].fields.contains_key("method"));
}
}
2 changes: 1 addition & 1 deletion rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ fn request_path(payload: &Value) -> Option<String> {
}

/// Catalog token shape; anything else is omitted rather than failing the record.
fn token(value: &str) -> Option<String> {
pub(crate) fn token(value: &str) -> Option<String> {
(!value.is_empty()
&& value.len() <= 64
&& value
Expand Down
80 changes: 80 additions & 0 deletions rust/crates/diagnostics/src/catalog_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ pub static EVENTS: &[EventMetadata] = &[
rate: 60,
owner: "lithe-core",
},
EventMetadata {
id: "app.core.panic_interrupted",
channel: "app",
level: LogLevel::Error,
message: "Core code panicked at the {boundary} boundary",
fields: &[
FieldMetadata { name: "boundary", field_type: FieldType::Token, required: true, description: "Where the panic ends: request when the dispatcher turned it into a failed response and Core kept running, thread when it unwinds a Core thread whose owner decides what happens next", reason: None },
FieldMetadata { name: "location", field_type: FieldType::Text, required: false, description: "Source file, line and column the compiler attached to the panic", reason: Some("The compiler reports the panic site as a source path with line and column; dependency paths can be absolute, so Core redacts the text and caps it at 1 KiB instead of treating it as a stable identifier") },
FieldMetadata { name: "method", field_type: FieldType::Token, required: false, description: "Core protocol method the request was running when boundary is request, e.g. git.write", reason: None },
FieldMetadata { name: "panic", field_type: FieldType::Text, required: true, description: "Panic message from the Rust payload, or a fixed note when the payload is not text", reason: Some("A Rust panic message is free text written at the panic site, often with the Debug output of an error, and has no stable code; keep its wording after Core redaction and the 1 KiB cap") },
],
span: None,
rate: 60,
owner: "lithe-core",
},
EventMetadata {
id: "app.core.request.failed",
channel: "app/core",
Expand Down Expand Up @@ -205,6 +220,20 @@ pub static EVENTS: &[EventMetadata] = &[
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.runtime.panic_interrupted",
channel: "app",
level: LogLevel::Error,
message: "Recovered a panic at {boundary}",
fields: &[
FieldMetadata { name: "boundary", field_type: FieldType::Token, required: true, description: "Recover site: viva: followed by the UI framework boundary such as viva:darwin:appkit-callback, or core:events-observer and core:log-waker for Core callbacks", reason: None },
FieldMetadata { name: "panic", field_type: FieldType::Text, required: true, description: "Panic value as text, as the recovering boundary received it", reason: Some("A recovered Go panic value is arbitrary text with no stable code; keep its wording so the failing check can be found, after Core redaction and the 1 KiB cap") },
FieldMetadata { name: "stack", field_type: FieldType::Text, required: false, description: "Frames of the panicking goroutine from the panic call outward, joined on one line", reason: Some("A Go stack trace has no structured equivalent; the host keeps only the frames after the panic call as function file:line pairs with base file names, and Core redacts and caps the text at 1 KiB") },
],
span: None,
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.search.directory_skipped",
channel: "app",
Expand All @@ -218,6 +247,45 @@ pub static EVENTS: &[EventMetadata] = &[
rate: 60,
owner: "lithe-core",
},
EventMetadata {
id: "app.session.close_missing",
channel: "app",
level: LogLevel::Warn,
message: "Previous session ended without closing its log",
fields: &[
FieldMetadata { name: "session", field_type: FieldType::Path, required: true, description: "Log directory of the session that was killed, force quit or stopped by a native crash before closing its log", reason: None },
],
span: None,
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.session.crash_capture_failed",
channel: "app",
level: LogLevel::Warn,
message: "Crash capture failed at {stage}",
fields: &[
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Filesystem or runtime error of that step", reason: None },
FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Step that failed: create when this session's crash file could not be made, so a fatal crash of this session is not recorded; claim when a previous session's crash file could not be read or removed; release when Close could not remove this session's file, so the next start reports this session as not closed", reason: None },
],
span: None,
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.session.previous_interrupted",
channel: "app",
level: LogLevel::Error,
message: "Previous session ended in a crash",
fields: &[
FieldMetadata { name: "panic", field_type: FieldType::Text, required: true, description: "First line the Go runtime printed when the process died, such as panic: or fatal error:", reason: Some("The Go runtime prints the cause of a fatal crash only as text in its crash output; keep the first line after Core redaction and the 1 KiB cap") },
FieldMetadata { name: "session", field_type: FieldType::Path, required: true, description: "Log directory of the session that crashed, so its last records can be read next to this one", reason: None },
FieldMetadata { name: "stack", field_type: FieldType::Text, required: false, description: "Frames of the goroutine that crashed, from its panic call outward, joined on one line", reason: Some("A Go stack trace has no structured equivalent; the host keeps only the frames after the panic call as function file:line pairs with base file names, and Core redacts and caps the text at 1 KiB") },
],
span: None,
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.session.started",
channel: "app",
Expand Down Expand Up @@ -329,6 +397,18 @@ pub static EVENTS: &[EventMetadata] = &[
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.window.loop_failed",
channel: "app",
level: LogLevel::Error,
message: "Window loop stopped with an error",
fields: &[
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Error the UI framework returned when its window loop ended for a reason other than a recovered panic", reason: None },
],
span: None,
rate: 60,
owner: "Lithe",
},
EventMetadata {
id: "app.workspace.directory_skipped",
channel: "app",
Expand Down
Loading
Loading