agent: abort also ends a hanging request and compaction
This commit is contained in:
1 parent
e119dc2f0d
commit
79cf5fcda1
1 file changed
+44
-2
@@ -433,7 +433,12 @@ impl Agent {
|
||||
) -> Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>, Error> {
|
||||
let mut wait = self.retry_ms;
|
||||
for attempt in 1..=4 {
|
||||
match self.provider.stream(req.clone()).await {
|
||||
let mut ab = self.abort.clone();
|
||||
let r = tokio::select! {
|
||||
r = self.provider.stream(req.clone()) => r,
|
||||
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
||||
};
|
||||
match r {
|
||||
Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => {
|
||||
self.emit(Event::Info(format!(
|
||||
"api error {status}; retry {attempt}/3 in {wait}ms"
|
||||
@@ -477,8 +482,12 @@ impl Agent {
|
||||
if self.aborted() {
|
||||
return Err(Error::Aborted);
|
||||
}
|
||||
let mut ab = self.abort.clone();
|
||||
if self.window.should_compact(&self.session.messages())
|
||||
&& self.compact(KEEP_MESSAGES).await?
|
||||
&& tokio::select! {
|
||||
r = self.compact(KEEP_MESSAGES) => r?,
|
||||
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
||||
}
|
||||
{
|
||||
self.emit(Event::Info("context compacted".into())).await;
|
||||
}
|
||||
@@ -919,6 +928,39 @@ mod tests {
|
||||
(r, n)
|
||||
}
|
||||
|
||||
struct Hang;
|
||||
#[async_trait]
|
||||
impl Provider for Hang {
|
||||
async fn stream(
|
||||
&self,
|
||||
_: Request,
|
||||
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn abort_ends_a_request_that_never_answers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, h) = Agent::new(
|
||||
Arc::new(Hang),
|
||||
Registry::default(),
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
let t = tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
h.abort();
|
||||
});
|
||||
let r = tokio::time::timeout(std::time::Duration::from_secs(5), a.run("go")).await;
|
||||
t.await.unwrap();
|
||||
assert!(matches!(r, Ok(Err(Error::Aborted))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transient_api_errors_are_retried() {
|
||||
let (r, n) = flaky_run(1, 529).await;
|
||||
|
||||
Reference in new issue
Block a user