swarm-controller: keep the known models in memory, and let the controller watch agent-inference
GET /api/models listed the agent-inference bucket on every request with keys(), which needs the nameless ephemeral consumer subject CONSUMER.CREATE.KV_agent-inference. The controller's NATS grant had that subject for the status, permissions and bash task buckets but not for this one, so NATS refused the create and the client waited out its timeout: the request hung every time. The controller now follows the bucket with a watch that replays each key's current value first, keeps each agent's models in memory beside the reported ones, and answers the request from there without reading the bucket. The grant adds the one create subject the watch needs, with a policy test like the other buckets'.
This commit is contained in:
parent
bceaf31f36
commit
519ed2f134
3 changed files with 184 additions and 44 deletions
|
|
@ -135,7 +135,11 @@ warning in its log, until the next `PUT` replaces it.
|
|||
any agent's stored settings (its model and its subagent models) and in the
|
||||
settings the agents reported running on, sorted. The swarm UI offers them in
|
||||
the model dropdown, so no model name lives in the UI. A swarm where no agent
|
||||
has either answers an empty list.
|
||||
has either answers an empty list. The controller keeps the list in memory: a
|
||||
watch on the `agent-inference` bucket follows every write and delete, and the
|
||||
agents' turn-state headers feed the reported side, so a request reads no bucket
|
||||
and answers at once. A restart refills the stored side from the watch within
|
||||
moments, and the reported side as each agent next publishes, within a minute.
|
||||
|
||||
An agent's own queue credential grants it
|
||||
`$JS.API.DIRECT.GET.KV_agent-inference.$KV.agent-inference.<agent>`, the
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ use std::collections::{BTreeSet, HashMap};
|
|||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_nats::jetstream::kv::Operation;
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
|
|
@ -135,10 +136,15 @@ fn effective_view(v: Effective) -> EffectiveInference {
|
|||
}
|
||||
}
|
||||
|
||||
/// The latest [`Effective`] each agent reported, by agent.
|
||||
/// The latest [`Effective`] each agent reported, by agent, and the models in
|
||||
/// each agent's stored settings.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Reported {
|
||||
latest: Mutex<HashMap<String, Effective>>,
|
||||
/// The models in each agent's stored settings, by agent. A watch on the
|
||||
/// bucket keeps it ([`Reported::follow_stored`]), so `GET /api/models`
|
||||
/// answers from memory and never reads the bucket.
|
||||
stored: Mutex<HashMap<String, Vec<String>>>,
|
||||
/// Each agent's newest header exactly as published, with when it came.
|
||||
raw: Mutex<HashMap<String, (Instant, Vec<u8>)>>,
|
||||
}
|
||||
|
|
@ -148,7 +154,10 @@ impl Reported {
|
|||
pub(crate) fn spawn(client: async_nats::Client) -> Arc<Self> {
|
||||
let reported = Arc::new(Self::default());
|
||||
let recording = Arc::clone(&reported);
|
||||
tokio::spawn(async move { recording.follow(&client).await });
|
||||
let headers = client.clone();
|
||||
tokio::spawn(async move { recording.follow(&headers).await });
|
||||
let watching = Arc::clone(&reported);
|
||||
tokio::spawn(async move { watching.follow_stored(&client).await });
|
||||
reported
|
||||
}
|
||||
|
||||
|
|
@ -172,6 +181,73 @@ impl Reported {
|
|||
}
|
||||
}
|
||||
|
||||
/// Keep the models of every agent's stored settings, and watch the bucket
|
||||
/// again if the watch ends.
|
||||
async fn follow_stored(&self, client: &async_nats::Client) {
|
||||
const RETRY: Duration = Duration::from_secs(5);
|
||||
loop {
|
||||
match self.watch_stored(client).await {
|
||||
Ok(()) => tracing::warn!("inference: settings watch ended"),
|
||||
Err(e) => tracing::warn!(
|
||||
error = %format!("{e:#}"),
|
||||
"inference: settings watch failed"
|
||||
),
|
||||
}
|
||||
tokio::time::sleep(RETRY).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow the bucket until the watch ends. It opens with every key's
|
||||
/// current value, so what an earlier watch kept is dropped first and a
|
||||
/// key deleted while none ran does not linger.
|
||||
async fn watch_stored(&self, client: &async_nats::Client) -> anyhow::Result<()> {
|
||||
let store = agent_inference::open_or_create(client).await?;
|
||||
let mut watch = store.watch_with_history(">").await?;
|
||||
self.stored
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clear();
|
||||
tracing::info!("inference: following the stored settings");
|
||||
while let Some(entry) = watch.next().await {
|
||||
let entry = entry?;
|
||||
self.record_stored(&entry.key, entry.operation, &entry.value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep one agent's stored models: a write replaces them, and a delete,
|
||||
/// a purge or a value that does not decode removes them.
|
||||
fn record_stored(&self, agent: &str, operation: Operation, value: &[u8]) {
|
||||
let mut stored = self.stored.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match operation {
|
||||
Operation::Put => match serde_json::from_slice::<AgentInference>(value) {
|
||||
Ok(settings) => {
|
||||
stored.insert(agent.to_owned(), settings_models(&settings));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(%agent, error = %e, "inference: stored settings do not decode");
|
||||
stored.remove(agent);
|
||||
}
|
||||
},
|
||||
Operation::Delete | Operation::Purge => {
|
||||
stored.remove(agent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every model the swarm knows: those in any agent's stored settings and
|
||||
/// those the agents reported running on, sorted.
|
||||
pub(crate) fn known(&self) -> Vec<String> {
|
||||
let stored = self
|
||||
.stored
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.values()
|
||||
.cloned()
|
||||
.collect();
|
||||
known_models(stored, self.models())
|
||||
}
|
||||
|
||||
/// `agent`'s newest header, as published, when it arrived within `max_age`.
|
||||
/// An older one describes an agent that may have stopped since.
|
||||
pub(crate) fn header_within(&self, agent: &str, max_age: Duration) -> Option<Vec<u8>> {
|
||||
|
|
@ -277,17 +353,22 @@ pub(crate) async fn get_agent_inference(
|
|||
}))
|
||||
}
|
||||
|
||||
/// The distinct model names among `stored` settings and the `reported` ones,
|
||||
/// The model names in one agent's stored settings: its model and its subagent
|
||||
/// models.
|
||||
fn settings_models(settings: &AgentInference) -> Vec<String> {
|
||||
settings
|
||||
.model
|
||||
.iter()
|
||||
.chain(settings.subagent_models.iter().flatten())
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The distinct model names among the `stored` lists and the `reported` ones,
|
||||
/// sorted.
|
||||
fn known_models<'a>(
|
||||
stored: impl IntoIterator<Item = &'a AgentInference>,
|
||||
reported: Vec<String>,
|
||||
) -> Vec<String> {
|
||||
fn known_models(stored: Vec<Vec<String>>, reported: Vec<String>) -> Vec<String> {
|
||||
let mut models: BTreeSet<String> = reported.into_iter().collect();
|
||||
for settings in stored {
|
||||
models.extend(settings.model.iter().cloned());
|
||||
models.extend(settings.subagent_models.iter().flatten().cloned());
|
||||
}
|
||||
models.extend(stored.into_iter().flatten());
|
||||
models.into_iter().filter(|m| !m.is_empty()).collect()
|
||||
}
|
||||
|
||||
|
|
@ -300,36 +381,21 @@ fn known_models<'a>(
|
|||
body = KnownModels),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the settings could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn get_models(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<KnownModels>, ProblemDetails> {
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
let store = open(&client).await?;
|
||||
let mut stored = Vec::new();
|
||||
let mut keys = store
|
||||
.keys()
|
||||
.await
|
||||
.map_err(|e| queue_problem(&anyhow::Error::new(e)))?;
|
||||
while let Some(key) = keys.next().await {
|
||||
let key = key.map_err(|e| queue_problem(&anyhow::Error::new(e)))?;
|
||||
let (current, _, _) = read_or_default::<Option<AgentInference>>(&store, &key)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
stored.extend(current);
|
||||
}
|
||||
let reported = state
|
||||
queue(&state).map_err(refused)?;
|
||||
// Answered from what the controller keeps, never by reading the bucket: a
|
||||
// read of every key per request hung for as long as the queue was slow.
|
||||
let models = state
|
||||
.reported_inference
|
||||
.as_ref()
|
||||
.map(|r| r.models())
|
||||
.map(|reported| reported.known())
|
||||
.unwrap_or_default();
|
||||
Ok(Json(KnownModels {
|
||||
models: known_models(&stored, reported),
|
||||
}))
|
||||
Ok(Json(KnownModels { models }))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
|
|
@ -637,14 +703,41 @@ mod tests {
|
|||
into_stored(settings(r#"{"effort":"high"}"#).unwrap()).unwrap(),
|
||||
into_stored(settings(r#"{"model":"sonnet"}"#).unwrap()).unwrap(),
|
||||
];
|
||||
let stored = stored.iter().map(settings_models).collect();
|
||||
assert_eq!(
|
||||
known_models(
|
||||
&stored,
|
||||
stored,
|
||||
vec!["sonnet".to_owned(), "claude-opus-4-8".to_owned()]
|
||||
),
|
||||
["claude-opus-4-8", "haiku", "opus", "sonnet"]
|
||||
);
|
||||
assert!(known_models(&[], Vec::new()).is_empty());
|
||||
assert!(known_models(Vec::new(), Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
/// A write replaces an agent's stored models; a delete, a purge or a value
|
||||
/// that does not decode removes them.
|
||||
#[test]
|
||||
fn stored_models_follow_the_bucket_writes() {
|
||||
let reported = Reported::default();
|
||||
let put = |agent: &str, json: &str| {
|
||||
reported.record_stored(agent, Operation::Put, json.as_bytes());
|
||||
};
|
||||
put("atlas", r#"{"model":"opus","subagent_models":["haiku"]}"#);
|
||||
put("iris", r#"{"model":"sonnet"}"#);
|
||||
assert_eq!(reported.known(), ["haiku", "opus", "sonnet"]);
|
||||
|
||||
put("atlas", r#"{"model":"opus"}"#);
|
||||
assert_eq!(reported.known(), ["opus", "sonnet"]);
|
||||
|
||||
reported.record_stored("iris", Operation::Delete, b"");
|
||||
assert_eq!(reported.known(), ["opus"]);
|
||||
|
||||
put("atlas", "not json");
|
||||
assert!(reported.known().is_empty());
|
||||
|
||||
put("atlas", r#"{"model":"opus"}"#);
|
||||
reported.record_stored("atlas", Operation::Purge, b"");
|
||||
assert!(reported.known().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -788,20 +881,34 @@ mod tests {
|
|||
assert_eq!(&entry[..], b"{}");
|
||||
}
|
||||
|
||||
/// The list reads every agent's key, counts an undecodable value as no
|
||||
/// settings, and answers an empty list for an empty bucket.
|
||||
/// The models list once the watch has caught up with `want`, or the
|
||||
/// assertion that it never did.
|
||||
async fn listed(state: &AppState, want: &[&str]) {
|
||||
for _ in 0..100 {
|
||||
let list = get_models(State(state.clone())).await.expect("read");
|
||||
if list.0.models == want {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
let list = get_models(State(state.clone())).await.expect("read");
|
||||
assert_eq!(list.0.models, want);
|
||||
}
|
||||
|
||||
/// The list follows the bucket: a key written shows up, a deleted one goes,
|
||||
/// an undecodable value counts as no settings, and an empty bucket answers
|
||||
/// an empty list. It's read from memory, so it waits for the watch to catch up.
|
||||
#[tokio::test]
|
||||
async fn the_models_list_reads_every_key_and_skips_an_undecodable_one() {
|
||||
async fn the_models_list_follows_the_bucket() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let mut state = crate::agent_limits::tests::declared(&client).await;
|
||||
state.reported_inference = Some(Reported::spawn(client.clone()));
|
||||
let store = agent_inference::open_or_create(&client)
|
||||
.await
|
||||
.expect("bucket");
|
||||
|
||||
let none = get_models(State(state.clone())).await.expect("read");
|
||||
assert!(none.0.models.is_empty());
|
||||
|
||||
listed(&state, &[]).await;
|
||||
for (agent, value) in [
|
||||
(
|
||||
"atlas",
|
||||
|
|
@ -815,8 +922,10 @@ mod tests {
|
|||
.await
|
||||
.expect("written");
|
||||
}
|
||||
let list = get_models(State(state)).await.expect("read");
|
||||
assert_eq!(list.0.models, ["haiku", "opus", "sonnet"]);
|
||||
listed(&state, &["haiku", "opus", "sonnet"]).await;
|
||||
|
||||
store.delete("atlas").await.expect("deleted");
|
||||
listed(&state, &["sonnet"]).await;
|
||||
}
|
||||
|
||||
/// `restore` puts back the settings a `store` replaced, or takes the key
|
||||
|
|
|
|||
|
|
@ -857,6 +857,16 @@ impl Policy {
|
|||
"$JS.API.CONSUMER.CREATE.{}",
|
||||
swarm_wire::bash_task::STREAM
|
||||
));
|
||||
// The inference settings, followed by a watch: the controller keeps the
|
||||
// list of models the swarm knows from every write to the bucket. A
|
||||
// watch builds the same nameless ephemeral consumer as `keys()`, so
|
||||
// the bare create subject is the one it needs. Without it the create
|
||||
// request is refused and reaches the client as a timeout, which is
|
||||
// how `GET /api/models` hung every time.
|
||||
subjects.push(format!(
|
||||
"$JS.API.CONSUMER.CREATE.{}",
|
||||
swarm_wire::agent_inference::STREAM
|
||||
));
|
||||
subjects
|
||||
}
|
||||
}
|
||||
|
|
@ -930,6 +940,23 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reader_can_watch_the_agent_inference_bucket_and_no_other_stream() {
|
||||
let subjects = policy().reader_subjects();
|
||||
let s = swarm_wire::agent_inference::STREAM;
|
||||
// The bare form is what a watch or `keys()` needs: its ephemeral
|
||||
// consumer has no name.
|
||||
assert!(subjects.contains(&format!("$JS.API.CONSUMER.CREATE.{s}")));
|
||||
// Negative controls: the grant names this one stream, and holds no
|
||||
// wildcard or `.>` form for it.
|
||||
assert!(!subjects.contains(&"$JS.API.CONSUMER.CREATE.*".to_owned()));
|
||||
assert!(!subjects.contains(&format!("$JS.API.CONSUMER.CREATE.{s}.>")));
|
||||
assert!(
|
||||
!subjects.contains(&"$JS.API.CONSUMER.CREATE.KV_unrelated".to_owned()),
|
||||
"an unrelated stream must not be creatable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reader_can_list_the_bash_task_statuses_and_no_other_stream() {
|
||||
let subjects = policy().reader_subjects();
|
||||
|
|
|
|||
Loading…
Reference in a new issue