Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(agent-harness): free the context lease before answering a reset (#9768)

teodb27fef07a32
diff --git a/crates/agent_harness/src/domain/conversation_turns.rs b/crates/agent_harness/src/domain/conversation_turns.rs
index d24e788226..098d96f39c 100644
--- a/crates/agent_harness/src/domain/conversation_turns.rs
+++ b/crates/agent_harness/src/domain/conversation_turns.rs
@@ -86,9 +86,16 @@ pub struct ConversationTurnStatus {
}
/// Persistence mechanics only; authorization and execution decisions stay in the harness.
-/// A held reply reconciliation claim. Dropping it releases the claim, including
-/// on cancellation; no external action is retried by acquiring this lease.
-pub trait ConversationLease: Send {}
+/// A held reply reconciliation claim. Dropping it releases the claim soon
+/// after, including on cancellation; no external action is retried by acquiring
+/// this lease.
+#[async_trait::async_trait]
+pub trait ConversationLease: Send {
+ /// Release now, so the session is free for the next claim once this
+ /// returns. Dropping leaves the release to a background task, so a claim
+ /// made straight after a drop can still find the lease held.
+ async fn release(self: Box<Self>);
+}
/// The persona configuration adopted when a conversation's session first opens.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
diff --git a/crates/agent_harness/src/domain/conversations.rs b/crates/agent_harness/src/domain/conversations.rs
index 5202af9b4f..ba24a7abe0 100644
--- a/crates/agent_harness/src/domain/conversations.rs
+++ b/crates/agent_harness/src/domain/conversations.rs
@@ -331,31 +331,14 @@ impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversatio
},
})
}
-}
-impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversationRepo>
- AgentConversations for AgentConversationsService<C, P, B, S>
-{
- async fn start_fresh(
+ /// Start a fresh session, holding the old session's context lease.
+ async fn reset_held(
&self,
- caller: MacroUserIdStr<'static>,
+ store: &dyn super::conversation_turns::ConversationTurnStore,
conversation: AgentConversation,
expected: AgentSessionId,
) -> Result<(), ConversationError> {
- let agent = self.joined(&caller, conversation).await?;
- self.eligibility
- .authorize_agent_dm(caller, agent.bot_id)
- .await
- .map_err(|error| match error {
- BotError::Unauthorized | BotError::NotFound(_) => ConversationError::NotRetryable,
- error => ConversationError::Unavailable(error.into()),
- })?;
- let store = self.turns.as_ref().ok_or(ConversationError::ContextBusy)?;
- let _lease = store
- .claim_context(expected)
- .await
- .map_err(|error| ConversationError::Unavailable(error.into()))?
- .ok_or(ConversationError::ContextBusy)?;
if self
.sessions
.current(conversation)
@@ -394,6 +377,66 @@ impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversatio
Ok(())
}
+ /// Queue a retry of a failed turn, holding its session's context lease.
+ async fn retry_held(
+ &self,
+ store: &dyn super::conversation_turns::ConversationTurnStore,
+ conversation: AgentConversation,
+ source: Uuid,
+ expected: agent_runtime_protocol::domain::action::AgentActionId,
+ session: AgentSessionId,
+ ) -> Result<(), ConversationError> {
+ if self
+ .sessions
+ .current(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ != Some(session)
+ {
+ return Err(ConversationError::NotRetryable);
+ }
+ if !store
+ .retry(source, conversation.bot_id, expected)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ {
+ return Err(ConversationError::NotRetryable);
+ }
+ Ok(())
+ }
+}
+
+impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversationRepo>
+ AgentConversations for AgentConversationsService<C, P, B, S>
+{
+ async fn start_fresh(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ expected: AgentSessionId,
+ ) -> Result<(), ConversationError> {
+ let agent = self.joined(&caller, conversation).await?;
+ self.eligibility
+ .authorize_agent_dm(caller, agent.bot_id)
+ .await
+ .map_err(|error| match error {
+ BotError::Unauthorized | BotError::NotFound(_) => ConversationError::NotRetryable,
+ error => ConversationError::Unavailable(error.into()),
+ })?;
+ let store = self.turns.as_ref().ok_or(ConversationError::ContextBusy)?;
+ let lease = store
+ .claim_context(expected)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .ok_or(ConversationError::ContextBusy)?;
+ let reset = self
+ .reset_held(store.as_ref(), conversation, expected)
+ .await;
+ // Whoever acts on the answer can claim again at once.
+ lease.release().await;
+ reset
+ }
+
async fn retry(
&self,
caller: MacroUserIdStr<'static>,
@@ -430,28 +473,22 @@ impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversatio
if Some(record.session_id) != current || record.action_id != expected {
return Err(ConversationError::NotRetryable);
}
- let _lease = store
+ let lease = store
.claim_context(record.session_id)
.await
.map_err(|error| ConversationError::Unavailable(error.into()))?
.ok_or(ConversationError::NotRetryable)?;
- if self
- .sessions
- .current(conversation)
- .await
- .map_err(|error| ConversationError::Unavailable(error.into()))?
- != Some(record.session_id)
- {
- return Err(ConversationError::NotRetryable);
- }
- if !store
- .retry(source, conversation.bot_id, expected)
- .await
- .map_err(|error| ConversationError::Unavailable(error.into()))?
- {
- return Err(ConversationError::NotRetryable);
- }
- Ok(())
+ let retried = self
+ .retry_held(
+ store.as_ref(),
+ conversation,
+ source,
+ expected,
+ record.session_id,
+ )
+ .await;
+ lease.release().await;
+ retried
}
async fn list(
diff --git a/crates/agent_harness/src/outbound/conversation_turns.rs b/crates/agent_harness/src/outbound/conversation_turns.rs
index bf0dfe477c..d5ae98c1a3 100644
--- a/crates/agent_harness/src/outbound/conversation_turns.rs
+++ b/crates/agent_harness/src/outbound/conversation_turns.rs
@@ -50,10 +50,21 @@ async fn take_slot(
}
struct PgReplyLease {
- _transaction: sqlx::Transaction<'static, sqlx::Postgres>,
+ transaction: sqlx::Transaction<'static, sqlx::Postgres>,
_slot: tokio::sync::OwnedSemaphorePermit,
}
-impl ConversationLease for PgReplyLease {}
+
+#[async_trait::async_trait]
+impl ConversationLease for PgReplyLease {
+ async fn release(self: Box<Self>) {
+ let Self { transaction, _slot } = *self;
+ // The lock ends with the transaction. A failed rollback means the
+ // connection is gone, and the server releases the lock with it.
+ if let Err(error) = transaction.rollback().await {
+ tracing::warn!(?error, "could not roll back a conversation lease");
+ }
+ }
+}
impl PgConversationTurnStore {
/// Construct at the composition root from MacroDB.
@@ -93,7 +104,7 @@ impl ConversationTurnStore for PgConversationTurnStore {
.map_err(anyhow::Error::from)?;
Ok(claimed.then(|| {
Box::new(PgReplyLease {
- _transaction: tx,
+ transaction: tx,
_slot: slot,
}) as Box<dyn ConversationLease>
}))
@@ -115,7 +126,7 @@ impl ConversationTurnStore for PgConversationTurnStore {
.map_err(anyhow::Error::from)?;
Ok(claimed.then(|| {
Box::new(PgReplyLease {
- _transaction: tx,
+ transaction: tx,
_slot: slot,
}) as Box<dyn ConversationLease>
}))
@@ -315,7 +326,7 @@ impl ConversationTurnStore for PgConversationTurnStore {
return Ok(None);
}
Ok(Some(Box::new(PgReplyLease {
- _transaction: tx,
+ transaction: tx,
_slot: slot,
})))
}
diff --git a/crates/agent_harness/src/outbound/conversation_turns/test.rs b/crates/agent_harness/src/outbound/conversation_turns/test.rs
index b15bfd2837..2fd4e4747e 100644
--- a/crates/agent_harness/src/outbound/conversation_turns/test.rs
+++ b/crates/agent_harness/src/outbound/conversation_turns/test.rs
@@ -425,6 +425,53 @@ async fn a_running_turn_blocks_reset_and_completed_context_is_retained(pool: PgP
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_released_context_lease_is_free_at_once(pool: PgPool) {
+ let (store, session, _, _) = setup(pool.clone()).await;
+ let other = PgConversationTurnStore::new(pool);
+ for _ in 0..100 {
+ let lease = store.claim_context(session).await.unwrap().unwrap();
+ assert!(other.claim_context(session).await.unwrap().is_none());
+ lease.release().await;
+ other
+ .claim_context(session)
+ .await
+ .unwrap()
+ .expect("a released lease is free")
+ .release()
+ .await;
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_refused_reset_leaves_the_context_free(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let owner = mention_origin(&command).sender.clone();
+ let record = store.admit(session, channel, command).await.unwrap();
+ let service = conversations(pool.clone(), store.clone(), true);
+ assert!(
+ store
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap()
+ );
+ for _ in 0..50 {
+ assert!(matches!(
+ service
+ .start_fresh(owner.clone(), conversation(channel), session)
+ .await,
+ Err(ConversationError::ContextBusy)
+ ));
+ store
+ .claim_context(session)
+ .await
+ .unwrap()
+ .expect("the refused reset released its lease")
+ .release()
+ .await;
+ }
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn reset_cancels_undispatched_work_and_serializes_with_claims(pool: PgPool) {
let (store, session, channel, command) = setup(pool.clone()).await;