Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): keep a session's last use on its lifecycle record (#6773)

injaneity94e3d1862624
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index 8f8a6f202f..f6896717a6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -334,12 +334,6 @@ static SESSION_CLEANUP_PROGRESS: OnceLock<Mutex<HashMap<String, SessionCleanupPr
static SESSION_REVIVE_HOOKS: OnceLock<Mutex<HashMap<u64, SessionReviveHook>>> = OnceLock::new();
static NEXT_SESSION_REVIVE_HOOK_ID: AtomicU64 = AtomicU64::new(1);
-/// Last-activity timestamp per live lifecycle session. Only an admitted,
-/// session-requiring call that reaches dispatch refreshes this timestamp.
-/// Transport close remains an immediate cleanup path; idle eviction is the
-/// crash and inactivity fallback. `"default"` and empty ids are never tracked.
-static SESSION_ACTIVITY: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
-
#[derive(Debug, Clone)]
struct LifecycleRecord {
public_label: Option<String>,
@@ -348,6 +342,11 @@ struct LifecycleRecord {
transport: SessionTransport,
client_kind: SessionClientKind,
started_at: Instant,
+ /// Last use. Admission, declaration and dispatch completion stamp it
+ /// with `Instant::now()` while holding the records lock, so stamps only
+ /// move forward and the idle sweep reads it with `in_flight` in one
+ /// critical section.
+ last_activity: Instant,
/// Trusted host override. Ordinary sessions use the runtime sweep's
/// default TTL so tests and process-level configuration can still supply
/// that fallback.
@@ -393,16 +392,13 @@ impl Drop for SessionDispatchGuard {
return;
};
record.in_flight = record.in_flight.saturating_sub(1);
- activity()
- .lock()
- .unwrap()
- .insert(self.session_id.clone(), Instant::now());
+ record.last_activity = Instant::now();
(record.in_flight == 0)
.then(|| record.pending_end.take())
.flatten()
};
if let Some(reason) = pending {
- finish_session_end(&self.session_id, reason);
+ finish_session_end(&self.session_id, reason, None);
}
}
}
@@ -500,6 +496,7 @@ fn begin_session_dispatch_inner(
transport,
client_kind,
started_at: now,
+ last_activity: Instant::now(),
idle_ttl,
in_flight: 0,
pending_end: None,
@@ -514,16 +511,13 @@ fn begin_session_dispatch_inner(
record.idle_ttl = idle_ttl;
}
record.in_flight += 1;
+ record.last_activity = Instant::now();
if recreated {
ended.remove(session_id);
idle_ended.remove(session_id);
}
recreated
};
- activity()
- .lock()
- .unwrap()
- .insert(session_id.to_owned(), now);
if recreated {
// Platform overlays keep their own late-command tombstones; clear
// them exactly as an explicit start_session revival would.
@@ -598,6 +592,7 @@ fn activate_session_inner(
if idle_ttl.is_some() {
record.idle_ttl = idle_ttl;
}
+ record.last_activity = Instant::now();
} else {
records.insert(
session_id.to_owned(),
@@ -608,6 +603,7 @@ fn activate_session_inner(
transport,
client_kind,
started_at: now,
+ last_activity: Instant::now(),
idle_ttl,
in_flight: 0,
pending_end: None,
@@ -615,10 +611,6 @@ fn activate_session_inner(
);
}
}
- activity()
- .lock()
- .unwrap()
- .insert(session_id.to_owned(), now);
Ok(())
}
@@ -685,6 +677,7 @@ pub fn activate_or_revive_session_for_owner(
if idle_ttl.is_some() {
record.idle_ttl = idle_ttl;
}
+ record.last_activity = Instant::now();
} else {
records.insert(
session_id.to_owned(),
@@ -695,6 +688,7 @@ pub fn activate_or_revive_session_for_owner(
transport,
client_kind,
started_at: now,
+ last_activity: Instant::now(),
idle_ttl,
in_flight: 0,
pending_end: None,
@@ -707,10 +701,6 @@ pub fn activate_or_revive_session_for_owner(
}
revived
};
- activity()
- .lock()
- .unwrap()
- .insert(session_id.to_owned(), now);
Ok(revived)
}
@@ -723,7 +713,7 @@ pub fn session_snapshot(
if record.owner_transport != owner_transport {
return None;
}
- let idle = session_idle_duration(session_id).unwrap_or_default();
+ let idle = record.last_activity.elapsed();
let ttl = record.idle_ttl.unwrap_or(ttl);
Some(LifecycleSessionSnapshot {
runtime_id: session_id.to_owned(),
@@ -825,7 +815,7 @@ pub fn list_session_snapshots_with_prefix(
records
.into_iter()
.map(|(_, runtime_id, record)| {
- let idle = session_idle_duration(&runtime_id).unwrap_or_default();
+ let idle = record.last_activity.elapsed();
let idle_ttl = record.idle_ttl.unwrap_or(ttl);
LifecycleSessionSnapshot {
runtime_id,
@@ -859,10 +849,6 @@ pub fn end_sessions_for_owner(owner_transport: &str, reason: SessionEndReason) -
ids.len()
}
-fn activity() -> &'static Mutex<HashMap<String, Instant>> {
- SESSION_ACTIVITY.get_or_init(|| Mutex::new(HashMap::new()))
-}
-
/// Whether `id` is a real, trackable session id (not the anonymous fallback).
fn is_trackable(id: &str) -> bool {
!id.is_empty() && id != "default"
@@ -1239,11 +1225,6 @@ pub fn release_process_state_for_shutdown() {
progress.clear();
progress.shrink_to_fit();
}
- if let Some(activity) = SESSION_ACTIVITY.get() {
- let mut activity = activity.lock().unwrap();
- activity.clear();
- activity.shrink_to_fit();
- }
if let Some(records) = LIFECYCLE_RECORDS.get() {
let mut records = records.lock().unwrap();
records.clear();
@@ -1279,13 +1260,16 @@ pub fn fire_session_end(session_id: &str) -> bool {
}
fn fire_session_end_for_owner(session_id: &str, owner_transport: Option<&str>) -> bool {
- let transition = mark_session_ended(session_id, owner_transport, SessionEndReason::Unknown);
+ let transition =
+ mark_session_ended(session_id, owner_transport, SessionEndReason::Unknown, None);
let _ = retry_session_cleanup(session_id);
transition == EndTransition::First
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EndTransition {
+ /// The idle sweep's candidate was used, or ended, after it was picked.
+ StillLive,
/// The episode's first end.
First,
/// A terminal end of a session the idle sweep had left dormant.
@@ -1305,10 +1289,19 @@ fn mark_session_ended(
session_id: &str,
owner_transport: Option<&str>,
reason: SessionEndReason,
+ idle: Option<IdleCheck>,
) -> EndTransition {
- activity().lock().unwrap().remove(session_id);
let mut ended = ended_sessions().lock().unwrap();
- let record = lifecycle_records().lock().unwrap().remove(session_id);
+ let record = {
+ let mut records = lifecycle_records().lock().unwrap();
+ // The sweep's idle decision and the removal share this critical
+ // section, so a call that started and finished after the sweep picked
+ // the session keeps it alive.
+ if idle.is_some_and(|idle| !records.get(session_id).is_some_and(|r| idle.expired(r))) {
+ return EndTransition::StillLive;
+ }
+ records.remove(session_id)
+ };
let mut idle_ended = idle_ended_sessions().lock().unwrap();
let transition = if ended.contains_key(session_id) {
if reason != SessionEndReason::IdleTimeout && idle_ended.remove(session_id).is_some() {
@@ -1498,7 +1491,12 @@ pub fn session_cleanup_status(session_id: &str) -> SessionCleanupReport {
/// a local operator control path without requiring an authorization grant:
/// revocation can only remove authority, never create it.
pub fn revoke_all_sessions() -> usize {
- let mut sessions: Vec<String> = activity().lock().unwrap().keys().cloned().collect();
+ let mut sessions: Vec<String> = lifecycle_records()
+ .lock()
+ .unwrap()
+ .keys()
+ .cloned()
+ .collect();
sessions.extend(dormant_sessions(|_, _| true));
for session in &sessions {
end_session(session);
@@ -1508,7 +1506,7 @@ pub fn revoke_all_sessions() -> usize {
/// Revoke only sessions owned by one runtime-private namespace.
pub fn revoke_sessions_with_prefix(prefix: &str) -> usize {
- let mut sessions: Vec<String> = activity()
+ let mut sessions: Vec<String> = lifecycle_records()
.lock()
.unwrap()
.keys()
@@ -1669,38 +1667,22 @@ pub fn revive_session_for_owner(
}
}
-/// Record activity for an explicit runtime-private session id, resetting its
-/// idle-TTL clock. Called at the authorized registry boundary after public
-/// arguments have been mapped into their owning runtime namespace. No-op for
-/// the anonymous fallback (`"default"` / empty) and for a session that has
-/// already ended (so a late in-flight call can't resurrect a reaped session's
-/// TTL entry).
-pub fn touch_session(session_id: &str) {
- if !is_trackable(session_id) || is_session_ended(session_id) {
- return;
- }
- activity()
- .lock()
- .unwrap()
- .insert(session_id.to_owned(), Instant::now());
-}
-
#[doc(hidden)]
pub fn has_session_activity(session_id: &str) -> bool {
- activity().lock().unwrap().contains_key(session_id)
+ lifecycle_records().lock().unwrap().contains_key(session_id)
}
#[doc(hidden)]
pub fn session_idle_duration(session_id: &str) -> Option<Duration> {
- activity()
+ lifecycle_records()
.lock()
.unwrap()
.get(session_id)
- .map(Instant::elapsed)
+ .map(|record| record.last_activity.elapsed())
}
/// End a session explicitly (the `end_session` tool / `session end` CLI verb):
-/// drop its idle-TTL entry and fan `fire_session_end` out to every cleanup hook
+/// drop its lifecycle record and fan `fire_session_end` out to every cleanup hook
/// (overlay remove, recording stop, config-override clear). Idempotent via
/// `fire_session_end`'s dedupe. No-op for the anonymous fallback.
pub fn end_session(session_id: &str) {
@@ -1729,11 +1711,18 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
if defer {
return;
}
- finish_session_end(session_id, reason);
+ finish_session_end(session_id, reason, None);
}
-fn finish_session_end(session_id: &str, reason: SessionEndReason) {
- let transition = mark_session_ended(session_id, None, reason);
+fn finish_session_end(
+ session_id: &str,
+ reason: SessionEndReason,
+ idle: Option<IdleCheck>,
+) -> EndTransition {
+ let transition = mark_session_ended(session_id, None, reason, idle);
+ if transition == EndTransition::StillLive {
+ return transition;
+ }
let first_fire = transition == EndTransition::First;
let mut cursor_readers = CURSOR_OUTCOME_READERS
.get()
@@ -1764,6 +1753,26 @@ fn finish_session_end(session_id: &str, reason: SessionEndReason) {
observer.on_session_ended(public_session_label(session_id), reason, cursor);
}
}
+ transition
+}
+
+/// The idle sweep's test for one live record. Admitted work keeps a session
+/// alive however old its last use is.
+#[derive(Debug, Clone, Copy)]
+struct IdleCheck {
+ now: Instant,
+ default_ttl: Duration,
+}
+
+impl IdleCheck {
+ fn expired(self, record: &LifecycleRecord) -> bool {
+ // A use after the sweep's `now` is fresh even under a zero TTL.
+ record.in_flight == 0
+ && self
+ .now
+ .checked_duration_since(record.last_activity)
+ .is_some_and(|idle| idle >= record.idle_ttl.unwrap_or(self.default_ttl))
+ }
}
/// End every session whose last activity is older than `ttl`, returning the ids
@@ -1773,60 +1782,39 @@ fn finish_session_end(session_id: &str, reason: SessionEndReason) {
/// here instead of leaking its cursor / recording. Sessions touched within the
/// TTL are left untouched.
pub fn evict_idle(ttl: Duration) -> Vec<String> {
- let now = Instant::now();
- let lifecycle = lifecycle_records()
- .lock()
- .unwrap()
- .iter()
- .map(|(id, record)| (id.clone(), (record.in_flight, record.idle_ttl)))
- .collect::<HashMap<_, _>>();
- let stale: Vec<String> = {
- let map = activity().lock().unwrap();
- map.iter()
- .filter(|(id, last)| {
- let (in_flight, session_ttl) = lifecycle.get(*id).copied().unwrap_or_default();
- now.duration_since(**last) >= session_ttl.unwrap_or(ttl) && in_flight == 0
- })
- .map(|(id, _)| id.clone())
- .collect()
- };
- for id in &stale {
- end_session_with_reason(id, SessionEndReason::IdleTimeout);
- }
- stale
+ evict_idle_matching(ttl, |_| true)
}
/// Runtime-scoped form of [`evict_idle`]. The namespace prefix is minted by
/// the trusted runtime and never accepted from a tool argument.
pub fn evict_idle_with_prefix(ttl: Duration, prefix: &str) -> Vec<String> {
- let now = Instant::now();
- let lifecycle = lifecycle_records()
+ evict_idle_matching(ttl, |id| id.starts_with(prefix))
+}
+
+fn evict_idle_matching(ttl: Duration, keep: impl Fn(&str) -> bool) -> Vec<String> {
+ let idle = IdleCheck {
+ now: Instant::now(),
+ default_ttl: ttl,
+ };
+ let candidates = lifecycle_records()
.lock()
.unwrap()
.iter()
- .map(|(id, record)| (id.clone(), (record.in_flight, record.idle_ttl)))
- .collect::<HashMap<_, _>>();
- let stale: Vec<String> = {
- let map = activity().lock().unwrap();
- map.iter()
- .filter(|(id, last)| {
- let (in_flight, session_ttl) = lifecycle.get(*id).copied().unwrap_or_default();
- id.starts_with(prefix)
- && now.duration_since(**last) >= session_ttl.unwrap_or(ttl)
- && in_flight == 0
- })
- .map(|(id, _)| id.clone())
- .collect()
- };
- for id in &stale {
- end_session_with_reason(id, SessionEndReason::IdleTimeout);
- }
- stale
+ .filter(|(id, record)| is_trackable(id) && keep(id) && idle.expired(record))
+ .map(|(id, _)| id.clone())
+ .collect::<Vec<_>>();
+ candidates
+ .into_iter()
+ .filter(|id| {
+ finish_session_end(id, SessionEndReason::IdleTimeout, Some(idle))
+ != EndTransition::StillLive
+ })
+ .collect()
}
-/// Number of sessions with a live idle-TTL entry. Diagnostics only.
+/// Number of live lifecycle sessions. Diagnostics only.
pub fn active_session_count() -> usize {
- activity().lock().unwrap().len()
+ lifecycle_records().lock().unwrap().len()
}
#[cfg(test)]
@@ -1871,6 +1859,19 @@ mod tests {
}
}
+ /// One completed session-requiring call by the session's own transport.
+ fn use_session(session_id: &str) -> Result<(), &'static str> {
+ begin_session_dispatch(
+ session_id,
+ None,
+ session_id,
+ false,
+ SessionTransport::Daemon,
+ SessionClientKind::Direct,
+ )
+ .map(drop)
+ }
+
fn probe_observer() -> Arc<ProbeObserver> {
static PROBE: OnceLock<Arc<ProbeObserver>> = OnceLock::new();
PROBE
@@ -1950,9 +1951,9 @@ mod tests {
}
#[test]
- fn touch_then_evict_by_ttl() {
+ fn used_session_is_evicted_by_ttl() {
let sid = "test-ttl-session-DDEEFF";
- touch_session(sid);
+ use_session(sid).unwrap();
// A huge TTL leaves it alone (just touched).
assert!(evict_idle_with_prefix(Duration::from_secs(3600), sid)
.iter()
@@ -1966,10 +1967,70 @@ mod tests {
assert!(is_session_ended(sid), "evicted session is ended");
}
+ #[test]
+ fn idle_sweep_keeps_a_session_used_after_it_was_picked() {
+ let sid = "test-ttl-used-after-pick-5E2";
+ use_session(sid).unwrap();
+ std::thread::sleep(Duration::from_millis(30));
+ let idle = IdleCheck {
+ now: Instant::now(),
+ default_ttl: Duration::from_millis(10),
+ };
+ assert!(idle.expired(&lifecycle_records().lock().unwrap()[sid]));
+ // A whole call lands between the sweep's pick and its end.
+ use_session(sid).unwrap();
+ assert_eq!(
+ finish_session_end(sid, SessionEndReason::IdleTimeout, Some(idle)),
+ EndTransition::StillLive
+ );
+ assert!(!is_session_ended(sid), "a just-used session stays live");
+ end_session(sid);
+ }
+
+ #[test]
+ fn zero_ttl_sweep_keeps_a_session_used_after_it_was_picked() {
+ let sid = "test-ttl-zero-used-after-pick-5E2";
+ use_session(sid).unwrap();
+ let idle = IdleCheck {
+ now: Instant::now(),
+ default_ttl: Duration::ZERO,
+ };
+ assert!(idle.expired(&lifecycle_records().lock().unwrap()[sid]));
+ std::thread::sleep(Duration::from_millis(2));
+ use_session(sid).unwrap();
+ assert_eq!(
+ finish_session_end(sid, SessionEndReason::IdleTimeout, Some(idle)),
+ EndTransition::StillLive
+ );
+ assert!(!is_session_ended(sid));
+ end_session(sid);
+ }
+
+ /// Revoke walks the lifecycle records, the same map admission writes.
+ /// The old gap (a record not yet in the activity map) cannot be reached
+ /// from outside one call, so this pins the walk, not the race.
+ #[test]
+ fn revoke_ends_a_session_declared_without_a_call() {
+ let prefix = "__cua_runtime_5e2d0000000000000000000000000000:";
+ let sid = format!("{prefix}declared");
+ activate_session(
+ &sid,
+ None,
+ &sid,
+ false,
+ SessionTransport::Daemon,
+ SessionClientKind::Direct,
+ )
+ .unwrap();
+ assert_eq!(revoke_sessions_with_prefix(prefix), 1);
+ assert!(is_session_ended(&sid));
+ forget_ended_sessions_with_prefix(prefix);
+ }
+
#[test]
fn anonymous_ids_are_never_tracked() {
- touch_session("default");
- touch_session("");
+ assert!(use_session("default").is_err());
+ assert!(use_session("").is_err());
// Neither shows up under a zero-TTL sweep (they were never inserted).
let evicted = evict_idle_with_prefix(Duration::ZERO, "test-anonymous-never-matches");
assert!(!evicted.iter().any(|s| s == "default" || s.is_empty()));
@@ -1999,7 +2060,7 @@ mod tests {
#[test]
fn end_session_is_explicit_teardown() {
let sid = "test-end-session-112233";
- touch_session(sid);
+ use_session(sid).unwrap();
end_session(sid);
assert!(is_session_ended(sid));
// Its TTL entry is gone, so a later sweep doesn't re-fire for it.
@@ -2289,7 +2350,7 @@ mod tests {
}
});
- touch_session(sid);
+ use_session(sid).unwrap();
end_session(sid);
assert!(is_session_ended(sid));
assert_eq!(retryable_calls.load(Ordering::SeqCst), 1);
@@ -2390,7 +2451,7 @@ mod tests {
#[test]
fn revive_clears_the_tombstone_for_an_ended_id() {
let sid = "test-revive-session-445566";
- touch_session(sid);
+ use_session(sid).unwrap();
end_session(sid);
assert!(is_session_ended(sid), "ended id is tombstoned");
@@ -2407,18 +2468,18 @@ mod tests {
fn runtime_revoke_retains_tombstones_until_revival_or_runtime_teardown() {
let prefix = "__cua_runtime_00112233445566778899aabbccddeeff:";
let sid = format!("{prefix}revoked-session");
- touch_session(&sid);
+ use_session(&sid).unwrap();
assert_eq!(revoke_sessions_with_prefix(prefix), 1);
assert!(is_session_ended(&sid));
- touch_session(&sid);
+ assert!(use_session(&sid).is_err());
assert!(
!has_session_activity(&sid),
"ordinary traffic must not resurrect a revoked runtime session"
);
assert!(revive_session(&sid));
- touch_session(&sid);
+ use_session(&sid).unwrap();
assert!(has_session_activity(&sid));
end_session(&sid);
assert_eq!(forget_ended_sessions_with_prefix(prefix), 1);
@@ -2709,7 +2770,7 @@ mod tests {
end_session_with_reason(idle, SessionEndReason::IdleTimeout);
let revived = "test-observer-revived-MN34";
- touch_session(revived);
+ use_session(revived).unwrap();
end_session(revived);
begin_tool_call(
"start_session",
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
index 7d59e08df0..29f495eff1 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs
@@ -30,14 +30,14 @@
//! both paths, which is the cross-platform half of the contract.
use cua_driver_core::session::{
- active_session_count, end_session, evict_idle, is_session_ended, register_session_end_hook,
- revive_session, touch_session,
+ active_session_count, begin_session_dispatch, end_session, evict_idle, is_session_ended,
+ register_session_end_hook, revive_session, SessionClientKind, SessionTransport,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::Duration;
-/// `evict_idle` operates on the PROCESS-GLOBAL activity map, and the test binary
+/// `evict_idle` operates on the PROCESS-GLOBAL lifecycle records, and the test binary
/// runs tests in parallel. A concurrent `evict_idle(ZERO)` from another test
/// would otherwise steal (reap) this test's idle session before its own sweep
/// observes it — making "my sweep returned my id" flaky. Serialize every test
@@ -50,6 +50,22 @@ fn eviction_lock() -> MutexGuard<'static, ()> {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
+/// One completed session-requiring call, the only production path that
+/// refreshes a session's idle clock.
+fn use_session(session_id: &str) {
+ drop(
+ begin_session_dispatch(
+ session_id,
+ None,
+ session_id,
+ false,
+ SessionTransport::Daemon,
+ SessionClientKind::Direct,
+ )
+ .unwrap(),
+ );
+}
+
/// Process-global session state is shared across every test in this binary, so
/// each test uses its own unique session id and hooks that filter on it.
fn unique_id(tag: &str) -> String {
@@ -136,7 +152,7 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {
// the trackable, not-ended, counted state is the proxy for "registered /
// cursor present" (the CursorRegistry is platform-macos, daemon-level only).
revive_session(&sid);
- touch_session(&sid);
+ use_session(&sid);
assert!(
!is_session_ended(&sid),
"freshly started session must be live"
@@ -148,7 +164,7 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {
disposal.assert_not_disposed("just started");
// 2. After activity, the session is alive and NOT evicted under a long TTL.
- touch_session(&sid);
+ use_session(&sid);
let evicted = evict_idle(Duration::from_secs(3600));
assert!(
!evicted.contains(&sid),
@@ -175,7 +191,7 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {
revive_session(&sid),
"re-declaring a recycled id revives it"
);
- touch_session(&sid);
+ use_session(&sid);
assert!(
!is_session_ended(&sid),
"revived id is live again, actions no longer rejected"
@@ -190,7 +206,7 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {
}
/// Idle-TTL auto-eviction disposes a session the SAME way `end_session` does:
-/// every cleanup hook fires — not merely that the id left the activity map.
+/// every cleanup hook fires — not merely that the id left the live records.
#[test]
fn idle_ttl_eviction_disposes_like_end_session() {
let _guard = eviction_lock();
@@ -198,14 +214,14 @@ fn idle_ttl_eviction_disposes_like_end_session() {
let disposal = Disposal::wire(&sid);
// Start, then leave the session UNTOUCHED past a short TTL.
- touch_session(&sid);
+ use_session(&sid);
disposal.assert_not_disposed("before idle window");
// Age the session well beyond the short TTL we'll sweep with.
std::thread::sleep(Duration::from_millis(25));
let evicted = evict_idle(Duration::from_millis(5));
- // (a) the id left the activity map (the shallow signal)...
+ // (a) the id left the live records (the shallow signal)...
assert!(
evicted.contains(&sid),
"idle session past the short TTL is evicted"
@@ -231,11 +247,11 @@ fn fresh_session_survives_short_ttl_that_evicts_idle_sibling() {
let idle_disposal = Disposal::wire(&idle);
let fresh_disposal = Disposal::wire(&fresh);
- touch_session(&idle);
+ use_session(&idle);
std::thread::sleep(Duration::from_millis(40));
// Touch `fresh` immediately before the sweep so its age (~0) is far under the
// 10ms TTL, while `idle` (~40ms) is far over it.
- touch_session(&fresh);
+ use_session(&fresh);
let evicted = evict_idle(Duration::from_millis(10));
assert!(evicted.contains(&idle), "idle sibling evicted");
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/driver.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/driver.rs
index 72e5da3276..d626a3c077 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/driver.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/driver.rs
@@ -277,23 +277,39 @@ impl DriverService for DriverServiceImpl {
#[cfg(test)]
mod tests {
use super::*;
- use cua_driver_core::session::{is_session_ended, touch_session};
+ use cua_driver_core::session::{
+ begin_session_dispatch, is_session_ended, SessionClientKind, SessionTransport,
+ };
+
+ fn use_session(session_id: &str) {
+ drop(
+ begin_session_dispatch(
+ session_id,
+ None,
+ session_id,
+ false,
+ SessionTransport::Daemon,
+ SessionClientKind::Direct,
+ )
+ .unwrap(),
+ );
+ }
#[tokio::test]
async fn the_sweep_ends_a_session_left_idle_past_the_ttl() {
let idle = format!("spacesd-sweep-idle-{}", std::process::id());
let busy = format!("spacesd-sweep-busy-{}", std::process::id());
- touch_session(&idle);
- touch_session(&busy);
+ use_session(&idle);
+ use_session(&busy);
let sweep = spawn_idle_sweep(Duration::from_millis(20), Duration::from_millis(300));
// `busy` is used again and again; `idle` is left alone.
for _ in 0..25 {
tokio::time::sleep(Duration::from_millis(20)).await;
- touch_session(&busy);
+ use_session(&busy);
}
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !is_session_ended(&idle) && std::time::Instant::now() < deadline {
- touch_session(&busy);
+ use_session(&busy);
tokio::time::sleep(Duration::from_millis(20)).await;
}
sweep.abort();