Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(session): move cancel_revalidation before push in all store paths

Steven Enamakel4134105c915e
diff --git a/crates/openhuman-session/src/manager.rs b/crates/openhuman-session/src/manager.rs
index 7b1f8335c3..e53b4aa288 100644
--- a/crates/openhuman-session/src/manager.rs
+++ b/crates/openhuman-session/src/manager.rs
@@ -208,7 +208,6 @@ impl<L: CoreLink> SessionManager<L> {
user: Option<Value>,
) -> Result<SessionState, SessionError> {
let guard = self.mutation.lock().await;
- self.cancel_revalidation();
let credential = Credential::classify(token);
if credential.secret.is_empty() {
return Err(SessionError::Invalid("token is required".to_string()));
@@ -221,6 +220,7 @@ impl<L: CoreLink> SessionManager<L> {
"local session requires a user payload".to_string(),
));
}
+ self.cancel_revalidation();
self.push(&credential, None, user.as_ref()).await?;
self.cache.forget();
drop(guard);
@@ -244,6 +244,7 @@ impl<L: CoreLink> SessionManager<L> {
"{LOG_PREFIX} session JWT verified via GET /auth/me on {}",
client.base_url()
);
+ self.cancel_revalidation();
self.push(&credential, user_id.as_deref(), Some(&me))
.await?;
self.cache.seed(&client, &credential, me);
@@ -271,6 +272,7 @@ impl<L: CoreLink> SessionManager<L> {
"{LOG_PREFIX} backend unreachable ({reason}); storing pending session for user_id={user_id} and revalidating in the background"
);
let pending = json!({ PENDING_BACKEND_VALIDATION_FIELD: true });
+ self.cancel_revalidation();
self.push(&credential, Some(&user_id), Some(&pending))
.await?;
self.cache.forget();
@@ -288,6 +290,7 @@ impl<L: CoreLink> SessionManager<L> {
if credential.secret.is_empty() {
return Err(SessionError::Invalid("api key is required".to_string()));
}
+ self.cancel_revalidation();
self.push(&credential, None, None).await?;
drop(guard);
self.changed().await
@@ -531,20 +534,27 @@ impl<L: CoreLink> SessionManager<L> {
/// Core state plus the current user, in one shape.
pub async fn state(&self) -> Result<SessionState, SessionError> {
- let core = self.core_state().await?;
- let current = match self.current_user_for(&core, false).await {
- Ok(current) => current,
- Err(SessionError::Rejected(_)) => {
- return Ok(SessionState::default());
+ loop {
+ let core = self.core_state().await?;
+ let current = match self.current_user_for(&core, false).await {
+ Ok(current) => current,
+ Err(SessionError::Rejected(_)) => return Ok(SessionState::default()),
+ Err(error) => return Err(error),
+ };
+ // `current_user_for` retries with a new credential when a refresh
+ // is superseded. Do not combine that retried user with the core
+ // snapshot from before the credential change.
+ if self.core_state().await? != core {
+ log::debug!("{LOG_PREFIX} session state changed while reading current user; retrying");
+ continue;
}
- Err(error) => return Err(error),
- };
- Ok(SessionState {
- current_user: current.user.or_else(|| core.user.clone()),
- current_user_stale: current.stale,
- current_user_stale_seconds: current.stale_seconds,
- core,
- })
+ return Ok(SessionState {
+ current_user: current.user.or_else(|| core.user.clone()),
+ current_user_stale: current.stale,
+ current_user_stale_seconds: current.stale_seconds,
+ core,
+ });
+ }
}
}
diff --git a/crates/openhuman-session/src/manager_tests.rs b/crates/openhuman-session/src/manager_tests.rs
index 36122c9f8b..c3b565f362 100644
--- a/crates/openhuman-session/src/manager_tests.rs
+++ b/crates/openhuman-session/src/manager_tests.rs
@@ -108,6 +108,24 @@ async fn unreachable_backend_refuses_tokens_without_exp_or_subject() {
assert_eq!(core.session(), None);
}
+#[tokio::test]
+async fn rejected_replacement_keeps_pending_session_revalidation_running() {
+ let core = FakeCore::new("http://127.0.0.1:9");
+ let m = manager(&core);
+ m.store_session_token(&LIVE_JWT, None).await.unwrap();
+ assert!(m.revalidation.lock().unwrap().is_some());
+
+ assert_eq!(
+ m.store_session_token(&EXPIRED_JWT, None).await.unwrap_err(),
+ SessionError::Expired
+ );
+ assert!(
+ m.revalidation.lock().unwrap().is_some(),
+ "a rejected replacement must not abandon the stored pending session"
+ );
+ m.cancel_revalidation();
+}
+
#[tokio::test]
async fn caller_supplied_user_id_rescues_a_subjectless_jwt_offline() {
let core = FakeCore::new("http://127.0.0.1:9");
@@ -276,6 +294,33 @@ async fn rejection_of_a_superseded_token_leaves_the_new_session_alone() {
.all(|e| !matches!(e, SessionEvent::Expired { .. })));
}
+#[tokio::test]
+async fn state_retries_its_core_snapshot_after_a_superseded_refresh() {
+ let backend = Backend::start(vec![
+ MeAnswer::Ok(me_user()),
+ MeAnswer::Slow(300),
+ MeAnswer::Ok(serde_json::json!({ "_id": "user-456", "email": "[email protected]" })),
+ ])
+ .await;
+ let core = FakeCore::new(&backend.url);
+ let m = manager(&core);
+ m.login_with_token("tok").await.unwrap();
+ m.cache().forget();
+
+ let reading = {
+ let m = Arc::clone(&m);
+ tokio::spawn(async move { m.state().await })
+ };
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ m.store_session_token(&LIVE_JWT_NO_SUB, Some(serde_json::json!({ "id": "user-456" })))
+ .await
+ .unwrap();
+
+ let state = reading.await.unwrap().unwrap();
+ assert_eq!(state.core.user_id.as_deref(), Some("user-456"));
+ assert_eq!(state.current_user.as_ref().unwrap()["_id"], "user-456");
+}
+
#[tokio::test]
async fn pending_confirmation_after_logout_does_not_restore_the_session() {
let backend = Backend::start(vec![MeAnswer::Slow(300)]).await;