Skip to content

Commit 56ffa82

Browse files
committed
Bug 2077139 - Terminate active flows when session ends
1 parent 1d3fa7a commit 56ffa82

2 files changed

Lines changed: 226 additions & 3 deletions

File tree

‎glean-core/src/core/mod.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use crate::database::Database;
2121
use crate::debug::DebugOptions;
2222
use crate::error::ClientIdFileError;
2323
use crate::event_database::EventDatabase;
24-
use crate::flows::{FlowRegistry, FlowState};
24+
use crate::flows::{self, FlowRegistry, FlowState};
2525
use crate::internal_metrics::{
2626
AdditionalMetrics, CoreMetrics, DatabaseMetrics, ExceptionState, HealthMetrics,
2727
};
@@ -1695,6 +1695,8 @@ impl Glean {
16951695
self.session_manager.sampled_in = sampled_in;
16961696
self.session_manager.state = SessionState::Active;
16971697
self.session_manager.inactive_since = None;
1698+
// Flow instances never span sessions, and `flow_seq` restarts at 0.
1699+
*self.flow_state.lock().unwrap() = FlowState::default();
16981700

16991701
// 4. Persist to storage.
17001702
session::store_session_seq(self, new_seq);
@@ -1718,6 +1720,12 @@ impl Glean {
17181720
}
17191721

17201722
let session_id = self.session_manager.session_id?;
1723+
1724+
// Close every active flow instance first, while this session is still
1725+
// current, so each `glean.flow_end` is recorded in-session and takes a
1726+
// `session.event_seq` from the session that owns the instance.
1727+
flows::close_all_at_session_end(self);
1728+
17211729
let seq = self.session_manager.session_seq;
17221730
let event_seq = self.session_manager.event_seq.load(Ordering::Relaxed);
17231731
let sample_rate = self.session_manager.sample_rate;

‎glean-core/src/flows/mod.rs‎

Lines changed: 217 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,8 @@ impl FlowState {
211211
}
212212

213213
/// Why a flow instance ended, as reported in `glean.flow_end`.
214-
// TODO(bugs 2077139, 2077141, 2077143): the session-end, timeout, and
215-
// persistence bugs construct the remaining reasons.
214+
// TODO(bugs 2077141, 2077143): the timeout and persistence bugs construct the
215+
// remaining reasons.
216216
#[allow(dead_code)]
217217
#[derive(Debug, Clone, Copy)]
218218
pub(crate) enum FlowEndReason<'a> {
@@ -330,6 +330,28 @@ pub(crate) fn close_instances(
330330
submitted
331331
}
332332

333+
/// Closes every active instance with `reason: session_end`, in reverse order of
334+
/// opening.
335+
///
336+
/// Must be called while the ending session is still current, before its state
337+
/// is torn down and `glean.session_end` is recorded.
338+
pub(crate) fn close_all_at_session_end(glean: &Glean) {
339+
let mut closed: Vec<(FlowId, u64)> = {
340+
let mut state = glean.flow_state.lock().unwrap();
341+
std::mem::take(&mut state.active).into_iter().collect()
342+
};
343+
// `flow_seq` is assigned in order of opening.
344+
closed.sort_by_key(|a| std::cmp::Reverse(a.1));
345+
for (flow, seq) in closed {
346+
record_flow_end(
347+
glean,
348+
&glean.flow_registry.flow(flow).name,
349+
seq,
350+
FlowEndReason::SessionEnd,
351+
);
352+
}
353+
}
354+
333355
/// Records a `glean.flow_end` event.
334356
///
335357
/// Like `glean.session_end`, this bypasses `EventMetric` and records directly,
@@ -1020,4 +1042,197 @@ mod test {
10201042
"the ping submitted by flow_end must be reported by the exit event's recording"
10211043
);
10221044
}
1045+
1046+
// -----------------------------------------------------------------------
1047+
// Session end
1048+
// -----------------------------------------------------------------------
1049+
1050+
fn two_flows() -> Vec<FlowDefinition> {
1051+
vec![
1052+
definition(
1053+
"alpha",
1054+
&[
1055+
("alpha.started", FlowRole::Start),
1056+
("alpha.finished", FlowRole::End),
1057+
("app.card_shown", FlowRole::Member),
1058+
],
1059+
),
1060+
definition(
1061+
"zeta",
1062+
&[
1063+
("zeta.started", FlowRole::Start),
1064+
("zeta.finished", FlowRole::End),
1065+
],
1066+
),
1067+
]
1068+
}
1069+
1070+
fn session_end_extras(flow: &str, seq: u64) -> HashMap<String, String> {
1071+
[
1072+
("flow_name", flow.to_string()),
1073+
("flow_seq", seq.to_string()),
1074+
("reason", "session_end".to_string()),
1075+
]
1076+
.into_iter()
1077+
.map(|(k, v)| (k.to_string(), v))
1078+
.collect()
1079+
}
1080+
1081+
/// Returns `(category.name, session.session_id, session.event_seq)` for each
1082+
/// event in the events store, in ping order.
1083+
fn ping_order(glean: &Glean) -> Vec<(String, Option<String>, Option<u64>)> {
1084+
glean
1085+
.event_storage()
1086+
.snapshot_as_json(glean, "events", false)
1087+
.unwrap()
1088+
.as_array()
1089+
.unwrap()
1090+
.iter()
1091+
.map(|e| {
1092+
(
1093+
format!(
1094+
"{}.{}",
1095+
e["category"].as_str().unwrap(),
1096+
e["name"].as_str().unwrap()
1097+
),
1098+
e["session"]["session_id"].as_str().map(str::to_string),
1099+
e["session"]["event_seq"].as_u64(),
1100+
)
1101+
})
1102+
.collect()
1103+
}
1104+
1105+
fn record_now(glean: &Glean, category: &str, name: &str) {
1106+
event(category, name, true).record_sync(
1107+
glean,
1108+
crate::get_timestamp_ms(),
1109+
HashMap::new(),
1110+
0,
1111+
);
1112+
}
1113+
1114+
#[test]
1115+
fn session_end_closes_instances_in_reverse_order_of_opening_before_session_end() {
1116+
let (mut glean, _t) = glean_with_flows(two_flows());
1117+
glean.session_start();
1118+
let session_id = glean.session_manager().session_id().unwrap().to_string();
1119+
1120+
// zeta opens first (seq 0), alpha second (seq 1).
1121+
record_now(&glean, "zeta", "started");
1122+
record_now(&glean, "alpha", "started");
1123+
record_now(&glean, "app", "card_shown");
1124+
glean.session_end(None);
1125+
1126+
let id = Some(session_id);
1127+
assert_eq!(
1128+
vec![
1129+
("glean.session_start".to_string(), None, None),
1130+
("zeta.started".to_string(), id.clone(), Some(0)),
1131+
("alpha.started".to_string(), id.clone(), Some(1)),
1132+
("app.card_shown".to_string(), id.clone(), Some(2)),
1133+
("glean.flow_end".to_string(), id.clone(), Some(3)),
1134+
("glean.flow_end".to_string(), id, Some(4)),
1135+
("glean.session_end".to_string(), None, None),
1136+
],
1137+
ping_order(&glean)
1138+
);
1139+
assert_eq!(
1140+
vec![
1141+
session_end_extras("alpha", 1),
1142+
session_end_extras("zeta", 0)
1143+
],
1144+
flow_ends(&glean)
1145+
);
1146+
assert!(glean.flow_state.lock().unwrap().active.is_empty());
1147+
}
1148+
1149+
#[test]
1150+
fn replaced_session_closes_instances_in_the_old_session() {
1151+
let (mut glean, _t) = glean_with_flows(two_flows());
1152+
glean.session_start();
1153+
let old_session = glean.session_manager().session_id().unwrap().to_string();
1154+
record_now(&glean, "alpha", "started");
1155+
1156+
glean.session_start();
1157+
1158+
let flow_end = flow_end_metric()
1159+
.get_value(&glean, "events")
1160+
.unwrap()
1161+
.pop()
1162+
.unwrap();
1163+
assert_eq!(Some(session_end_extras("alpha", 0)), flow_end.extra);
1164+
assert_eq!(
1165+
old_session,
1166+
flow_end.session.expect("flow_end is in-session").session_id
1167+
);
1168+
assert!(glean.flow_state.lock().unwrap().active.is_empty());
1169+
}
1170+
1171+
#[test]
1172+
fn auto_mode_timeout_closes_instances_in_the_timed_out_session() {
1173+
let dir = tempfile::tempdir().unwrap();
1174+
let mut cfg = test_cfg(&dir, two_flows());
1175+
cfg.session_mode = SessionMode::Auto;
1176+
cfg.session_inactivity_timeout_ms = 1;
1177+
let mut glean = Glean::new(cfg).unwrap();
1178+
1179+
glean.handle_client_active();
1180+
let old_session = glean.session_manager().session_id().unwrap().to_string();
1181+
record_now(&glean, "alpha", "started");
1182+
glean.handle_client_inactive();
1183+
std::thread::sleep(std::time::Duration::from_millis(5));
1184+
1185+
// The timeout is noticed here, ending the old session and starting a new one.
1186+
glean.handle_client_active();
1187+
assert_ne!(
1188+
old_session,
1189+
glean.session_manager().session_id().unwrap().to_string()
1190+
);
1191+
1192+
let flow_end = flow_end_metric()
1193+
.get_value(&glean, "events")
1194+
.expect("flow_end should be recorded when the timeout is noticed")
1195+
.pop()
1196+
.unwrap();
1197+
assert_eq!(Some(session_end_extras("alpha", 0)), flow_end.extra);
1198+
assert_eq!(
1199+
old_session,
1200+
flow_end.session.expect("flow_end is in-session").session_id
1201+
);
1202+
}
1203+
1204+
#[test]
1205+
fn flow_seq_restarts_at_zero_in_each_session() {
1206+
let (mut glean, _t) = glean_with_flows(two_flows());
1207+
1208+
glean.session_start();
1209+
record_now(&glean, "alpha", "started");
1210+
record_now(&glean, "alpha", "finished");
1211+
record_now(&glean, "zeta", "started");
1212+
glean.session_end(None);
1213+
1214+
glean.session_start();
1215+
record_now(&glean, "alpha", "started");
1216+
1217+
let starts = event("alpha", "started", true)
1218+
.get_value(&glean, "events")
1219+
.unwrap();
1220+
assert_eq!(vec![entry("alpha", 0)], starts[0].flows);
1221+
assert_eq!(vec![entry("alpha", 0)], starts[1].flows);
1222+
}
1223+
1224+
#[test]
1225+
fn session_end_with_no_active_instances_records_no_flow_end() {
1226+
let (mut glean, _t) = glean_with_flows(two_flows());
1227+
glean.session_start();
1228+
record_now(&glean, "alpha", "started");
1229+
record_now(&glean, "alpha", "finished");
1230+
glean.session_end(None);
1231+
1232+
// Only the exit's flow_end, none at session end.
1233+
assert_eq!(
1234+
vec![exit_extras("alpha", 0, "alpha.finished")],
1235+
flow_ends(&glean)
1236+
);
1237+
}
10231238
}

0 commit comments

Comments
 (0)