From 81df6f4af07945113a1e1df2ec1945a638d7d078 Mon Sep 17 00:00:00 2001 From: Conrad Irwin Date: Mon, 31 Aug 2026 15:29:14 +0000 Subject: [PATCH] crashes: Replace user info with generic Sentry tags (#63344) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The crash handler models the crashing user as a fixed `UserInfo` struct of `metrics_id` and `is_staff`. That is a reasonable fit for Zed and a poor extension point in general: reporting any further piece of session state with a crash means changing this crate, and every embedder along with it. The limitation has already produced a workaround in another consumer of this crate. Wanting one field that `UserInfo` has no room for is enough to push an embedder off the IPC channel entirely, onto persisting that state beside the minidump and correlating it back at upload time. That needs an atomic write, a retention window for records whose minidump never uploads, and a cross-check so a stale record cannot be attributed to the wrong crash — none of which the existing socket would have required. This replaces the `UserInfo` message with a generic `SetTags` message carrying one or more updates. Each key is the Sentry submission field the value is uploaded under, so an application can attach its own session state and reach any part of Sentry's event schema without this crate modelling what it means. Updates merge by key, and a `None` value removes one, which is how an application withdraws state from crashes it has not produced yet. A batch is applied while holding the tag-map lock once, so a crash cannot observe part of one logical state change. `set_user_info` keeps its signature and is now shorthand for setting the two identity tags in one batch, so Zed's call site is unchanged. `upload_minidump` loses its two bespoke user blocks in favour of forwarding the map, and keeps its installation-id fallback by checking whether the session ever reported a user. Two consequences worth flagging for review. The first is that this crate now knows it reports to Sentry, where previously it emitted neutral data that `reliability.rs` translated. I think that is honest rather than regrettable — its consumers upload to Sentry, and pretending otherwise is what gave `UserInfo` a shape that fits only one of them. The alternative considered was a well-known-key mapping table in the uploader, which keeps the crate agnostic at the cost of a translation layer that can silently file a value under the wrong namespace. The second is a one-time compatibility loss. A crash is uploaded by the build that starts after it, so an upgrade always reads crash data written by the previous build. Crashes pending across this change carry `user_info` and no `tags`, and will upload without user attribution. They still parse and still upload; only the identity is dropped, for one release. A test covers that. Testing: - New unit test for batch, merge, and removal semantics, driven through `on_message` so it exercises the real wire format. - New unit test that crash data written before `tags` existed still deserializes. - `cargo test -p crashes`, `./script/clippy -p crashes -p zed`, `cargo check -p zed -p remote_server`, `cargo fmt --check`. Release Notes: - N/A --------- Co-authored-by: morgankrey --- crates/crashes/src/crashes.rs | 166 ++++++++++++++++++++++++++++++++-- crates/zed/src/reliability.rs | 22 +---- 2 files changed, 162 insertions(+), 26 deletions(-) diff --git a/crates/crashes/src/crashes.rs b/crates/crashes/src/crashes.rs index b6ca75d5d17..87d6f5c640e 100644 --- a/crates/crashes/src/crashes.rs +++ b/crates/crashes/src/crashes.rs @@ -8,6 +8,7 @@ use std::{panic::Location, pin::Pin}; use system_specs::GpuSpecs; use std::{ + collections::BTreeMap, env, fs::{self, File}, io, panic, @@ -180,7 +181,7 @@ pub struct CrashServer { initialization_params: Mutex>, panic_info: Mutex>, active_gpu: Mutex>, - user_info: Mutex>, + tags: Mutex>, abort_message_location: Mutex>, shutdown: Arc, has_connection: Arc, @@ -199,7 +200,10 @@ pub struct CrashInfo { pub abort_message: Option, pub gpus: Vec, pub active_gpu: Option, - pub user_info: Option, + /// Session state the crashed application attached with [`set_tag`], keyed + /// by Sentry submission field. + #[serde(default)] + pub tags: BTreeMap, } /// Where to find the C runtime's abort diagnostic in the crashed process's @@ -228,7 +232,11 @@ pub struct CrashPanic { pub span: String, } -#[derive(Deserialize, Serialize, Debug, Clone)] +/// The Sentry field identifying the crashing user, which the uploader falls +/// back to filling in itself when a session never reported one. +pub const SENTRY_USER_ID: &str = "sentry[user][id]"; + +#[derive(Debug, Clone)] pub struct UserInfo { pub metrics_id: Option, pub is_staff: Option, @@ -253,7 +261,45 @@ pub fn set_gpu_info(crash_client: &Arc, specs: GpuSpecs) { } pub fn set_user_info(crash_client: &Arc, info: UserInfo) { - send_crash_server_message(crash_client, CrashServerMessage::UserInfo(info)); + set_tags( + crash_client, + [ + (SENTRY_USER_ID, info.metrics_id), + ( + "sentry[user][is_staff]", + info.is_staff.map(|is_staff| is_staff.to_string()), + ), + ], + ); +} + +/// Attaches a value to every crash this session produces from now on, or clears +/// it when `value` is `None`. A later call with the same key replaces the +/// earlier value, so independent callers can each track state that changes +/// during a session without coordinating. +/// +/// `key` is the Sentry submission field to upload the value under, such as +/// `sentry[user][username]` or any name under `sentry[tags]`, which is why the +/// value reaches Sentry without the crash handler modelling what it means. +pub fn set_tag(crash_client: &Arc, key: impl Into, value: Option) { + set_tags(crash_client, [(key, value)]); +} + +/// Applies several tag updates as one crash-handler message, so a crash cannot +/// observe part of a logical state change. +pub fn set_tags(crash_client: &Arc, tags: impl IntoIterator)>) +where + K: Into, +{ + let tags = tags + .into_iter() + .map(|(key, value)| (key.into(), value)) + .collect::>(); + debug_assert!( + tags.iter().all(|(key, _)| key.starts_with("sentry[")), + "crash tag keys must be Sentry submission fields" + ); + send_crash_server_message(crash_client, CrashServerMessage::SetTags(tags)); } /// Requests an orderly exit from the crash-handler sidecar. @@ -266,7 +312,7 @@ enum CrashServerMessage { Init(InitCrashHandler), Panic(CrashPanic), GPUInfo(GpuSpecs), - UserInfo(UserInfo), + SetTags(Vec<(String, Option)>), AbortMessageLocation(AbortMessageLocation), Shutdown, } @@ -439,7 +485,7 @@ impl minidumper::ServerHandler for CrashServer { abort_message, active_gpu: self.active_gpu.lock().clone(), gpus, - user_info: self.user_info.lock().clone(), + tags: self.tags.lock().clone(), }; let crash_data_path = self @@ -465,8 +511,18 @@ impl minidumper::ServerHandler for CrashServer { CrashServerMessage::GPUInfo(gpu_specs) => { self.active_gpu.lock().replace(gpu_specs); } - CrashServerMessage::UserInfo(user_info) => { - self.user_info.lock().replace(user_info); + CrashServerMessage::SetTags(updates) => { + let mut tags = self.tags.lock(); + for (key, value) in updates { + match value { + Some(value) => { + tags.insert(key, value); + } + None => { + tags.remove(&key); + } + } + } } CrashServerMessage::AbortMessageLocation(location) => { self.abort_message_location.lock().replace(location); @@ -673,7 +729,7 @@ pub fn crash_server(socket: &Path, logs_dir: PathBuf) { Box::new(CrashServer { initialization_params: Mutex::default(), panic_info: Mutex::default(), - user_info: Mutex::default(), + tags: Mutex::default(), abort_message_location: Mutex::default(), shutdown: shutdown.clone(), has_connection, @@ -690,6 +746,75 @@ pub fn crash_server(socket: &Path, logs_dir: PathBuf) { mod tests { use super::*; + /// Clearing a tag has to remove it rather than record an empty value, + /// because that is how an application withdraws identifying state from + /// crashes it has not produced yet. + #[test] + fn setting_tags_updates_and_removes_values() { + let server = test_crash_server(); + + server.receive(CrashServerMessage::SetTags(vec![ + (SENTRY_USER_ID.to_string(), Some("metrics-1".to_string())), + ( + "sentry[user][is_staff]".to_string(), + Some("true".to_string()), + ), + ( + "sentry[tags][custom]".to_string(), + Some("first".to_string()), + ), + ( + "sentry[tags][custom]".to_string(), + Some("second".to_string()), + ), + ])); + assert_eq!( + server.tags.lock().clone(), + BTreeMap::from([ + (SENTRY_USER_ID.to_string(), "metrics-1".to_string()), + ("sentry[user][is_staff]".to_string(), "true".to_string()), + ("sentry[tags][custom]".to_string(), "second".to_string()), + ]) + ); + + server.receive(CrashServerMessage::SetTags(vec![ + (SENTRY_USER_ID.to_string(), None), + ("sentry[user][is_staff]".to_string(), None), + ])); + assert_eq!( + server.tags.lock().clone(), + BTreeMap::from([("sentry[tags][custom]".to_string(), "second".to_string())]) + ); + } + + /// A crash is reported by the build that starts next, so an upgrade always + /// reads crash data written by the previous build. Tags were introduced + /// after `user_info`, and dropping a stale identity is acceptable, but + /// failing to parse would discard the whole crash. + #[test] + fn crash_info_written_before_tags_existed_still_parses() { + let crash_info: CrashInfo = serde_json::from_str( + r#"{ + "init": { + "session_id": "session-1", + "zed_version": "1.2.3", + "binary": "zed", + "release_channel": "stable", + "commit_sha": "abc123" + }, + "panic": null, + "minidump_error": null, + "gpus": [], + "active_gpu": null, + "user_info": { "metrics_id": "metrics-1", "is_staff": true } + }"#, + ) + .expect("crash data from an older build must still parse"); + + assert_eq!(crash_info.init.session_id, "session-1"); + assert!(crash_info.tags.is_empty()); + } + #[test] fn abort_message_read_len_requires_page_rounded_total() { assert_eq!(abort_message_read_len(0), None); @@ -780,4 +905,27 @@ mod tests { libc::munmap(mapping, 2 * page_size); } } + + impl CrashServer { + fn receive(&self, message: CrashServerMessage) { + use minidumper::ServerHandler as _; + + let message = + serde_json::to_vec(&message).expect("failed to serialize a crash server message"); + self.on_message(0, message); + } + } + + fn test_crash_server() -> CrashServer { + CrashServer { + initialization_params: Mutex::default(), + panic_info: Mutex::default(), + active_gpu: Mutex::default(), + tags: Mutex::default(), + abort_message_location: Mutex::default(), + shutdown: Arc::default(), + has_connection: Arc::default(), + logs_dir: PathBuf::new(), + } + } } diff --git a/crates/zed/src/reliability.rs b/crates/zed/src/reliability.rs index 3ad758f0ae2..87ca151fd39 100644 --- a/crates/zed/src/reliability.rs +++ b/crates/zed/src/reliability.rs @@ -321,25 +321,13 @@ async fn upload_minidump( .text("sentry[contexts][abort][message]", abort_message.clone()); } - if let Some(is_staff) = &metadata - .user_info - .as_ref() - .and_then(|user_info| user_info.is_staff) - { - form = form.text( - "sentry[user][is_staff]", - if *is_staff { "true" } else { "false" }, - ); + for (key, value) in &metadata.tags { + form = form.text(key.clone(), value.clone()); } - - if let Some(metrics_id) = metadata - .user_info - .as_ref() - .and_then(|user_info| user_info.metrics_id.as_ref()) + if !metadata.tags.contains_key(crashes::SENTRY_USER_ID) + && let Some(id) = client.telemetry().installation_id() { - form = form.text("sentry[user][id]", metrics_id.clone()); - } else if let Some(id) = client.telemetry().installation_id() { - form = form.text("sentry[user][id]", format!("installation-{}", id)) + form = form.text(crashes::SENTRY_USER_ID, format!("installation-{}", id)) } ::telemetry::event!(