Skip to content

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

feat(embed): expose shared budget capacity waiting

Steven Enamakele91a47423acf
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget.rs b/crates/openhuman-core/src/agent/tinyagents/budget.rs
index 6f02d9e0c4..8f4b2ff886 100644
--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs
@@ -14,6 +14,13 @@ pub struct ModelBudget {
pub call: CallBudget,
}
impl ModelBudget {
+ /// Wait for live reservations when settled spend still affords admission.
+ /// Clones and child turns inherit this opt-in; internal retries stay fail-fast.
+ pub fn wait_for_capacity(mut self) -> Self {
+ self.ledger = self.ledger.wait_for_capacity();
+ self
+ }
+
/// Apply the policy below retries and fallback selection.
pub(crate) fn wrap(&self, model: Arc<dyn ChatModel<()>>) -> Arc<dyn ChatModel<()>> {
Arc::new(tinyinference_llm::model::budget::BudgetedModel::new(
diff --git a/crates/openhuman-embed/src/budget.rs b/crates/openhuman-embed/src/budget.rs
index 688dc45025..35559d9aaa 100644
--- a/crates/openhuman-embed/src/budget.rs
+++ b/crates/openhuman-embed/src/budget.rs
@@ -7,6 +7,14 @@
//! bounds are host-supplied upper bounds for every allowed route, not billing
//! estimates; providers cannot be forced to honour a monetary cap locally.
//!
+//! Admission is fail-fast by default. [`ModelBudget::wait_for_capacity`] opts
+//! a policy into waiting only when live reservations prevent an otherwise
+//! affordable call; clones and child turns inherit it. Calls that fit still
+//! run concurrently, while settled spend that cannot fit refuses immediately.
+//! Canceling before admission reserves nothing. Internal transport retries
+//! remain fail-fast, and unknown dispatched charges are never refunded.
+//! Hosts retain their existing logical deadlines and cancellation controls.
+//!
//! Budgeted calls currently accept text only. Input bounds use serialized-byte
//! counts conservatively; multimodal requests fail before dispatch. Choose
//! bounds that include model framing and the maximum price on allowed routes.
diff --git a/crates/openhuman-embed/tests/budget_capacity.rs b/crates/openhuman-embed/tests/budget_capacity.rs
new file mode 100644
index 0000000000..d4baf31c8a
--- /dev/null
+++ b/crates/openhuman-embed/tests/budget_capacity.rs
@@ -0,0 +1,151 @@
+//! Capacity waiting preserves provider fallback and pre-admission cancellation.
+use openhuman_embed::routing::{CompletionLadder, CompletionRung};
+use openhuman_embed::{ChatMessage, Completer, CompletionRequest, Route};
+use serde_json::{json, Value};
+use wiremock::matchers::method;
+use wiremock::{Mock, MockServer, ResponseTemplate};
+
+fn answer(model: &str, finish: &str, cost: f64) -> Value {
+ json!({"model":model,"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":finish}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"cost":cost}})
+}
+async fn scripted(bodies: Vec<Value>) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(bodies[0].clone()))
+ .mount(&server)
+ .await;
+ server
+}
+
+#[tokio::test]
+async fn temporary_capacity_wait_does_not_suppress_rpc_fallback() {
+ use openhuman_embed::budget::{Budget, CallBudget, ModelBudget, Spend, SpendLimits};
+ let failing = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .set_body_json(json!({"error":{"message":"fixture rejection"}})),
+ )
+ .mount(&failing)
+ .await;
+ let healthy = scripted(vec![answer("healthy", "stop", 0.000010)]).await;
+ let policy = ModelBudget {
+ ledger: Budget::new(SpendLimits {
+ tokens: None,
+ cost_micros: Some(200),
+ }),
+ call: CallBudget {
+ input_tokens: 1000,
+ output_tokens: 20,
+ cost_micros: 100,
+ },
+ }
+ .wait_for_capacity();
+ let live = policy
+ .ledger
+ .reserve(Spend {
+ tokens: 0,
+ cost_micros: 150,
+ })
+ .unwrap();
+ let make_rung = |server: &MockServer, model: &str| {
+ CompletionRung::new(
+ Completer::new(Route::openai_compatible(
+ format!("{}/v1", server.uri()),
+ "fixture",
+ ))
+ .budget(policy.clone()),
+ model,
+ )
+ };
+ let ladder =
+ CompletionLadder::new(make_rung(&failing, "first")).fallback(make_rung(&healthy, "last"));
+ let mut completion = Box::pin(ladder.complete(
+ CompletionRequest::new("ignored", vec![ChatMessage::user("analysis")]).max_tokens(20),
+ ));
+ assert!(
+ std::future::poll_fn(|cx| std::task::Poll::Ready(std::future::Future::poll(
+ completion.as_mut(),
+ cx
+ )))
+ .await
+ .is_pending()
+ );
+ assert!(failing.received_requests().await.unwrap().is_empty());
+ live.settle(Spend::default());
+ let outcome = completion
+ .await
+ .expect("temporary capacity pressure must not turn RPC failure into BudgetExceeded");
+ assert_eq!(outcome.attempts.len(), 2);
+ assert_eq!(outcome.response.answered_model.as_deref(), Some("healthy"));
+ assert_eq!(policy.ledger.snapshot().spent.cost_micros, 110);
+ assert_eq!(policy.ledger.snapshot().reserved.cost_micros, 0);
+}
+
+#[tokio::test]
+async fn canceled_capacity_wait_does_not_charge_or_suppress_later_fallback() {
+ use openhuman_embed::budget::{Budget, CallBudget, ModelBudget, Spend, SpendLimits};
+ let failing = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .set_body_json(json!({"error":{"message":"fixture rejection"}})),
+ )
+ .mount(&failing)
+ .await;
+ let healthy = scripted(vec![answer("healthy", "stop", 0.000010)]).await;
+ let policy = ModelBudget {
+ ledger: Budget::new(SpendLimits {
+ tokens: None,
+ cost_micros: Some(200),
+ }),
+ call: CallBudget {
+ input_tokens: 1000,
+ output_tokens: 20,
+ cost_micros: 100,
+ },
+ }
+ .wait_for_capacity();
+ let live = policy
+ .ledger
+ .reserve(Spend {
+ tokens: 0,
+ cost_micros: 150,
+ })
+ .unwrap();
+ let make_rung = |server: &MockServer, model: &str| {
+ CompletionRung::new(
+ Completer::new(Route::openai_compatible(
+ format!("{}/v1", server.uri()),
+ "fixture",
+ ))
+ .budget(policy.clone()),
+ model,
+ )
+ };
+ let ladder =
+ CompletionLadder::new(make_rung(&failing, "first")).fallback(make_rung(&healthy, "last"));
+ let request =
+ CompletionRequest::new("ignored", vec![ChatMessage::user("analysis")]).max_tokens(20);
+ let mut completion = Box::pin(ladder.complete(request.clone()));
+ assert!(
+ std::future::poll_fn(|cx| std::task::Poll::Ready(std::future::Future::poll(
+ completion.as_mut(),
+ cx
+ )))
+ .await
+ .is_pending()
+ );
+ drop(completion);
+ assert!(failing.received_requests().await.unwrap().is_empty());
+ assert_eq!(policy.ledger.snapshot().reserved.cost_micros, 150);
+ assert_eq!(policy.ledger.snapshot().spent.cost_micros, 0);
+ live.settle(Spend::default());
+ let outcome = ladder
+ .complete(request)
+ .await
+ .expect("canceling an unadmitted call must not poison later fallback");
+ assert_eq!(outcome.attempts.len(), 2);
+ assert_eq!(policy.ledger.snapshot().spent.cost_micros, 110);
+ assert_eq!(policy.ledger.snapshot().reserved.cost_micros, 0);
+}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index e6be8cf98b..342bf56f06 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit e6be8cf98bfb93d5ecfed0951bf90617ba2ac674
+Subproject commit 342bf56f066cd3a8cdeff45f9a78c5cde4ff517a