A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
perf(session): capture git state off the session lock (#3317)
Sebastian Müller58fbe1e6a1d9
diff --git a/.changes/git-state-off-session-lock.md b/.changes/git-state-off-session-lock.mdnew file mode 100644index 0000000000..2ea68dfe8c--- /dev/null+++ b/.changes/git-state-off-session-lock.md@@ -0,0 +1 @@+- Agent runs no longer stall the session while recording git state: the git checks at the start and end of each run now run in parallel in the background instead of blocking other work on the session.diff --git a/crates/pa-core/src/session/manager/git.rs b/crates/pa-core/src/session/manager/git.rsindex 339293b54a..30e70dd1c1 100644--- a/crates/pa-core/src/session/manager/git.rs+++ b/crates/pa-core/src/session/manager/git.rs@@ -1,25 +1,9 @@//! The git-context concern (moved with its concern): the quiet git//! probes and the header's git-context capture (TS captureGitContext).-use super::{GitContext, Path};+use std::process::Stdio;-/// One quiet git probe: `--no-optional-locks`, stdio ignore/pipe/ignore,-/// `None` on any failure or empty output (TS `runGit` in utils/git.ts).-fn run_git_probe(cwd: &Path, args: &[&str]) -> Option<String> {- std::process::Command::new("git")- .arg("--no-optional-locks")- .args(args)- .current_dir(cwd)- .stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::null())- .output()- .ok()- .filter(|output| output.status.success())- .and_then(|output| String::from_utf8(output.stdout).ok())- .map(|stdout| stdout.trim().to_string())- .filter(|value| !value.is_empty())-}+use super::{GitContext, Path};/// Capture git context for the header (best effort; None outside a repo).///@@ -27,12 +11,35 @@ fn run_git_probe(cwd: &Path, args: &[&str]) -> Option<String> {/// the context exists when at least one probe succeeds. `branch` is/// `--show-current`, so a detached HEAD yields no branch. The remote URL is/// normalized through the git-source parser when it parses, else kept-/// verbatim.+/// verbatim. The three probes run concurrently.#[must_use]pub fn capture_git_context(cwd: &Path) -> Option<GitContext> {- let commit = run_git_probe(cwd, &["rev-parse", "HEAD"]);- let branch = run_git_probe(cwd, &["branch", "--show-current"]);- let remote = run_git_probe(cwd, &["remote", "get-url", "origin"]);+ let probes: [&[&str]; 3] = [+ &["rev-parse", "HEAD"],+ &["branch", "--show-current"],+ &["remote", "get-url", "origin"],+ ];+ // Spawn every probe before waiting on any.+ let children = probes.map(|args| {+ std::process::Command::new("git")+ .arg("--no-optional-locks")+ .args(args)+ .current_dir(cwd)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .ok()+ });+ let [commit, branch, remote] = children.map(|child| {+ child?+ .wait_with_output()+ .ok()+ .filter(|output| output.status.success())+ .and_then(|output| String::from_utf8(output.stdout).ok())+ .map(|stdout| stdout.trim().to_string())+ .filter(|value| !value.is_empty())+ });if commit.is_none() && branch.is_none() && remote.is_none() {return None;}diff --git a/crates/pa-core/src/session/manager_ext.rs b/crates/pa-core/src/session/manager_ext.rsindex bb8ce3b1c0..54592d68d3 100644--- a/crates/pa-core/src/session/manager_ext.rs+++ b/crates/pa-core/src/session/manager_ext.rs@@ -67,17 +67,12 @@ impl SessionManager {Ok(id)}- /// Append git state when it changed on the active branch.- pub fn record_git_state_if_changed(&mut self) -> Option<String> {- if !self.is_persisted() {+ /// Append `git` as a `git_state` row when it differs from the nearest+ /// git context on the active branch (or the header); returns the new id.+ pub fn record_git_state_if_changed(&mut self, git: GitContext) -> Option<String> {+ if self.active_git_context().as_ref() == Some(&git) {return None;}- let git = super::manager::capture_git_context(self.get_cwd())?;- if let Some(last) = self.active_git_context() {- if git_contexts_equal(&last, &git) {- return None;- }- }self.append_git_state(git).ok()}@@ -298,10 +293,6 @@ fn entry_type(entry: &FileEntry) -> &'static str {}}-fn git_contexts_equal(left: &GitContext, right: &GitContext) -> bool {- left.commit == right.commit && left.branch == right.branch && left.repo_url == right.repo_url-}-#[cfg(test)]mod tests {use crate::session::manager::SessionManager;diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rsindex d64c637684..cc88351ad0 100644--- a/crates/pa-core/src/session_engine/mod.rs+++ b/crates/pa-core/src/session_engine/mod.rs@@ -61,7 +61,7 @@ use pa_agent::types::{AgentEvent, AgentMessage, ThinkingLevel};use pa_types::session::AgentMessage as SessionAgentMessage;use pa_types::session::FileEntry;-use crate::session::manager::SessionManager;+use crate::session::manager::{capture_git_context, SessionManager};use crate::skills::PromptTemplate;use slash_commands::{SessionSlashCommand, SlashCommandRegistry};@@ -435,10 +435,22 @@ async fn persist_event(// Git state is captured at both run boundaries, exactly like the// TS run-boundary event path: a commit or branch switch made during the run// (e.g. via the bash tool) lands in the session file at `agent_end`.- // The persist check lives inside `record_git_state_if_changed`.+ // The git probes block, so they run on the blocking pool with the+ // session lock released. A session's captures are sequential (the loop+ // awaits every listener), the cwd never changes, and no other lock+ // holder appends `git_state`, so re-taking the lock cannot race.AgentEvent::AgentStart | AgentEvent::AgentEnd { .. } => {- let mut session = session.lock().await;- session.record_git_state_if_changed();+ let cwd = {+ let session = session.lock().await;+ session+ .is_persisted()+ .then(|| session.get_cwd().to_path_buf())+ };+ let Some(cwd) = cwd else { return Ok(()) };+ let git = tokio::task::spawn_blocking(move || capture_git_context(&cwd)).await?;+ if let Some(git) = git {+ session.lock().await.record_git_state_if_changed(git);+ }}_ => {}}diff --git a/crates/pa-core/src/session_engine/tests.rs b/crates/pa-core/src/session_engine/tests.rsindex c998624ecb..4f172f13bd 100644--- a/crates/pa-core/src/session_engine/tests.rs+++ b/crates/pa-core/src/session_engine/tests.rs@@ -934,8 +934,9 @@ async fn template_expansion_applies() {/// Git state is captured at both run boundaries (the TS run-boundary event/// path calls `recordGitStateIfChanged` on `agent_start`/`agent_end`): a commit-/// made between session creation and the run lands as a `git_state`-/// entry, and an unchanged context at `agent_end` adds nothing.+/// made between session creation and the run lands as a `git_state` entry, a+/// branch switch between turns is recorded by the next run, and an unchanged+/// context at `agent_end` adds nothing.#[tokio::test]async fn run_boundaries_record_git_state() {fn git(cwd: &std::path::Path, args: &[&str]) {@@ -986,6 +987,14 @@ async fn run_boundaries_record_git_state() {engine.prompt("hi", PromptOptions::default()).await.unwrap();engine.agent().wait_for_idle().await;+ git(repo.path(), &["checkout", "-q", "-b", "feature"]);+ provider.push_text_turn("ok");+ engine+ .prompt("again", PromptOptions::default())+ .await+ .unwrap();+ engine.agent().wait_for_idle().await;+let entries = engine.entries().await;let git_states: Vec<_> = entries.iter()@@ -994,7 +1003,19 @@ async fn run_boundaries_record_git_state() {_ => None,}).collect();- assert_eq!(git_states.len(), 1, "one git_state per changed context");- assert_eq!(git_states[0].commit.as_deref(), Some(second_sha.as_str()));- assert_eq!(git_states[0].branch.as_deref(), Some("main"));+ assert_eq!(+ git_states,+ vec![+ pa_types::session::GitContext {+ repo_url: None,+ commit: Some(second_sha.clone()),+ branch: Some("main".to_string()),+ },+ pa_types::session::GitContext {+ repo_url: None,+ commit: Some(second_sha),+ branch: Some("feature".to_string()),+ },+ ]+ );}diff --git a/crates/pa-core/tests/git_context.rs b/crates/pa-core/tests/git_context.rsindex 31152ff5f6..65073f7577 100644--- a/crates/pa-core/tests/git_context.rs+++ b/crates/pa-core/tests/git_context.rs@@ -240,7 +240,10 @@ fn no_git_state_entry_when_nothing_changed() {commit(repo.path(), "init");let mut manager = SessionManager::persisted(repo.path(), sessions.path());- assert_eq!(manager.record_git_state_if_changed(), None);+ assert_eq!(+ manager.record_git_state_if_changed(capture_git_context(repo.path()).unwrap()),+ None+ );assert!(!manager.get_entries().iter()@@ -257,7 +260,9 @@ fn records_git_state_when_commit_changes() {// The header captures the first commit; the run lands on the second.let mut manager = SessionManager::persisted(repo.path(), sessions.path());let second_sha = commit(repo.path(), "second");- assert!(manager.record_git_state_if_changed().is_some());+ assert!(manager+ .record_git_state_if_changed(capture_git_context(repo.path()).unwrap())+ .is_some());let entries = manager.get_entries();let git_states: Vec<_> = entries.iter()@@ -271,7 +276,10 @@ fn records_git_state_when_commit_changes() {other => panic!("expected git_state, got {other:?}"),}// Unchanged context dedupes away.- assert_eq!(manager.record_git_state_if_changed(), None);+ assert_eq!(+ manager.record_git_state_if_changed(capture_git_context(repo.path()).unwrap()),+ None+ );}#[test]@@ -284,13 +292,17 @@ fn re_records_git_state_on_branch_without_it_on_active_path() {let mut manager = SessionManager::persisted(repo.path(), sessions.path());let msg_id = manager.append_message(user("hi")).unwrap();commit(repo.path(), "second");- assert!(manager.record_git_state_if_changed().is_some());+ assert!(manager+ .record_git_state_if_changed(capture_git_context(repo.path()).unwrap())+ .is_some());// Move the leaf before the git_state entry: the nearest git context on// this path is the header again, so a new entry must be appended rather// than deduped against the sibling's.manager.branch(&msg_id);- assert!(manager.record_git_state_if_changed().is_some());+ assert!(manager+ .record_git_state_if_changed(capture_git_context(repo.path()).unwrap())+ .is_some());}#[test]@@ -302,7 +314,7 @@ fn git_state_entries_stay_out_of_llm_context() {let mut manager = SessionManager::persisted(repo.path(), sessions.path());commit(repo.path(), "second");- manager.record_git_state_if_changed();+ manager.record_git_state_if_changed(capture_git_context(repo.path()).unwrap());let context = pa_core::session::build_session_context(&manager.get_entries(),manager.get_leaf_id().map(str::to_string).as_deref(),