diff --git a/crates/aether-core/src/limits.rs b/crates/aether-core/src/limits.rs index 21b834b..b1a4f7c 100644 --- a/crates/aether-core/src/limits.rs +++ b/crates/aether-core/src/limits.rs @@ -2,13 +2,84 @@ use crate::named; +/// The limits of the task queue and of the tasks that run from it. #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum QueueLimitId { + /// How many tasks wait in all. Global, + /// How many tasks wait for each caller endpoint. PerPeer, + /// How many tasks this node runs at once, for all callers together. + Running, } named!(QueueLimitId { Global => "queue_global", PerPeer => "queue_per_peer", + Running => "running_tasks", }); + +impl QueueLimitId { + /// Every limit, in the order that the node shows them. + pub const ALL: [Self; 3] = [Self::Global, Self::PerPeer, Self::Running]; + + /// The smallest value that the owner can set. + #[must_use] + pub const fn minimum(self) -> u32 { + 1 + } + + /// The largest value that the owner can set. `None`: no fixed maximum. + #[must_use] + pub const fn maximum(self) -> Option { + match self { + Self::Global | Self::PerPeer => None, + Self::Running => Some(MAX_RUNNING_TASKS), + } + } + + /// Whether the owner can set this limit to `value`. + #[must_use] + pub fn accepts(self, value: u32) -> bool { + value >= self.minimum() && self.maximum().is_none_or(|maximum| value <= maximum) + } +} + +/// How many tasks a node runs at once unless its owner sets more. One keeps +/// the behavior of a node before the limit existed. +pub const DEFAULT_RUNNING_TASKS: u32 = 1; + +/// The most tasks that the owner can let a node run at once. +/// +/// Each running task is a turn of the agent (for Codex its own +/// `codex app-server` process and task folder) with a lease-renewal thread, +/// and every store write of the running tasks goes through one connection. +/// 32 is far above what one computer's agent runs well, and it keeps a +/// typing mistake from starting hundreds of processes. +pub const MAX_RUNNING_TASKS: u32 = 32; + +#[cfg(test)] +mod tests { + use super::{MAX_RUNNING_TASKS, QueueLimitId}; + + #[test] + fn the_running_limit_has_a_floor_and_a_ceiling() { + assert!(!QueueLimitId::Running.accepts(0)); + assert!(QueueLimitId::Running.accepts(1)); + assert!(QueueLimitId::Running.accepts(MAX_RUNNING_TASKS)); + assert!(!QueueLimitId::Running.accepts(MAX_RUNNING_TASKS.saturating_add(1))); + } + + #[test] + fn a_queue_limit_has_only_a_floor() { + assert!(!QueueLimitId::Global.accepts(0)); + assert!(QueueLimitId::PerPeer.accepts(u32::MAX)); + } + + #[test] + fn every_limit_has_its_own_name() { + for id in QueueLimitId::ALL { + assert_eq!(QueueLimitId::parse(id.as_str()), Some(id)); + } + } +} diff --git a/crates/aether-store/src/access_groups.rs b/crates/aether-store/src/access_groups.rs index fa1cf86..4ff9602 100644 --- a/crates/aether-store/src/access_groups.rs +++ b/crates/aether-store/src/access_groups.rs @@ -1,5 +1,6 @@ use rusqlite::params; +use crate::CachedSql; use crate::{NodeStore, StoreError}; /// The default group of direct contacts. Migration 011 makes it. @@ -28,7 +29,7 @@ pub struct AccessGroupMember { impl NodeStore { pub fn create_access_group(&self, name: &str) -> Result<(), StoreError> { self.connection - .execute("INSERT INTO access_groups(name) VALUES (?1)", [name])?; + .execute_cached("INSERT INTO access_groups(name) VALUES (?1)", [name])?; Ok(()) } @@ -39,19 +40,19 @@ impl NodeStore { identities: &[(String, String)], ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; - let initialized: bool = transaction.query_row( + let initialized: bool = transaction.query_row_cached( "SELECT EXISTS(SELECT 1 FROM configuration WHERE key=?1)", [INITIALIZED_KEY], |row| row.get(0), )?; if !initialized { for (agent, endpoint) in identities { - transaction.execute( + transaction.execute_cached( "INSERT OR IGNORE INTO access_group_members(group_name,agent_id,endpoint_id) VALUES (?1,?2,?3)", params![FRIENDS_GROUP, agent, endpoint], )?; } - transaction.execute( + transaction.execute_cached( "INSERT INTO configuration(key,value) VALUES (?1,'1')", [INITIALIZED_KEY], )?; @@ -61,7 +62,9 @@ impl NodeStore { } pub fn delete_access_group(&self, name: &str) -> Result<(), StoreError> { - if self.connection.execute("DELETE FROM access_groups WHERE name=?1", [name])? + if self + .connection + .execute_cached("DELETE FROM access_groups WHERE name=?1", [name])? == 0 { return Err(StoreError::NotFound); @@ -75,14 +78,14 @@ impl NodeStore { agent_id: &str, endpoint_id: &str, ) -> Result<(), StoreError> { - if !self.connection.query_row( + if !self.connection.query_row_cached( "SELECT EXISTS(SELECT 1 FROM access_groups WHERE name=?1)", [group], |row| row.get::<_, bool>(0), )? { return Err(StoreError::NotFound); } - self.connection.execute( + self.connection.execute_cached( "INSERT OR IGNORE INTO access_group_members(group_name,agent_id,endpoint_id) VALUES (?1,?2,?3)", params![group, agent_id, endpoint_id], )?; @@ -95,7 +98,7 @@ impl NodeStore { agent_id: &str, endpoint_id: &str, ) -> Result<(), StoreError> { - if self.connection.execute( + if self.connection.execute_cached( "DELETE FROM access_group_members WHERE group_name=?1 AND agent_id=?2 AND endpoint_id=?3", params![group, agent_id, endpoint_id], )? == 0 { @@ -109,7 +112,7 @@ impl NodeStore { agent_id: &str, endpoint_id: &str, ) -> Result { - self.connection.query_row( + self.connection.query_row_cached( "SELECT EXISTS(SELECT 1 FROM access_group_members WHERE agent_id=?1 AND endpoint_id=?2)", params![agent_id, endpoint_id], |row| row.get(0), @@ -117,9 +120,10 @@ impl NodeStore { } pub fn access_groups(&self) -> Result, StoreError> { - let mut groups = - self.connection.prepare("SELECT name FROM access_groups ORDER BY name")?; - let mut members = self.connection.prepare( + let mut groups = self + .connection + .prepare_cached("SELECT name FROM access_groups ORDER BY name")?; + let mut members = self.connection.prepare_cached( "SELECT agent_id,endpoint_id FROM access_group_members WHERE group_name=?1 ORDER BY agent_id,endpoint_id", )?; groups diff --git a/crates/aether-store/src/admin.rs b/crates/aether-store/src/admin.rs index d4187f8..7ae5d44 100644 --- a/crates/aether-store/src/admin.rs +++ b/crates/aether-store/src/admin.rs @@ -6,6 +6,7 @@ use std::collections::BTreeMap; use rusqlite::{Connection, OptionalExtension, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, config, now, sql_count, sql_named}; /// The kind of an admin change. The names are the @@ -140,7 +141,7 @@ fn audit( actor: AuditActor, result: AuditResult, ) -> Result { - connection.execute( + connection.execute_cached( "INSERT INTO audit_records(actor_type,action,result,created_at) VALUES(?1,?2,?3,?4)", params![actor, AuditAction::Change, result, now()], )?; @@ -177,13 +178,13 @@ fn keep_change( fn delete_expired(transaction: &Connection) -> Result<(), StoreError> { let expired = { let mut statement = transaction - .prepare("SELECT id FROM pending_changes WHERE expires_at<=?1")?; + .prepare_cached("SELECT id FROM pending_changes WHERE expires_at<=?1")?; statement .query_map([now()], |row| row.get::<_, String>(0))? .collect::, _>>()? }; for id in expired { - transaction.execute("DELETE FROM pending_changes WHERE id=?1", [&id])?; + transaction.execute_cached("DELETE FROM pending_changes WHERE id=?1", [&id])?; config::delete(transaction, &pending_revision_key(&id))?; } Ok(()) @@ -257,7 +258,7 @@ impl NodeStore { ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; delete_expired(&transaction)?; - transaction.execute( + transaction.execute_cached( "INSERT INTO pending_changes(id,change_type,value,expires_at) VALUES(?1,?2,?3,?4)", params![id, kind, value, expires_at], )?; @@ -286,7 +287,7 @@ impl NodeStore { /// Marks the audit record `audit` as failed. pub fn fail_change(&self, audit: i64) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "UPDATE audit_records SET result=?1 WHERE id=?2", params![AuditResult::Failed, audit], )?; @@ -320,7 +321,7 @@ impl NodeStore { None => config::delete(&transaction, CURRENT_WORKSPACE_KEY)?, } } - transaction.execute( + transaction.execute_cached( "UPDATE audit_records SET result=?1 WHERE id=?2", params![AuditResult::Failed, replaced.audit], )?; @@ -339,7 +340,7 @@ impl NodeStore { ) -> Result { let transaction = self.connection.transaction()?; let (kind, value, expires_at): (ChangeKind, String, i64) = transaction - .query_row( + .query_row_cached( "SELECT change_type,value,expires_at FROM pending_changes WHERE id=?1", [id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), @@ -351,7 +352,7 @@ impl NodeStore { transaction.commit()?; return Err(StoreError::InvalidState); } - transaction.execute("DELETE FROM pending_changes WHERE id=?1", [id])?; + transaction.execute_cached("DELETE FROM pending_changes WHERE id=?1", [id])?; config::delete(&transaction, &pending_revision_key(id))?; audit(&transaction, AuditActor::Ui, AuditResult::Confirmed)?; let replaced = @@ -361,7 +362,7 @@ impl NodeStore { } pub fn pending_changes(&self) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT id,change_type,value FROM pending_changes WHERE expires_at>?1 ORDER BY id", )?; Ok(statement @@ -375,7 +376,7 @@ impl NodeStore { id: &str, ) -> Result { self.connection - .query_row( + .query_row_cached( "SELECT id,change_type,value FROM pending_changes WHERE id=?1", [id], PendingChange::from_row, @@ -420,7 +421,7 @@ impl NodeStore { skip: usize, limit: usize, ) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT actor_type,action,result FROM audit_records ORDER BY id LIMIT ?1 OFFSET ?2", )?; Ok(statement @@ -439,7 +440,7 @@ impl NodeStore { &self, ) -> Result { self.connection - .execute( + .execute_cached( "INSERT INTO audit_records(actor_type,action,result,created_at) VALUES('mcp','change','private-credential',0)", [], ) diff --git a/crates/aether-store/src/config.rs b/crates/aether-store/src/config.rs index 627cfde..fe60e00 100644 --- a/crates/aether-store/src/config.rs +++ b/crates/aether-store/src/config.rs @@ -6,18 +6,21 @@ use rusqlite::{Connection, OptionalExtension, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError}; pub fn get(connection: &Connection, key: &str) -> Result, StoreError> { Ok(connection - .query_row("SELECT value FROM configuration WHERE key=?1", [key], |row| { - row.get(0) - }) + .query_row_cached( + "SELECT value FROM configuration WHERE key=?1", + [key], + |row| row.get(0), + ) .optional()?) } pub fn put(connection: &Connection, key: &str, value: &str) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( "INSERT INTO configuration(key,value) VALUES(?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value", params![key, value], )?; @@ -26,7 +29,7 @@ pub fn put(connection: &Connection, key: &str, value: &str) -> Result<(), StoreE /// Removing a key that is not there is not an error. pub fn delete(connection: &Connection, key: &str) -> Result<(), StoreError> { - connection.execute("DELETE FROM configuration WHERE key=?1", [key])?; + connection.execute_cached("DELETE FROM configuration WHERE key=?1", [key])?; Ok(()) } @@ -35,7 +38,7 @@ pub fn values( connection: &Connection, prefix: &str, ) -> Result, StoreError> { - let mut statement = connection.prepare( + let mut statement = connection.prepare_cached( "SELECT value FROM configuration WHERE substr(key,1,length(?1))=?1 ORDER BY key", )?; Ok(statement.query_map([prefix], |row| row.get(0))?.collect::>()?) @@ -43,7 +46,7 @@ pub fn values( /// How many keys start with `prefix`. pub fn count(connection: &Connection, prefix: &str) -> Result { - let count: i64 = connection.query_row( + let count: i64 = connection.query_row_cached( "SELECT COUNT(*) FROM configuration WHERE substr(key,1,length(?1))=?1", [prefix], |row| row.get(0), @@ -90,8 +93,9 @@ mod tests { store.configuration_values("caller.card.").expect("values must load"), ["a", "b"] ); - assert!( - store.configuration_values("CALLER.").expect("values must load").is_empty() + assert_eq!( + store.configuration_values("CALLER.").expect("values must load"), + Vec::::new() ); } } diff --git a/crates/aether-store/src/control.rs b/crates/aether-store/src/control.rs index 86ea0d0..0a79ed5 100644 --- a/crates/aether-store/src/control.rs +++ b/crates/aether-store/src/control.rs @@ -6,6 +6,7 @@ use std::path::Path; use aether_core::ScopeKind; use rusqlite::{Connection, OptionalExtension, params}; +use crate::CachedSql; use crate::{ ManagedMember, SignedRecord, StoreError, directory::{RECORD_COLUMNS, upsert_record}, @@ -98,7 +99,7 @@ impl ControlStore { } let transaction = self.connection.transaction()?; let revoked_through: Option = transaction - .query_row( + .query_row_cached( "SELECT revoked_through FROM directory_record_marks WHERE agent_id=?1 AND signing_key=?2", params![record.agent_id, signing_key], |row| row.get(0), @@ -111,7 +112,7 @@ impl ControlStore { put_scope(&transaction, &record.scope_id, ScopeKind::Directory)?; upsert_record(&transaction, &record.agent_id, record)?; mark_latest(&transaction, &record.agent_id, signing_key, record.expires_at)?; - transaction.execute( + transaction.execute_cached( "INSERT INTO directory_events(event_type,scope_id,agent_id,record,created_at) VALUES(?1,?2,?3,?4,?5)", params![event, record.scope_id, record.agent_id, record.record, now()], )?; @@ -121,7 +122,7 @@ impl ControlStore { pub fn signed_record(&self, agent_id: &str) -> Result { self.connection - .query_row( + .query_row_cached( &format!( "SELECT {RECORD_COLUMNS} FROM signed_records WHERE agent_id=?1 ORDER BY expires_at DESC LIMIT 1" ), @@ -142,22 +143,24 @@ impl ControlStore { ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; let (scope_id, expires_at): (String, i64) = transaction - .query_row( + .query_row_cached( "SELECT scope_id,expires_at FROM signed_records WHERE agent_id=?1 ORDER BY expires_at DESC LIMIT 1", [agent_id], |row| Ok((row.get(0)?, row.get(1)?)), ) .optional()? .ok_or(StoreError::NotFound)?; - transaction - .execute("DELETE FROM signed_records WHERE agent_id=?1", [agent_id])?; + transaction.execute_cached( + "DELETE FROM signed_records WHERE agent_id=?1", + [agent_id], + )?; // A record from before the marks table has no mark yet. mark_latest(&transaction, agent_id, signing_key, expires_at)?; - transaction.execute( + transaction.execute_cached( "UPDATE directory_record_marks SET revoked_through=latest_expires_at WHERE agent_id=?1 AND signing_key=?2", params![agent_id, signing_key], )?; - transaction.execute( + transaction.execute_cached( "INSERT INTO directory_events(event_type,scope_id,agent_id,record,created_at) VALUES(?1,?2,?3,NULL,?4)", params![DirectoryEventType::Revoked, scope_id, agent_id, now()], )?; @@ -169,7 +172,7 @@ impl ControlStore { &self, timestamp: i64, ) -> Result, StoreError> { - let mut statement = self.connection.prepare(&format!( + let mut statement = self.connection.prepare_cached(&format!( "SELECT {RECORD_COLUMNS} FROM signed_records WHERE expires_at>?1 ORDER BY agent_id" ))?; Ok(statement @@ -185,7 +188,7 @@ impl ControlStore { if sequence < 0 || limit == 0 { return Err(StoreError::InvalidState); } - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT sequence,event_type,scope_id,agent_id,record FROM directory_events WHERE sequence>?1 ORDER BY sequence LIMIT ?2", )?; Ok(statement @@ -213,7 +216,7 @@ impl ControlStore { } let transaction = self.connection.transaction()?; ensure_scope(&transaction, scope_id, ScopeKind::Managed)?; - transaction.execute( + transaction.execute_cached( "INSERT INTO managed_invitations(id,scope_id,token_hash,expires_at) VALUES(?1,?2,?3,?4)", params![id, scope_id, token_hash, expires_at], )?; @@ -229,18 +232,18 @@ impl ControlStore { let timestamp = now(); member.check_new(timestamp)?; let transaction = self.connection.transaction()?; - let changed = transaction.execute( + let changed = transaction.execute_cached( "UPDATE managed_invitations SET redeemed_at=?1,redeemed_agent_id=?2 WHERE token_hash=?3 AND redeemed_at IS NULL AND expires_at>?1 AND scope_id=?4", params![timestamp, member.agent_id, token_hash, member.scope_id], )?; if changed != 1 { return Err(StoreError::NotFound); } - transaction.execute( + transaction.execute_cached( "INSERT INTO managed_members(scope_id,agent_id,endpoint_id,role,expires_at,revoked_at) VALUES(?1,?2,?3,?4,?5,NULL)", params![member.scope_id, member.agent_id, member.endpoint_id, member.role, member.expires_at], )?; - transaction.execute( + transaction.execute_cached( "INSERT INTO managed_events(event_type,scope_id,agent_id,endpoint_id,role,expires_at,created_at) VALUES(?1,?2,?3,?4,?5,?6,?7)", params![ManagedEventType::Joined, member.scope_id, member.agent_id, member.endpoint_id, member.role, member.expires_at, timestamp], )?; @@ -258,13 +261,13 @@ impl ControlStore { } let timestamp = now(); let transaction = self.connection.transaction()?; - if transaction.execute( + if transaction.execute_cached( "UPDATE managed_members SET revoked_at=?1 WHERE scope_id=?2 AND agent_id=?3 AND revoked_at IS NULL", params![timestamp, scope_id, agent_id], )? != 1 { return Err(StoreError::NotFound); } - transaction.execute( + transaction.execute_cached( "INSERT INTO managed_events(event_type,scope_id,agent_id,endpoint_id,role,expires_at,created_at) VALUES(?1,?2,?3,NULL,NULL,NULL,?4)", params![ManagedEventType::Revoked, scope_id, agent_id, timestamp], )?; @@ -288,7 +291,7 @@ impl ControlStore { if scope_id.is_empty() || sequence < 0 || limit == 0 { return Err(StoreError::InvalidState); } - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT sequence,event_type,scope_id,agent_id,endpoint_id,role,expires_at FROM managed_events WHERE scope_id=?1 AND sequence>?2 ORDER BY sequence LIMIT ?3", )?; Ok(statement @@ -325,7 +328,7 @@ fn mark_latest( signing_key: &[u8; 32], expires_at: i64, ) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( "INSERT INTO directory_record_marks(agent_id,signing_key,latest_expires_at) VALUES(?1,?2,?3) ON CONFLICT(agent_id,signing_key) DO UPDATE SET latest_expires_at=MAX(latest_expires_at,excluded.latest_expires_at)", params![agent_id, signing_key, expires_at], @@ -411,7 +414,10 @@ mod tests { let mut store = ControlStore::open(&database).expect("control must reopen"); assert_eq!(store.signed_record("agent"), Ok(record("agent", 2))); assert_eq!(store.active_signed_records(1).expect("records must load").len(), 1); - assert!(store.active_signed_records(2).expect("records must load").is_empty()); + assert_eq!( + store.active_signed_records(2).expect("records must load"), + Vec::new() + ); store.revoke_signed_record("agent", &KEY).expect("record must revoke"); assert_eq!(store.signed_record("agent"), Err(StoreError::NotFound)); assert_eq!( diff --git a/crates/aether-store/src/directory.rs b/crates/aether-store/src/directory.rs index ce86cda..cb70791 100644 --- a/crates/aether-store/src/directory.rs +++ b/crates/aether-store/src/directory.rs @@ -6,6 +6,7 @@ use aether_core::ScopeKind; use rusqlite::{Connection, OptionalExtension, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, ensure_scope, managed, put_scope}; #[derive(Debug, Clone, Eq, PartialEq)] @@ -36,7 +37,7 @@ pub fn upsert_record( id: &str, record: &SignedRecord, ) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( &format!( "INSERT INTO signed_records(id,{RECORD_COLUMNS}) VALUES(?1,?2,?3,?4,?5) ON CONFLICT(id) DO UPDATE SET scope_id=excluded.scope_id,agent_id=excluded.agent_id,record=excluded.record,expires_at=excluded.expires_at" @@ -76,10 +77,10 @@ impl NodeStore { /// [`StoreError::NotFound`] when there is no contact `agent_id`. pub fn remove_contact_record(&self, agent_id: &str) -> Result<(), StoreError> { - match self - .connection - .execute("DELETE FROM signed_records WHERE id=?1", [contact_id(agent_id)])? - { + match self.connection.execute_cached( + "DELETE FROM signed_records WHERE id=?1", + [contact_id(agent_id)], + )? { 0 => Err(StoreError::NotFound), _ => Ok(()), } @@ -115,7 +116,7 @@ impl NodeStore { scope_id: &str, agent_id: &str, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( "UPDATE signed_records SET expires_at=0 WHERE id=?1 AND expires_at<>0", [directory_id(scope_id, agent_id)], )? != 0) @@ -147,7 +148,7 @@ impl NodeStore { /// The records that have not expired at `now`. pub fn live_record_count(&self, now: i64) -> Result { - let count: i64 = self.connection.query_row( + let count: i64 = self.connection.query_row_cached( "SELECT COUNT(*) FROM signed_records WHERE expires_at>?1", [now], |row| row.get(0), @@ -157,7 +158,7 @@ impl NodeStore { fn record(&self, id: &str) -> Result { self.connection - .query_row( + .query_row_cached( &format!("SELECT {RECORD_COLUMNS} FROM signed_records WHERE id=?1"), [id], SignedRecord::from_row, diff --git a/crates/aether-store/src/hub.rs b/crates/aether-store/src/hub.rs index fff9833..db5e28f 100644 --- a/crates/aether-store/src/hub.rs +++ b/crates/aether-store/src/hub.rs @@ -1,5 +1,6 @@ use rusqlite::{OptionalExtension, TransactionBehavior, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, sql_named}; /// The side of a hub invite that this node's page acted on. The strings are @@ -78,7 +79,7 @@ pub const MAX_ACCESS_REQUEST_DRAFTS: i64 = 5; impl NodeStore { /// Keeps `approval`, in place of a record with the same invite id. pub fn put_hub_approval(&self, approval: &HubApproval) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT OR REPLACE INTO hub_approvals(invite_id,side,kind,peer_name,peer_endpoint,days,access_group,bundle,created_at,expires_at,listing,listing_signature,listing_expires_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13)", params![ approval.invite_id, @@ -105,7 +106,7 @@ impl NodeStore { ) -> Result, StoreError> { Ok(self .connection - .query_row( + .query_row_cached( "SELECT invite_id,side,kind,peer_name,peer_endpoint,days,access_group,bundle,created_at,expires_at,listing,listing_signature,listing_expires_at FROM hub_approvals WHERE invite_id=?1", [invite_id], |row| { @@ -145,7 +146,7 @@ impl NodeStore { bundle: &str, ) -> Result<(), StoreError> { let invite_id = approval.invite_id.as_str(); - let changed = self.connection.execute( + let changed = self.connection.execute_cached( "UPDATE hub_approvals SET peer_endpoint=?2, bundle=?3 WHERE invite_id=?1 AND peer_name=?4 AND created_at=?5 AND (peer_endpoint IS NULL OR peer_endpoint=?2)", params![invite_id, endpoint, bundle, approval.peer_name, approval.created_at], )?; @@ -161,17 +162,20 @@ impl NodeStore { /// Removes the approval of `invite_id`. Removing one that is not there is /// not an error. pub fn remove_hub_approval(&self, invite_id: &str) -> Result<(), StoreError> { - self.connection - .execute("DELETE FROM hub_approvals WHERE invite_id=?1", [invite_id])?; + self.connection.execute_cached( + "DELETE FROM hub_approvals WHERE invite_id=?1", + [invite_id], + )?; Ok(()) } /// Removes every approval that expired at Unix time `now`, and returns /// how many it removed. pub fn clear_expired_hub_approvals(&self, now: i64) -> Result { - Ok(self - .connection - .execute("DELETE FROM hub_approvals WHERE expires_at <= ?1", [now])?) + Ok(self.connection.execute_cached( + "DELETE FROM hub_approvals WHERE expires_at <= ?1", + [now], + )?) } /// Keeps a draft that waits for the person. [`StoreError::Overloaded`] @@ -184,7 +188,7 @@ impl NodeStore { let transaction = self .connection .transaction_with_behavior(TransactionBehavior::Immediate)?; - let open: i64 = transaction.query_row( + let open: i64 = transaction.query_row_cached( "SELECT COUNT(*) FROM access_request_drafts WHERE expires_at > ?1", [draft.created_at], |row| row.get(0), @@ -192,11 +196,11 @@ impl NodeStore { if open >= MAX_ACCESS_REQUEST_DRAFTS { return Err(StoreError::Overloaded); } - transaction.execute( + transaction.execute_cached( "DELETE FROM access_request_drafts WHERE expires_at <= ?1", [draft.created_at], )?; - let inserted = transaction.execute( + let inserted = transaction.execute_cached( "INSERT OR IGNORE INTO access_request_drafts(id,target_name,listing,signature,listing_expires_at,days,created_at,expires_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)", params![ draft.id, @@ -221,7 +225,7 @@ impl NodeStore { &self, now: i64, ) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT id,target_name,listing,signature,listing_expires_at,days,created_at,expires_at FROM access_request_drafts WHERE expires_at > ?1 ORDER BY created_at, id", )?; let drafts = statement @@ -236,7 +240,7 @@ impl NodeStore { ) -> Result, StoreError> { Ok(self .connection - .query_row( + .query_row_cached( "SELECT id,target_name,listing,signature,listing_expires_at,days,created_at,expires_at FROM access_request_drafts WHERE id=?1", [id], draft_from_row, @@ -248,14 +252,14 @@ impl NodeStore { /// error. pub fn remove_access_request_draft(&self, id: &str) -> Result<(), StoreError> { self.connection - .execute("DELETE FROM access_request_drafts WHERE id=?1", [id])?; + .execute_cached("DELETE FROM access_request_drafts WHERE id=?1", [id])?; Ok(()) } /// Whether this node asked the agent `name` for access, or prepared a /// request to it, and the request is open at Unix time `now`. pub fn access_requested(&self, name: &str, now: i64) -> Result { - Ok(self.connection.query_row( + Ok(self.connection.query_row_cached( "SELECT EXISTS(SELECT 1 FROM access_request_drafts WHERE target_name=?1 AND expires_at > ?2) OR EXISTS(SELECT 1 FROM hub_approvals WHERE peer_name=?1 AND side=?3 AND kind=?4 AND expires_at > ?2)", params![name, now, ApprovalSide::Receiver, ApprovalKind::Request], |row| row.get(0), @@ -270,7 +274,7 @@ impl NodeStore { name: &str, now: i64, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT OR IGNORE INTO hub_blocks(endpoint,name,created_at) VALUES (?1,?2,?3)", params![endpoint, name, now], )?; @@ -278,7 +282,7 @@ impl NodeStore { } pub fn hub_blocked(&self, endpoint: &str) -> Result { - Ok(self.connection.query_row( + Ok(self.connection.query_row_cached( "SELECT EXISTS(SELECT 1 FROM hub_blocks WHERE endpoint=?1)", [endpoint], |row| row.get(0), @@ -289,7 +293,7 @@ impl NodeStore { /// an error. pub fn remove_hub_block(&self, endpoint: &str) -> Result<(), StoreError> { self.connection - .execute("DELETE FROM hub_blocks WHERE endpoint=?1", [endpoint])?; + .execute_cached("DELETE FROM hub_blocks WHERE endpoint=?1", [endpoint])?; Ok(()) } } diff --git a/crates/aether-store/src/lib.rs b/crates/aether-store/src/lib.rs index 61e4c8d..227c924 100644 --- a/crates/aether-store/src/lib.rs +++ b/crates/aether-store/src/lib.rs @@ -100,6 +100,50 @@ impl PartialEq for StoreError { impl Eq for StoreError {} +/// Statements that the connection prepares once and keeps, so a hot path +/// does not parse its SQL on every call. Each statement text is one cache +/// entry, so the text must not carry values; bind them as parameters. +pub(crate) trait CachedSql { + fn execute_cached( + &self, + sql: &str, + params: P, + ) -> rusqlite::Result; + + fn query_row_cached( + &self, + sql: &str, + params: P, + map: F, + ) -> rusqlite::Result + where + P: rusqlite::Params, + F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result; +} + +impl CachedSql for Connection { + fn execute_cached( + &self, + sql: &str, + params: P, + ) -> rusqlite::Result { + self.prepare_cached(sql)?.execute(params) + } + + fn query_row_cached( + &self, + sql: &str, + params: P, + map: F, + ) -> rusqlite::Result + where + P: rusqlite::Params, + F: FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result, + { + self.prepare_cached(sql)?.query_row(params, map) + } +} + pub struct NodeStore { pub(crate) connection: Connection, } @@ -113,6 +157,16 @@ impl NodeStore { Self::open(dir.join(NODE_DATABASE)) } + /// Whether the database has exactly the migrations that this binary + /// knows: one cheap `PRAGMA user_version`. A store that stays open checks + /// this before a use, because another binary can migrate the file after + /// the open. When it is `false` (or the read fails), open the file again: + /// [`NodeStore::open`] migrates an older schema and refuses a newer one. + #[must_use] + pub fn schema_is_current(&self) -> bool { + migrate::schema_is_latest(&self.connection, NODE_MIGRATIONS).unwrap_or(false) + } + pub fn put_scope(&self, id: &str, kind: ScopeKind) -> Result<(), StoreError> { put_scope(&self.connection, id, kind) } @@ -123,7 +177,7 @@ pub(crate) fn put_scope( id: &str, kind: ScopeKind, ) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( "INSERT INTO scopes(id,kind) VALUES(?1,?2) ON CONFLICT(id) DO UPDATE SET kind=excluded.kind", params![id, kind.as_str()], )?; @@ -137,12 +191,12 @@ pub(crate) fn ensure_scope( id: &str, kind: ScopeKind, ) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( "INSERT INTO scopes(id,kind) VALUES(?1,?2) ON CONFLICT(id) DO NOTHING", params![id, kind.as_str()], )?; let stored: Option = connection - .query_row("SELECT kind FROM scopes WHERE id=?1", [id], |row| row.get(0)) + .query_row_cached("SELECT kind FROM scopes WHERE id=?1", [id], |row| row.get(0)) .optional()?; if stored.as_deref() == Some(kind.as_str()) { Ok(()) diff --git a/crates/aether-store/src/managed.rs b/crates/aether-store/src/managed.rs index 12433ad..05b558b 100644 --- a/crates/aether-store/src/managed.rs +++ b/crates/aether-store/src/managed.rs @@ -1,6 +1,7 @@ use aether_core::ScopeKind; use rusqlite::{Connection, OptionalExtension, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, ensure_scope, now}; /// A member of a managed scope. Its JSON form is the control service wire @@ -61,7 +62,7 @@ pub fn members_in_scope( if scope_id.is_empty() { return Err(StoreError::InvalidState); } - let mut statement = connection.prepare(&format!( + let mut statement = connection.prepare_cached(&format!( "SELECT {MEMBER_COLUMNS} FROM managed_members WHERE scope_id=?1 ORDER BY agent_id" ))?; Ok(statement @@ -105,7 +106,7 @@ impl NodeStore { let transaction = self.connection.transaction()?; advance_cursor(&transaction, &cursor_key(control, &member.scope_id), cursor)?; ensure_scope(&transaction, &member.scope_id, ScopeKind::Managed)?; - transaction.execute( + transaction.execute_cached( &format!( "INSERT INTO managed_members({MEMBER_COLUMNS}) VALUES(?1,?2,?3,?4,?5,NULL) ON CONFLICT(scope_id,agent_id) DO UPDATE SET endpoint_id=excluded.endpoint_id,role=excluded.role,expires_at=excluded.expires_at @@ -133,7 +134,7 @@ impl NodeStore { } let transaction = self.connection.transaction()?; advance_cursor(&transaction, &cursor_key(control, scope_id), cursor)?; - if transaction.execute( + if transaction.execute_cached( "UPDATE managed_members SET revoked_at=COALESCE(revoked_at,?1) WHERE scope_id=?2 AND agent_id=?3", params![now(), scope_id, agent_id], )? != 1 { @@ -153,7 +154,7 @@ impl NodeStore { /// The members of every managed scope who are not revoked and have not /// expired at `now`. pub fn active_member_count(&self, now: i64) -> Result { - let count: i64 = self.connection.query_row( + let count: i64 = self.connection.query_row_cached( "SELECT COUNT(*) FROM managed_members WHERE expires_at>?1 AND revoked_at IS NULL", [now], |row| row.get(0), @@ -162,7 +163,7 @@ impl NodeStore { } pub fn all_managed_members(&self) -> Result, StoreError> { - let mut statement = self.connection.prepare(&format!( + let mut statement = self.connection.prepare_cached(&format!( "SELECT {MEMBER_COLUMNS} FROM managed_members ORDER BY scope_id,agent_id" ))?; Ok(statement @@ -174,9 +175,11 @@ impl NodeStore { /// The cursor kept under `key`; 0 when there is none. pub fn cursor(connection: &Connection, key: &str) -> Result { let stored: Option = connection - .query_row("SELECT value FROM configuration WHERE key=?1", [key], |row| { - row.get(0) - }) + .query_row_cached( + "SELECT value FROM configuration WHERE key=?1", + [key], + |row| row.get(0), + ) .optional()?; match stored { None => Ok(0), @@ -197,7 +200,7 @@ pub fn advance_cursor( if next <= cursor(connection, key)? { return Err(StoreError::InvalidState); } - connection.execute( + connection.execute_cached( "INSERT INTO configuration(key,value) VALUES(?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value", params![key, next.to_string()], )?; diff --git a/crates/aether-store/src/migrate.rs b/crates/aether-store/src/migrate.rs index 999dc7c..c400add 100644 --- a/crates/aether-store/src/migrate.rs +++ b/crates/aether-store/src/migrate.rs @@ -12,6 +12,10 @@ use crate::{StoreError, now}; pub const BACKUP_RETENTION: usize = 3; +/// How many prepared statements a connection keeps. The node store has +/// about a hundred statements; the default of 16 would evict them in turn. +const STATEMENT_CACHE: usize = 256; + /// The database files that this process has migrated and checked. static MIGRATED: LazyLock>> = LazyLock::new(Mutex::default); @@ -25,6 +29,7 @@ pub fn open_connection( migrations: &[&str], ) -> Result { let mut connection = Connection::open(path)?; + connection.set_prepared_statement_cache_capacity(STATEMENT_CACHE); connection.busy_timeout(std::time::Duration::from_secs(1))?; connection.pragma_update(None, "foreign_keys", "ON")?; connection.pragma_update_and_check(None, "journal_mode", "WAL", |row| { @@ -52,7 +57,7 @@ fn migrated() -> MutexGuard<'static, HashSet> { } /// Whether the database at `connection` has every one of `migrations`. -fn schema_is_latest( +pub fn schema_is_latest( connection: &Connection, migrations: &[&str], ) -> Result { @@ -222,7 +227,7 @@ mod tests { assert_eq!(names, ["friends", "requests"]); assert_eq!(groups[0].members.len(), 1); assert_eq!(groups[0].members[0].agent_id, "ana"); - assert!(groups[1].members.is_empty()); + assert_eq!(groups[1].members, Vec::new()); assert_eq!(backup_count(&database), 1); drop(store); diff --git a/crates/aether-store/src/outbox.rs b/crates/aether-store/src/outbox.rs index 9ca8ae4..e4db373 100644 --- a/crates/aether-store/src/outbox.rs +++ b/crates/aether-store/src/outbox.rs @@ -2,6 +2,7 @@ use std::sync::LazyLock; use rusqlite::{OptionalExtension, TransactionBehavior, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, column_u64, sql_count, sql_named, sql_names}; /// The state of a task that this node sent. The strings are the @@ -122,7 +123,7 @@ fn sent_task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { impl NodeStore { /// Keeps a new task for the outbox, waiting and due at once. pub fn insert_sent_task(&self, input: &SentTaskInput) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT INTO sent_tasks(task_id,idempotency_key,agent_id,endpoint_id,authorization_json,text,state,created_at,updated_at,next_attempt_at,expires_at) VALUES (?1,?2,?3,?4,?5,?6,?9,?7,?7,?7,?8)", params![ input.task_id, @@ -142,7 +143,7 @@ impl NodeStore { pub fn sent_task(&self, task_id: &str) -> Result, StoreError> { Ok(self .connection - .query_row( + .query_row_cached( &format!("SELECT {SENT_COLUMNS} FROM sent_tasks WHERE task_id=?1"), [task_id], sent_task_from_row, @@ -155,7 +156,7 @@ impl NodeStore { clause: &str, values: &[&dyn rusqlite::ToSql], ) -> Result, StoreError> { - let mut statement = self.connection.prepare(&format!( + let mut statement = self.connection.prepare_cached(&format!( "SELECT {SENT_COLUMNS} FROM sent_tasks WHERE {clause}" ))?; let rows = statement.query_map(values, sent_task_from_row)?; @@ -176,7 +177,7 @@ impl NodeStore { .connection .transaction_with_behavior(TransactionBehavior::Immediate)?; let candidates = { - let mut statement = transaction.prepare(&format!( + let mut statement = transaction.prepare_cached(&format!( "SELECT {SENT_COLUMNS} FROM sent_tasks s WHERE {ACTIVE} AND next_attempt_at<=?1 AND (lease_until IS NULL OR lease_until<=?1) AND NOT EXISTS (SELECT 1 FROM sent_tasks o WHERE o.endpoint_id=s.endpoint_id AND o.task_id<>s.task_id AND o.{ACTIVE} AND o.lease_until>?1) ORDER BY next_attempt_at, created_at, task_id", ACTIVE = ACTIVE.as_str() ))?; let rows = statement.query_map([now], sent_task_from_row)?; @@ -191,7 +192,7 @@ impl NodeStore { if !endpoints.insert(task.endpoint_id.clone()) { continue; } - transaction.execute( + transaction.execute_cached( "UPDATE sent_tasks SET lease_until=?2 WHERE task_id=?1", params![task.task_id, lease_until], )?; @@ -213,7 +214,7 @@ impl NodeStore { let transaction = self .connection .transaction_with_behavior(TransactionBehavior::Immediate)?; - let changed = transaction.execute( + let changed = transaction.execute_cached( &format!("UPDATE sent_tasks SET lease_until=?3 WHERE task_id=?1 AND {ACTIVE} AND (lease_until IS NULL OR lease_until<=?2)", ACTIVE = ACTIVE.as_str()), params![task_id, now, lease_until], )?; @@ -237,7 +238,7 @@ impl NodeStore { now: i64, ) -> Result { let finished = (!attempt.state.is_active()).then_some(now); - let changed = self.connection.execute( + let changed = self.connection.execute_cached( &format!("UPDATE sent_tasks SET state=?2, reason=?3, host_state=?4, answer=?5, last_event_sequence=?6, next_attempt_at=?7, attempts=attempts+1, updated_at=?8, finished_at=?9, lease_until=NULL WHERE task_id=?1 AND {ACTIVE} AND lease_until IS ?10", ACTIVE = ACTIVE.as_str()), params![ task_id, @@ -263,7 +264,7 @@ impl NodeStore { endpoint_id: &str, now: i64, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!("UPDATE sent_tasks SET next_attempt_at=?2 WHERE endpoint_id=?1 AND {ACTIVE} AND next_attempt_at>?2", ACTIVE = ACTIVE.as_str()), params![endpoint_id, now], )?) @@ -276,7 +277,7 @@ impl NodeStore { endpoint_id: &str, until: i64, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!("UPDATE sent_tasks SET next_attempt_at=MAX(next_attempt_at, ?2) WHERE endpoint_id=?1 AND {ACTIVE} AND lease_until IS NULL", ACTIVE = ACTIVE.as_str()), params![endpoint_id, until], )?) @@ -290,7 +291,7 @@ impl NodeStore { } pub fn has_active_sent_tasks(&self) -> Result { - Ok(self.connection.query_row( + Ok(self.connection.query_row_cached( &format!( "SELECT EXISTS (SELECT 1 FROM sent_tasks WHERE {ACTIVE})", ACTIVE = ACTIVE.as_str() @@ -307,7 +308,7 @@ impl NodeStore { reason: &str, now: i64, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!("UPDATE sent_tasks SET state=?4, reason=?2, updated_at=?3, finished_at=?3, lease_until=NULL WHERE endpoint_id=?1 AND {ACTIVE}", ACTIVE = ACTIVE.as_str()), params![endpoint_id, reason, now, SentState::NotDelivered], )?) @@ -320,7 +321,7 @@ impl NodeStore { now: i64, reason: &str, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!("UPDATE sent_tasks SET state=?3, reason=?2, updated_at=?1, finished_at=?1, lease_until=NULL WHERE {ACTIVE} AND expires_at<=?1", ACTIVE = ACTIVE.as_str()), params![now, reason, SentState::NotDelivered], )?) @@ -351,7 +352,7 @@ impl NodeStore { task_id: &str, now: i64, ) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!("UPDATE sent_tasks SET read_at=COALESCE(read_at, ?2) WHERE task_id=?1 AND NOT {ACTIVE}", ACTIVE = ACTIVE.as_str()), params![task_id, now], )? == 1) @@ -359,7 +360,7 @@ impl NodeStore { /// Deletes the ended tasks that ended at `before` or earlier. pub fn purge_sent_tasks(&self, before: i64) -> Result { - Ok(self.connection.execute( + Ok(self.connection.execute_cached( &format!( "DELETE FROM sent_tasks WHERE NOT {ACTIVE} AND finished_at<=?1", ACTIVE = ACTIVE.as_str() @@ -432,7 +433,7 @@ mod tests { let claimed = store.claim_due_sent_tasks(10, 100, 4).expect("claim"); assert_eq!(claimed.len(), 1); assert_eq!(claimed[0].lease_until, Some(100)); - assert!(store.claim_due_sent_tasks(20, 120, 4).expect("claim").is_empty()); + assert_eq!(store.claim_due_sent_tasks(20, 120, 4).expect("claim"), Vec::new()); assert_eq!(store.claim_sent_task("task", 20, 120).expect("claim"), None); assert!( store @@ -492,7 +493,7 @@ mod tests { .map(|task| task.task_id) .collect(); assert_eq!(first, ["a", "c"]); - assert!(store.claim_due_sent_tasks(30, 130, 4).expect("claim").is_empty()); + assert_eq!(store.claim_due_sent_tasks(30, 130, 4).expect("claim"), Vec::new()); let waiting = SentAttempt { state: SentState::Waiting, ..answered(40) }; store.record_sent_attempt("a", Some(100), &waiting, 40).expect("record"); let next: Vec = store diff --git a/crates/aether-store/src/pact.rs b/crates/aether-store/src/pact.rs index cc11b45..8c21249 100644 --- a/crates/aether-store/src/pact.rs +++ b/crates/aether-store/src/pact.rs @@ -10,6 +10,7 @@ use std::path::Path; use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use crate::CachedSql; use crate::{StoreError, migrate::open_connection, sql_named}; pub const PACT_DATABASE: &str = "pact.sqlite"; @@ -130,7 +131,7 @@ impl PactStore { pa_subject: &str, now: i64, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT INTO pact_contexts(context_id, brand_id, pa_issuer, pa_subject, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?5)", params![context_id, brand_id, pa_issuer, pa_subject, now], )?; @@ -140,7 +141,7 @@ impl PactStore { pub fn context(&self, context_id: &str) -> Result, StoreError> { Ok(self .connection - .query_row( + .query_row_cached( "SELECT context_id, brand_id, pa_issuer, pa_subject, brand_user, closed_at IS NOT NULL FROM pact_contexts WHERE context_id=?1", [context_id], |row| { @@ -165,7 +166,7 @@ impl PactStore { context_id: &str, brand_user: &str, ) -> Result<(), StoreError> { - let changed = self.connection.execute( + let changed = self.connection.execute_cached( "UPDATE pact_contexts SET brand_user=?2 WHERE context_id=?1 AND (brand_user IS NULL OR brand_user=?2)", params![context_id, brand_user], )?; @@ -181,11 +182,11 @@ impl PactStore { now: i64, ) -> Result { let transaction = self.connection.unchecked_transaction()?; - let closed = transaction.execute( + let closed = transaction.execute_cached( "UPDATE pact_contexts SET closed_at=?2 WHERE closed_at IS NULL AND updated_at < ?1", params![idle_before, now], )?; - transaction.execute( + transaction.execute_cached( "DELETE FROM pact_messages WHERE context_id IN (SELECT context_id FROM pact_contexts WHERE closed_at IS NOT NULL)", [], )?; @@ -206,7 +207,7 @@ impl PactStore { ) -> Result { let transaction = self.connection.unchecked_transaction()?; let existing: Option> = transaction - .query_row( + .query_row_cached( "SELECT response FROM pact_messages WHERE context_id=?1 AND message_id=?2", params![context_id, message_id], |row| row.get(0), @@ -215,14 +216,14 @@ impl PactStore { if let Some(response) = existing { return Ok(Reservation::Existing(response)); } - let open = transaction.execute( + let open = transaction.execute_cached( "UPDATE pact_contexts SET updated_at=?2 WHERE context_id=?1 AND closed_at IS NULL", params![context_id, now], )?; if open != 1 { return Err(StoreError::NotFound); } - transaction.execute( + transaction.execute_cached( "INSERT INTO pact_messages(context_id, message_id, sequence, request_text, created_at) VALUES (?1, ?2, (SELECT COALESCE(MAX(sequence), 0) + 1 FROM pact_messages WHERE context_id=?1), ?3, ?4)", params![context_id, message_id, request_text, now], )?; @@ -240,7 +241,7 @@ impl PactStore { reply_text: Option<&str>, response: &str, ) -> Result<(), StoreError> { - let changed = self.connection.execute( + let changed = self.connection.execute_cached( "UPDATE pact_messages SET reply_text=?3, response=?4 WHERE context_id=?1 AND message_id=?2 AND response IS NULL", params![context_id, message_id, reply_text, response], )?; @@ -254,7 +255,7 @@ impl PactStore { context_id: &str, message_id: &str, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "DELETE FROM pact_messages WHERE context_id=?1 AND message_id=?2 AND response IS NULL", params![context_id, message_id], )?; @@ -270,7 +271,7 @@ impl PactStore { limit: usize, ) -> Result, StoreError> { let limit = i64::try_from(limit).unwrap_or(i64::MAX); - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT request_text, reply_text FROM (SELECT sequence, request_text, reply_text FROM pact_messages WHERE context_id=?1 AND reply_text IS NOT NULL AND sequence < (SELECT sequence FROM pact_messages WHERE context_id=?1 AND message_id=?2) ORDER BY sequence DESC LIMIT ?3) ORDER BY sequence", )?; statement @@ -287,7 +288,7 @@ impl PactStore { &self, authorization: &NewDeviceAuthorization, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT INTO pact_device_authorizations(device_code_hash, user_code, brand_id, pa_issuer, pa_subject, scopes, status, interval_seconds, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?10, ?7, ?8, ?9)", params![ authorization.device_code_hash, @@ -313,7 +314,7 @@ impl PactStore { ) -> Result, StoreError> { Ok(self .connection - .query_row( + .query_row_cached( "SELECT user_code, brand_id, pa_issuer, pa_subject, scopes, expires_at FROM pact_device_authorizations WHERE user_code=?1 AND status=?3 AND expires_at > ?2", params![user_code, now, DeviceStatus::Pending], |row| { @@ -339,7 +340,7 @@ impl PactStore { now: i64, ) -> Result<(), StoreError> { let transaction = self.connection.unchecked_transaction()?; - let changed = transaction.execute( + let changed = transaction.execute_cached( "UPDATE pact_device_authorizations SET status=?4, grant_id=?2 WHERE user_code=?1 AND status=?5 AND expires_at > ?3", params![ user_code, @@ -360,7 +361,7 @@ impl PactStore { /// Denies the pending authorization `user_code`. `NotFound` when it is /// no longer pending, or has expired. pub fn deny_device(&self, user_code: &str, now: i64) -> Result<(), StoreError> { - let changed = self.connection.execute( + let changed = self.connection.execute_cached( "UPDATE pact_device_authorizations SET status=?2 WHERE user_code=?1 AND status=?3 AND expires_at > ?4", params![user_code, DeviceStatus::Denied, DeviceStatus::Pending, now], )?; @@ -384,7 +385,7 @@ impl PactStore { TransactionBehavior::Immediate, )?; let row: Option = transaction - .query_row( + .query_row_cached( "SELECT status, grant_id, interval_seconds, last_polled_at, expires_at FROM pact_device_authorizations WHERE device_code_hash=?1 AND brand_id=?2 AND pa_issuer=?3 AND pa_subject=?4", params![device_code_hash, brand_id, pa_issuer, pa_subject], |row| { @@ -412,7 +413,7 @@ impl PactStore { DeviceStatus::Pending => { let slow_down = last_polled_at .is_some_and(|last| now.saturating_sub(last) < interval); - transaction.execute( + transaction.execute_cached( "UPDATE pact_device_authorizations SET last_polled_at=?2 WHERE device_code_hash=?1 AND status=?3", params![device_code_hash, now, DeviceStatus::Pending], )?; @@ -421,7 +422,7 @@ impl PactStore { DeviceStatus::Approved => { // Like every transition here, the update names the state // it leaves, so only one poll can consume an approval. - let consumed = transaction.execute( + let consumed = transaction.execute_cached( "UPDATE pact_device_authorizations SET status=?2 WHERE device_code_hash=?1 AND status=?3 AND expires_at > ?4", params![ device_code_hash, @@ -455,7 +456,7 @@ impl PactStore { grant_id: &str, expires_at: i64, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT INTO pact_refresh_tokens(token_hash, grant_id, expires_at) VALUES (?1, ?2, ?3)", params![token_hash, grant_id, expires_at], )?; @@ -479,7 +480,7 @@ impl PactStore { TransactionBehavior::Immediate, )?; let grant_id: Option = transaction - .query_row( + .query_row_cached( "UPDATE pact_refresh_tokens SET used_at=?2 WHERE token_hash=?1 AND used_at IS NULL AND expires_at > ?2 AND grant_id IN (SELECT grant_id FROM pact_grants WHERE brand_id=?3 AND pa_issuer=?4 AND pa_subject=?5) RETURNING grant_id", params![token_hash, now, brand_id, pa_issuer, pa_subject], |row| row.get(0), @@ -504,7 +505,7 @@ impl PactStore { jws: &str, now: i64, ) -> Result<(), StoreError> { - self.connection.execute( + self.connection.execute_cached( "INSERT INTO pact_receipts(context_id, message_id, grant_id, jws, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", params![context_id, message_id, grant_id, jws, now], )?; @@ -513,7 +514,7 @@ impl PactStore { /// The receipts stored for `grant_id`, oldest first. pub fn receipts(&self, grant_id: &str) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT jws FROM pact_receipts WHERE grant_id=?1 ORDER BY created_at, context_id, message_id", )?; statement @@ -552,7 +553,7 @@ struct DeviceRow { } fn insert_grant(connection: &Connection, grant: &PactGrant) -> Result<(), StoreError> { - connection.execute( + connection.execute_cached( &format!("INSERT INTO pact_grants({GRANT_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"), params![ grant.grant_id, @@ -573,7 +574,7 @@ fn query_grant( grant_id: &str, ) -> Result, StoreError> { Ok(connection - .query_row( + .query_row_cached( &format!("SELECT {GRANT_COLUMNS} FROM pact_grants WHERE grant_id=?1"), [grant_id], PactGrant::from_row, diff --git a/crates/aether-store/src/tasks.rs b/crates/aether-store/src/tasks.rs index 607725d..f219e07 100644 --- a/crates/aether-store/src/tasks.rs +++ b/crates/aether-store/src/tasks.rs @@ -4,6 +4,7 @@ use aether_core::{ }; use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; +use crate::CachedSql; use crate::{NodeStore, StoreError, now, sql_count, sql_named, sql_names}; pub const CONTENT_RETENTION_SECONDS: i64 = 24 * 60 * 60; @@ -289,7 +290,7 @@ impl NodeStore { } pub fn last_tasks(&self, scope_id: &str) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT caller_endpoint_id,state,created_at,remote_text,final_result FROM ( SELECT caller_endpoint_id,state,created_at,remote_text,final_result, ROW_NUMBER() OVER ( @@ -358,7 +359,7 @@ fn admit( ) -> Result { let request = &input.request; let existing = tx - .query_row( + .query_row_cached( &format!( "SELECT {REQUEST_COLUMNS},request_fingerprint,caller_task_id,caller_request_id FROM tasks WHERE caller_endpoint_id=?1 AND idempotency_key=?2" ), @@ -400,7 +401,7 @@ fn admit( ); let caller_ids = own_ids.as_ref().map(|_| (request.task_id.as_str(), request.id.as_str())); - tx.execute( + tx.execute_cached( &format!( "INSERT INTO tasks({REQUEST_COLUMNS},idempotency_key,request_fingerprint,skill,remote_text,state,created_at,caller_task_id,caller_request_id) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16)" @@ -441,7 +442,7 @@ fn own_ids( request: &Request, ) -> Result, StoreError> { let endpoint = request.caller_endpoint_id.as_str(); - let mut statement = tx.prepare( + let mut statement = tx.prepare_cached( "SELECT caller_endpoint_id FROM tasks WHERE id=?1 OR request_id=?2 OR (caller_endpoint_id=?3 AND (caller_task_id=?1 OR caller_request_id=?2))", @@ -464,7 +465,7 @@ fn own_ids( /// A random ID in the form of a UUID. fn random_id(tx: &Transaction<'_>) -> Result { let hex: String = - tx.query_row("SELECT lower(hex(randomblob(16)))", [], |row| row.get(0))?; + tx.query_row_cached("SELECT lower(hex(randomblob(16)))", [], |row| row.get(0))?; let part = |range: std::ops::Range| hex.get(range).unwrap_or_default(); Ok(format!( "{}-{}-{}-{}-{}", @@ -479,7 +480,7 @@ fn random_id(tx: &Transaction<'_>) -> Result { impl NodeStore { pub fn state(&self, task_id: &str) -> Result { self.connection - .query_row("SELECT state FROM tasks WHERE id=?1", [task_id], |row| { + .query_row_cached("SELECT state FROM tasks WHERE id=?1", [task_id], |row| { row.get(0) }) .optional()? @@ -499,7 +500,7 @@ impl NodeStore { Option, ) = self .connection - .query_row( + .query_row_cached( "SELECT id,state,skill,remote_text,final_result FROM tasks WHERE id=?1", [task_id], |row| { @@ -529,7 +530,7 @@ impl NodeStore { task_id: &str, last_sequence: i64, ) -> Result, StoreError> { - let mut statement = self.connection.prepare("SELECT sequence,event_type FROM task_events WHERE task_id=?1 AND sequence>?2 ORDER BY sequence")?; + let mut statement = self.connection.prepare_cached("SELECT sequence,event_type FROM task_events WHERE task_id=?1 AND sequence>?2 ORDER BY sequence")?; Ok(statement .query_map(params![task_id, last_sequence], TaskEvent::from_row)? .collect::>()?) @@ -545,7 +546,7 @@ impl NodeStore { limit: usize, ) -> Result<(Vec, bool), StoreError> { let fetch = sql_count(limit.saturating_add(1)); - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT sequence,event_type FROM task_events WHERE task_id=?1 AND sequence>?2 ORDER BY sequence LIMIT ?3", )?; let mut events = statement @@ -563,7 +564,7 @@ impl NodeStore { task_id: &str, ) -> Result<(TaskState, Option), StoreError> { self.connection - .query_row( + .query_row_cached( "SELECT state,final_result FROM tasks WHERE id=?1", [task_id], |row| Ok((row.get(0)?, row.get(1)?)), @@ -596,7 +597,7 @@ impl NodeStore { cursor: i64, limit: usize, ) -> Result, StoreError> { - let mut statement = self.connection.prepare( + let mut statement = self.connection.prepare_cached( "SELECT rowid,task_id,event_type FROM task_events WHERE rowid>?1 ORDER BY rowid LIMIT ?2", )?; Ok(statement @@ -627,22 +628,46 @@ impl NodeStore { owner: &str, execution_id: &str, expires_at: i64, + ) -> Result, StoreError> { + self.lease_next_except(owner, execution_id, expires_at, &[]) + } + + /// Leases the next queued task that is not in `skip`. A node that runs + /// several tasks at once passes the tasks that a run of its own still + /// holds: such a task can be queued again (its lease ran out before the + /// run could renew it), and it must not get a second run while the first + /// one lives. + pub fn lease_next_except( + &mut self, + owner: &str, + execution_id: &str, + expires_at: i64, + skip: &[String], ) -> Result, StoreError> { let tx = self.connection.transaction()?; + let skipped = if skip.is_empty() { + String::new() + } else { + let marks = (0..skip.len()).map(|_| "?").collect::>().join(","); + format!(" AND queued.id NOT IN ({marks})") + }; + let parameters = std::iter::once(TaskState::Queued.as_str()) + .chain(skip.iter().map(String::as_str)) + .collect::>(); let task = tx - .query_row( + .query_row_cached( &format!( - "SELECT queued.id FROM tasks queued WHERE queued.state=?1 + "SELECT queued.id FROM tasks queued WHERE queued.state=?1{skipped} ORDER BY (SELECT COUNT(*) FROM tasks active WHERE active.caller_agent_id=queued.caller_agent_id AND active.state IN ({})), queued.created_at, queued.id LIMIT 1", TaskState::sql_list(&TaskState::ACTIVE), ), - [TaskState::Queued], + rusqlite::params_from_iter(parameters), |row| row.get::<_, String>(0), ) .optional()?; let Some(task) = task else { return Ok(None) }; enter(&tx, &task, TaskState::Leased)?; - tx.execute("INSERT INTO execution_leases(task_id,owner,execution_id,expires_at) VALUES(?1,?2,?3,?4)", params![task,owner,execution_id,expires_at])?; + tx.execute_cached("INSERT INTO execution_leases(task_id,owner,execution_id,expires_at) VALUES(?1,?2,?3,?4)", params![task,owner,execution_id,expires_at])?; tx.commit()?; Ok(Some(task)) } @@ -674,7 +699,7 @@ impl NodeStore { expires_at: i64, now: i64, ) -> Result<(), StoreError> { - if self.connection.execute( + if self.connection.execute_cached( "UPDATE execution_leases SET expires_at=?1 WHERE task_id=?2 AND execution_id=?3 AND expires_at>?4", params![expires_at, task_id, execution_id, now], )? == 0 { @@ -702,7 +727,7 @@ impl NodeStore { return Err(StoreError::NotFound); } end(&tx, task_id, TaskState::Succeeded)?; - tx.execute( + tx.execute_cached( "UPDATE tasks SET final_result=?1,result_expires_at=?2 WHERE id=?3", params![result, result_expires_at, task_id], )?; @@ -722,7 +747,7 @@ impl NodeStore { ) -> Result { let tx = self.connection.transaction()?; let ids = { - let mut statement = tx.prepare(&format!( + let mut statement = tx.prepare_cached(&format!( "SELECT id FROM tasks WHERE content_expired_at IS NULL AND state IN ({}) @@ -738,7 +763,7 @@ impl NodeStore { .collect::, _>>()? }; for task_id in &ids { - tx.execute( + tx.execute_cached( "UPDATE tasks SET remote_text='',final_result=NULL,result_expires_at=NULL,content_expired_at=?1 WHERE id=?2", params![timestamp, task_id], )?; @@ -750,7 +775,7 @@ impl NodeStore { pub fn content_is_expired(&self, task_id: &str) -> Result { self.connection - .query_row( + .query_row_cached( "SELECT content_expired_at IS NOT NULL FROM tasks WHERE id=?1", [task_id], |row| row.get(0), @@ -823,7 +848,7 @@ impl NodeStore { ) -> Result { let tx = self.connection.transaction()?; let (id, owner, scope): (String, String, String) = tx - .query_row( + .query_row_cached( "SELECT id,caller_endpoint_id,scope_id FROM tasks WHERE id=?1 OR (caller_endpoint_id=?2 AND caller_task_id=?1) ORDER BY caller_task_id IS NULL LIMIT 1", @@ -844,7 +869,7 @@ impl NodeStore { task_id: &str, ) -> Result { self.connection - .query_row( + .query_row_cached( &format!( "SELECT {REQUEST_COLUMNS},skill,remote_text FROM tasks WHERE id=?1" ), @@ -884,8 +909,9 @@ impl NodeStore { ) -> Result, StoreError> { let tx = self.connection.transaction()?; let ids = { - let mut statement = tx - .prepare("SELECT task_id FROM execution_leases WHERE expires_at<=?1")?; + let mut statement = tx.prepare_cached( + "SELECT task_id FROM execution_leases WHERE expires_at<=?1", + )?; statement .query_map([timestamp], |row| row.get::<_, String>(0))? .collect::, _>>()? @@ -921,11 +947,11 @@ fn accept_replay_key( expires_at: i64, limit: usize, ) -> Result<(), StoreError> { - tx.execute( + tx.execute_cached( "DELETE FROM replay_entries WHERE caller_endpoint_id=?1 AND scope_id=?2 AND expires_at<=?3", params![caller_endpoint_id, scope_id, now()], )?; - let exists: bool = tx.query_row( + let exists: bool = tx.query_row_cached( "SELECT EXISTS(SELECT 1 FROM replay_entries WHERE caller_endpoint_id=?1 AND scope_id=?2 AND replay_key=?3)", params![caller_endpoint_id, scope_id, replay_key], |row| row.get(0), @@ -933,7 +959,7 @@ fn accept_replay_key( if exists { return Err(StoreError::DuplicateConflict); } - let count: i64 = tx.query_row( + let count: i64 = tx.query_row_cached( "SELECT COUNT(*) FROM replay_entries WHERE caller_endpoint_id=?1 AND scope_id=?2", params![caller_endpoint_id, scope_id], |row| row.get(0), @@ -943,7 +969,7 @@ fn accept_replay_key( // would let the caller send that frame again. return Err(StoreError::Overloaded); } - tx.execute( + tx.execute_cached( "INSERT INTO replay_entries(caller_endpoint_id,scope_id,replay_key,expires_at) VALUES(?1,?2,?3,?4)", params![caller_endpoint_id, scope_id, replay_key, expires_at], )?; @@ -952,12 +978,12 @@ fn accept_replay_key( fn count(tx: &Transaction<'_>, peer: Option<&str>) -> Result { let count: i64 = match peer { - Some(peer) => tx.query_row( + Some(peer) => tx.query_row_cached( "SELECT COUNT(*) FROM tasks WHERE state=?1 AND caller_endpoint_id=?2", params![TaskState::Queued, peer], |row| row.get(0), )?, - None => tx.query_row( + None => tx.query_row_cached( "SELECT COUNT(*) FROM tasks WHERE state=?1", [TaskState::Queued], |row| row.get(0), @@ -971,7 +997,7 @@ fn lease_matches( task_id: &str, execution_id: &str, ) -> Result { - tx.query_row( + tx.query_row_cached( "SELECT EXISTS(SELECT 1 FROM execution_leases WHERE task_id=?1 AND execution_id=?2)", params![task_id, execution_id], |row| row.get(0), @@ -980,9 +1006,11 @@ fn lease_matches( } fn state(tx: &Transaction<'_>, task_id: &str) -> Result { - tx.query_row("SELECT state FROM tasks WHERE id=?1", [task_id], |row| row.get(0)) - .optional()? - .ok_or(StoreError::NotFound) + tx.query_row_cached("SELECT state FROM tasks WHERE id=?1", [task_id], |row| { + row.get(0) + }) + .optional()? + .ok_or(StoreError::NotFound) } /// Moves the task to the terminal state `next`, starts its input's @@ -1003,12 +1031,12 @@ fn cancel(tx: Transaction<'_>, task_id: &str) -> Result<(), StoreError> { } fn delete_lease(tx: &Transaction<'_>, task_id: &str) -> Result<(), StoreError> { - tx.execute("DELETE FROM execution_leases WHERE task_id=?1", [task_id])?; + tx.execute_cached("DELETE FROM execution_leases WHERE task_id=?1", [task_id])?; Ok(()) } fn set_input_expiry(tx: &Transaction<'_>, task_id: &str) -> Result<(), StoreError> { - tx.execute( + tx.execute_cached( "UPDATE tasks SET input_expires_at=?1 WHERE id=?2 AND input_expires_at IS NULL", params![now().saturating_add(CONTENT_RETENTION_SECONDS), task_id], )?; @@ -1036,7 +1064,7 @@ fn change( } // Write only over the state just checked, so the guard holds even if // another writer changed the row in between. - if tx.execute( + if tx.execute_cached( "UPDATE tasks SET state=?1 WHERE id=?2 AND state=?3", params![next, task_id, current], )? == 0 @@ -1051,12 +1079,12 @@ fn event( task_id: &str, event_type: EventType, ) -> Result<(), StoreError> { - let sequence: i64 = tx.query_row( + let sequence: i64 = tx.query_row_cached( "SELECT COALESCE(MAX(sequence),0)+1 FROM task_events WHERE task_id=?1", [task_id], |row| row.get(0), )?; - tx.execute( + tx.execute_cached( "INSERT INTO task_events(task_id,sequence,event_type,data,created_at) VALUES(?1,?2,?3,'{}',?4)", params![task_id, sequence, event_type, now()], )?; @@ -1105,7 +1133,10 @@ mod tests { .collect::>(), [("endpoint-a", TaskState::Queued), ("endpoint-b", TaskState::Cancelled)] ); - assert!(store.last_tasks("other").expect("last tasks must load").is_empty()); + assert_eq!( + store.last_tasks("other").expect("last tasks must load"), + Vec::new() + ); drop(store); fs::remove_file(database).expect("database must remove"); } @@ -1561,6 +1592,28 @@ mod tests { fs::remove_file(database).expect("database must remove"); } + #[test] + fn a_lease_skips_the_tasks_that_a_live_run_still_holds() { + let (mut store, database) = store(); + for (id, peer) in [("one", "a"), ("two", "b"), ("three", "c")] { + store + .admit(&input(id, peer), QueueLimits { global: 3, per_peer: 1 }) + .expect("task must admit"); + } + let skip = ["one".to_owned(), "two".to_owned()]; + assert_eq!( + store.lease_next_except("worker", "first", 10, &skip), + Ok(Some("three".to_owned())) + ); + // Nothing else is left to lease. + assert_eq!(store.lease_next_except("worker", "second", 10, &skip), Ok(None)); + // A skipped task is still queued, and the next lease without a list + // takes the oldest of them. + assert_eq!(store.state("one"), Ok(TaskState::Queued)); + assert_eq!(store.lease_next("worker", "third", 10), Ok(Some("one".to_owned()))); + fs::remove_file(database).expect("database must remove"); + } + #[test] fn a_task_id_of_another_endpoint_does_not_block_a_caller() { let (mut store, database) = store(); diff --git a/crates/aether/src/admin.rs b/crates/aether/src/admin.rs index 19623ee..714a6b1 100644 --- a/crates/aether/src/admin.rs +++ b/crates/aether/src/admin.rs @@ -186,7 +186,7 @@ impl ChangeRequest { let expires_at = SystemTime::now() .checked_add(std::time::Duration::from_secs(300)) .ok_or(AdminError::InvalidField("expires_at"))?; - if matches!(self, Self::Limit { limit: 0, .. }) { + if matches!(&self, Self::Limit { id, limit } if !id.accepts(*limit)) { return Err(AdminError::InvalidField("limit")); } valid(self.id(), "id")?; @@ -838,7 +838,6 @@ impl Administration { /// stored policy. A policy that cannot be read proves nothing, so it /// counts as wider. fn policy_is_wider(&self, settings: &crate::policy::PolicySettings) -> bool { - use aether_core::limits::QueueLimitId::{Global, PerPeer}; let Ok(Some(current)) = crate::policy::policy_settings_in_store(&self.store) else { return true; @@ -846,8 +845,9 @@ impl Administration { settings.workspace != current.workspace || settings.max_context_tokens > current.max_context_tokens || settings.max_seconds > current.max_seconds - || settings.queue.get(Global) > current.queue.get(Global) - || settings.queue.get(PerPeer) > current.queue.get(PerPeer) + || aether_core::limits::QueueLimitId::ALL + .into_iter() + .any(|id| settings.queue.get(id) > current.queue.get(id)) } /// Confirms a durably pending change the same way `apply_now` applies an @@ -1267,6 +1267,45 @@ mod tests { ); } + #[test] + fn the_running_limit_follows_the_rules_of_the_queue_limits() { + use aether_core::limits::{MAX_RUNNING_TASKS, QueueLimitId::Running}; + // A decrease applies at once, with an audit entry like any limit. + let (_directory, mut administration) = in_temp_dir(); + let node = Arc::new(FakeNode::default().with_queue_limit(4)); + administration.set_live(node.clone()); + administration + .submit(&limit_change(Running, 2), aether_store::AuditActor::Mcp, false) + .expect("a lower running limit must apply"); + assert_eq!(node.calls(), ["limit running_tasks 2"]); + assert!(administration.pending().expect("pending").is_empty()); + // An increase waits for the owner in the UI. + let (_directory, mut administration) = in_temp_dir(); + administration.set_live(Arc::new(FakeNode::default().with_queue_limit(1))); + administration + .submit(&limit_change(Running, 2), aether_store::AuditActor::Mcp, false) + .expect("a higher running limit must queue"); + assert_eq!( + administration.pending().expect("pending"), + [PendingChange { + id: "running_tasks".to_owned(), + kind: "limit".to_owned() + }] + ); + // Zero and more than the maximum are not limits. + for limit in [0, MAX_RUNNING_TASKS.saturating_add(1)] { + assert!(matches!( + ChangeRequest::Limit { id: Running, limit }.into_change(), + Err(AdminError::InvalidField("limit")) + )); + } + assert!( + ChangeRequest::Limit { id: Running, limit: MAX_RUNNING_TASKS } + .into_change() + .is_ok() + ); + } + #[test] fn queue_limit_change_uses_the_live_node_callback() { let (_directory, mut administration) = in_temp_dir(); diff --git a/crates/aether/src/admin_socket.rs b/crates/aether/src/admin_socket.rs index c5fa3cb..fdbb2fe 100644 --- a/crates/aether/src/admin_socket.rs +++ b/crates/aether/src/admin_socket.rs @@ -55,6 +55,7 @@ pub enum Request { max_seconds: Option, queue_global: Option, queue_per_peer: Option, + running_tasks: Option, dry_run: bool, }, } @@ -290,6 +291,7 @@ fn handle( max_seconds, queue_global, queue_per_peer, + running_tasks, dry_run, } => with_lock(administration, |administration| { let Some(mut settings) = @@ -312,6 +314,9 @@ fn handle( if let Some(value) = queue_per_peer { settings.queue.set(aether_core::limits::QueueLimitId::PerPeer, value); } + if let Some(value) = running_tasks { + settings.queue.set(aether_core::limits::QueueLimitId::Running, value); + } if dry_run { match crate::policy::validate_policy_settings(&settings) { Ok(()) => Response::Validated, diff --git a/crates/aether/src/admin_ui/advanced.rs b/crates/aether/src/admin_ui/advanced.rs index e989be5..120f515 100644 --- a/crates/aether/src/admin_ui/advanced.rs +++ b/crates/aether/src/admin_ui/advanced.rs @@ -200,6 +200,11 @@ pub(super) async fn dashboard( label(attrs: attributes! { for="queue_per_peer" }, "Max waiting tasks per person") input(attrs: attributes! { id="queue_per_peer" name="queue_per_peer" type="number" min="1" required="" value=(policy.queue.get(aether_core::limits::QueueLimitId::PerPeer).to_string()) }) +
+ label(attrs: attributes! { for="running_tasks" }, "Tasks running at once") + input(attrs: attributes! { id="running_tasks" name="running_tasks" type="number" min=(aether_core::limits::QueueLimitId::Running.minimum().to_string()) max=(aether_core::limits::MAX_RUNNING_TASKS.to_string()) required="" value=(policy.queue.get(aether_core::limits::QueueLimitId::Running).to_string()) }) +

"For all people together. One runs a task at a time. A higher number uses more of this computer, and other tasks wait until one ends. Lowering it never stops a running task. An agent that takes fewer tasks at once, such as Codex with a shared workspace or a connected agent that takes one, still runs that many."

+
button(variant: ButtonVariant::Primary, attrs: attributes! { type="submit" class="w-fit" }, "Save task policy") @@ -334,6 +339,7 @@ pub(super) struct PolicyForm { max_seconds: u64, queue_global: usize, queue_per_peer: usize, + running_tasks: usize, } #[page(POST "/policy")] @@ -350,12 +356,13 @@ pub(super) async fn save_policy( queue: crate::policy::QueuePolicyLimits::new( form.queue_global, form.queue_per_peer, - ), + ) + .with_running(form.running_tasks), }; administration(cx) .save_policy_settings(&settings, aether_store::AuditActor::Ui) .map_err(|_| { - bad_request("use an existing absolute folder and limits above zero") + bad_request("use an existing absolute folder and limits in range") })?; Ok(view! { dashboard(policy_saved: true) }) } @@ -480,7 +487,8 @@ mod tests { .append_pair("max_context_tokens", "12000") .append_pair("max_seconds", "90") .append_pair("queue_global", "3") - .append_pair("queue_per_peer", "2"); + .append_pair("queue_per_peer", "2") + .append_pair("running_tasks", "3"); let denied = post( application.clone(), "/policy", @@ -505,6 +513,7 @@ mod tests { assert_eq!(settings.max_seconds, 90); assert_eq!(settings.queue.global, 3); assert_eq!(settings.queue.per_peer, 2); + assert_eq!(settings.queue.running, 3); } #[tokio::test] diff --git a/crates/aether/src/admin_ui/shared.rs b/crates/aether/src/admin_ui/shared.rs index a7a3e3c..19edf6a 100644 --- a/crates/aether/src/admin_ui/shared.rs +++ b/crates/aether/src/admin_ui/shared.rs @@ -121,8 +121,14 @@ pub(super) fn queue_text(data_dir: &Path) -> String { } else { format!("{} waiting tasks", limits.global) }; + let running = match crate::policy::running_limit(data_dir) { + Ok(Some(1) | None) | Err(_) => "It runs one task at a time.".to_owned(), + Ok(Some(running)) => { + format!("It runs up to {running} tasks at a time.") + } + }; format!( - "Your agent keeps {tasks} in all and {} for each person. People who get access by request share these places.", + "Your agent keeps {tasks} in all and {} for each person. {running} People who get access by request share these places.", limits.per_peer ) } diff --git a/crates/aether/src/agent.rs b/crates/aether/src/agent.rs index 7d40fc0..99de2bd 100644 --- a/crates/aether/src/agent.rs +++ b/crates/aether/src/agent.rs @@ -55,6 +55,20 @@ impl Agent for NodeAgent { Self::Connected(agent) => agent.cancel(task_id), } } + + fn forget(&self, task_id: &str) { + match self { + Self::Codex(agent) => agent.forget(task_id), + Self::Connected(agent) => agent.forget(task_id), + } + } + + fn capacity(&self) -> usize { + match self { + Self::Codex(agent) => agent.capacity(), + Self::Connected(agent) => agent.capacity(), + } + } } /// Writes `message` to `writer` as one line of JSON. diff --git a/crates/aether/src/agent/codex.rs b/crates/aether/src/agent/codex.rs index 7290e8f..2d9864b 100644 --- a/crates/aether/src/agent/codex.rs +++ b/crates/aether/src/agent/codex.rs @@ -7,7 +7,7 @@ use std::{ path::{Path, PathBuf}, process::{ChildStdin, Stdio}, sync::{ - Arc, Mutex, + Arc, Mutex, PoisonError, atomic::{AtomicU64, Ordering}, mpsc::{self, Receiver}, }, @@ -149,12 +149,23 @@ fn spawn_environment( environment } +/// Held from the copy of the Codex binary into a task folder until the +/// `codex app-server` process of that task has started, by every turn of the +/// node. While a thread copies a file, it holds the file open for writing, +/// and a process that another thread forks at that moment holds it too until +/// its own `exec`. A third thread that starts the copied file in that time +/// gets `ETXTBSY` and its turn fails. Turns that run side by side would meet +/// there; one at a time they never did. +static SPAWN_LOCK: Mutex<()> = Mutex::new(()); + #[derive(Clone)] pub struct CodexAppServer { binary: PathBuf, /// The file of `binary`, found once when the server is made. A task - /// folder gets a link to it or a copy of it. - source: Option, + /// folder gets a link to it or a copy of it. Shared by the clones that + /// run each turn, so a binary found again after an update is kept for + /// the next turns. + source: Arc>>, arguments: Vec, limits: CodexLimits, turns: Arc>, @@ -230,7 +241,7 @@ impl CodexAppServer { return Err(ExecutionError::Limits); } Ok(Self { - source: resolve_binary(&binary).ok(), + source: Arc::new(Mutex::new(resolve_binary(&binary).ok())), binary, arguments, limits, @@ -240,15 +251,16 @@ impl CodexAppServer { /// The Codex binary in `folder`. When the file found at start is gone /// (an update moved it), it finds the binary again. - fn task_binary(&mut self, folder: &TaskFolder) -> Result { + fn task_binary(&self, folder: &TaskFolder) -> Result { + let known = self.source.lock().unwrap_or_else(PoisonError::into_inner).clone(); if let Some(binary) = - self.source.as_deref().and_then(|source| folder.codex_binary(source).ok()) + known.as_deref().and_then(|source| folder.codex_binary(source).ok()) { return Ok(binary); } let source = resolve_binary(&self.binary)?; let binary = folder.codex_binary(&source)?; - self.source = Some(source); + *self.source.lock().unwrap_or_else(PoisonError::into_inner) = Some(source); Ok(binary) } @@ -327,7 +339,7 @@ impl CodexAppServer { } fn start( - &mut self, + &self, ctx: &TurnContext, events: &mut dyn FnMut(ExecutionEvent), ) -> Result { @@ -345,6 +357,7 @@ impl CodexAppServer { } else { ctx.workspace.clone() }; + let spawn_guard = SPAWN_LOCK.lock().unwrap_or_else(PoisonError::into_inner); let (binary, arguments, environment) = match &task_folder { Some(folder) => { let mut arguments = self.arguments.clone(); @@ -362,7 +375,9 @@ impl CodexAppServer { ), }; let session = - AppServerSession::spawn(&binary, &arguments, ctx.deadline, &environment)?; + AppServerSession::spawn(&binary, &arguments, ctx.deadline, &environment); + drop(spawn_guard); + let session = session?; session.request("initialize", &initialize_params(), events)?; let thread_id = self.start_thread(&session, &workspace, &ctx.skill, events)?; self.run_turn(&session, &workspace, &ctx.task_id, &thread_id, &ctx.text, events) @@ -589,6 +604,17 @@ impl Agent for CodexAppServer { turns.cancels.forget(task_id); } } + + /// A task folder is the turn's own: its own folder, its own + /// `codex app-server` process and its own profile, so turns run side by + /// side. `WorkspaceWrite` lets every turn write one shared folder, so + /// turns would overwrite each other's files: one at a time. + fn capacity(&self) -> usize { + match self.limits.sandbox { + CodexSandbox::TaskFolder => usize::MAX, + CodexSandbox::WorkspaceWrite => 1, + } + } } pub(crate) fn valid_environment_value(value: &str) -> bool { @@ -1313,6 +1339,97 @@ done ); } + #[test] + #[cfg(unix)] + fn two_turns_run_side_by_side_and_a_cancel_stops_only_its_turn() { + let directory = tempfile::tempdir().expect("directory must create"); + let limits = CodexLimits { + sandbox: CodexSandbox::WorkspaceWrite, + allow_network: false, + environment: BTreeMap::new(), + }; + let script = r#" +while IFS= read -r request; do + case "$request" in + *'"id":1'*) printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{}}' ;; + *'"id":2'*) printf '%s\n' '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thread"}}}' ;; + *'"id":3'*) + printf '%s\n' '{"jsonrpc":"2.0","id":3,"result":{"turn":{"id":"turn"}}}' + printf '%s\n' '{"jsonrpc":"2.0","method":"item/agentMessage/delta","params":{"threadId":"thread","turnId":"turn","delta":"waiting"}}' + IFS= read -r interrupt + printf '%s\n' '{"jsonrpc":"2.0","id":4,"result":{}}' + printf '%s\n' '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thread","turn":{"id":"turn","status":"interrupted","items":[]}}}' + ;; + esac +done +"#; + let server = CodexAppServer::with_arguments( + PathBuf::from("sh"), + vec!["-c".to_owned(), script.to_owned()], + limits, + ) + .expect("limits must be valid"); + let (ready_sender, ready_receiver) = mpsc::channel(); + let start = |task: &'static str| { + let mut running = server.clone(); + let ready = ready_sender.clone(); + let workspace = directory.path().to_path_buf(); + std::thread::spawn(move || { + running.start_turn_with_events( + &turn_ctx(&workspace, task, "review", "untrusted", 30), + &mut |event| { + if event == ExecutionEvent::Progress { + let _ = ready.send(task); + } + }, + ) + }) + }; + let first = start("first"); + let second = start("second"); + // Both turns are active at the same time. + let mut active = [ + ready_receiver + .recv_timeout(Duration::from_secs(5)) + .expect("a turn is active"), + ready_receiver + .recv_timeout(Duration::from_secs(5)) + .expect("a turn is active"), + ]; + active.sort_unstable(); + assert_eq!(active, ["first", "second"]); + server.cancel("first"); + assert_eq!( + first.join().expect("turn thread must join"), + Err(ExecutionError::Cancelled) + ); + std::thread::sleep(Duration::from_millis(100)); + assert!(!second.is_finished(), "a cancel of one turn must not stop the other"); + server.cancel("second"); + assert_eq!( + second.join().expect("turn thread must join"), + Err(ExecutionError::Cancelled) + ); + } + + #[test] + fn only_a_task_folder_lets_turns_run_side_by_side() { + let capacity = |sandbox| { + CodexAppServer::new( + PathBuf::from("codex"), + CodexLimits { + sandbox, + allow_network: false, + environment: BTreeMap::new(), + }, + ) + .expect("limits must be valid") + .capacity() + }; + assert_eq!(capacity(CodexSandbox::TaskFolder), usize::MAX); + assert_eq!(capacity(CodexSandbox::WorkspaceWrite), 1); + } + #[test] #[cfg(unix)] fn app_server_honours_a_cancel_that_comes_before_the_turn_starts() { diff --git a/crates/aether/src/agent/connected.rs b/crates/aether/src/agent/connected.rs index 62db8f6..57dc1a0 100644 --- a/crates/aether/src/agent/connected.rs +++ b/crates/aether/src/agent/connected.rs @@ -71,8 +71,14 @@ impl Turns { } } +/// How many tasks an agent takes at once when its `ready` does not say: one, +/// as every agent did before the node ran tasks side by side. +const DEFAULT_MAX_TASKS: usize = 1; + struct Connection { generation: u64, + /// The most open tasks that the agent said it takes at once. + max_tasks: usize, stream: UnixStream, writer: Writer, pending: Pending, @@ -96,11 +102,28 @@ enum NodeMessage<'a> { #[derive(Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] enum AgentMessage { - Ready { protocol: u64 }, - Progress { id: String }, - Result { id: String, text: String }, - Failed { id: String }, - Cancelled { id: String }, + Ready { + protocol: u64, + /// Any JSON value, so that a `ready` with a `max_tasks` that is not + /// a whole number still attaches the agent, which then takes one + /// task at a time. As a `u64` such a line would not parse, and the + /// node would skip it and wait for a `ready` that never comes. + #[serde(default)] + max_tasks: Option, + }, + Progress { + id: String, + }, + Result { + id: String, + text: String, + }, + Failed { + id: String, + }, + Cancelled { + id: String, + }, } impl ConnectedAgent { @@ -181,10 +204,14 @@ impl Shared { return; }; let mut reader = BufReader::new(stream); - match read_message(&mut reader) { - Some(AgentMessage::Ready { protocol: PROTOCOL }) => {} + let max_tasks = match read_message(&mut reader) { + Some(AgentMessage::Ready { protocol: PROTOCOL, max_tasks }) => max_tasks + .as_ref() + .and_then(serde_json::Value::as_u64) + .and_then(|tasks| usize::try_from(tasks).ok()) + .map_or(DEFAULT_MAX_TASKS, |tasks| tasks.max(1)), _ => return, - } + }; let generation = self.generation.fetch_add(1, Ordering::Relaxed).wrapping_add(1); let pending = Arc::new(Mutex::new(Turns::default())); @@ -200,6 +227,7 @@ impl Shared { .unwrap_or_default(); let replaced = connection.replace(Connection { generation, + max_tasks, stream: control, writer: Arc::new(Mutex::new(writer)), pending: Arc::clone(&pending), @@ -365,6 +393,17 @@ impl Agent for ConnectedAgent { cancels.forget(task_id); } } + + /// What the attached agent said in its `ready`; one when it said + /// nothing, or when no agent is attached. + fn capacity(&self) -> usize { + self.shared + .connection + .lock() + .ok() + .and_then(|connection| connection.as_ref().map(|current| current.max_tasks)) + .unwrap_or(DEFAULT_MAX_TASKS) + } } #[cfg(test)] @@ -611,6 +650,74 @@ mod tests { } } + #[test] + fn the_optional_fields_and_the_default_match_the_contract() { + let contract = json_file(CONTRACT); + assert_eq!(contract["default_max_tasks"], super::DEFAULT_MAX_TASKS); + assert_eq!( + contract["messages"]["optional_fields"]["ready"], + json!(["max_tasks"]) + ); + let ready = json!({"type": "ready", "protocol": PROTOCOL, "max_tasks": 3}); + assert!(matches!( + serde_json::from_value::(ready), + Ok(AgentMessage::Ready { protocol: PROTOCOL, max_tasks: Some(tasks) }) + if tasks == json!(3) + )); + } + + #[test] + fn the_agent_says_how_many_tasks_it_takes_at_once() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + // No agent: the capacity is the default. + assert_eq!(agent.capacity(), 1); + for (ready, capacity) in [ + (json!({"type": "ready", "protocol": 1}), 1), + (json!({"type": "ready", "protocol": 1, "max_tasks": 3}), 3), + (json!({"type": "ready", "protocol": 1, "max_tasks": 0}), 1), + // Not a whole number: the agent still attaches, with one task. + (json!({"type": "ready", "protocol": 1, "max_tasks": 2.5}), 1), + (json!({"type": "ready", "protocol": 1, "max_tasks": -1}), 1), + (json!({"type": "ready", "protocol": 1, "max_tasks": "2"}), 1), + (json!({"type": "ready", "protocol": 1, "max_tasks": null}), 1), + ] { + let _peer = Peer::attach(&agent, &path, &ready); + assert_eq!(agent.capacity(), capacity, "{ready}"); + } + } + + #[test] + fn two_turns_are_open_on_one_connection_and_end_separately() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + let mut peer = Peer::attach( + &agent, + &path, + &json!({"type": "ready", "protocol": 1, "max_tasks": 2}), + ); + let deadline = + Instant::now().checked_add(Duration::from_secs(5)).expect("deadline"); + let start = |id: &'static str| { + let mut runner = agent.clone(); + std::thread::spawn(move || runner.start_turn(&turn_ctx(id, id, deadline))) + }; + let first = start("task-1"); + assert_eq!(peer.read()["id"], "task-1"); + let second = start("task-2"); + assert_eq!(peer.read()["id"], "task-2"); + // An answer of the second task ends only the second turn. + peer.write(&json!({"type": "result", "id": "task-2", "text": "two"})); + assert_eq!(second.join().expect("turn joins"), Ok("two".to_owned())); + // A cancel reaches only the task that it names. + agent.cancel("task-1"); + assert_eq!(peer.read(), json!({"type": "cancel", "id": "task-1"})); + peer.write(&json!({"type": "cancelled", "id": "task-1"})); + assert_eq!(first.join().expect("turn joins"), Err(ExecutionError::Cancelled)); + } + #[test] fn the_socket_is_owner_only() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/execution.rs b/crates/aether/src/execution.rs index cd75e87..38d47fa 100644 --- a/crates/aether/src/execution.rs +++ b/crates/aether/src/execution.rs @@ -124,7 +124,38 @@ pub trait Agent { /// for a turn that has not started drops it here, so that the cancel /// does not stop a later turn of the same task. fn forget(&self, _task_id: &str) {} + /// How many turns this agent runs at once, whatever the owner's limit + /// says. The node never runs more. An adapter that cannot run turns + /// side by side (they would share a folder, or the agent takes one task + /// at a time) says 1. + fn capacity(&self) -> usize { + usize::MAX + } +} + +/// One turn that the executor checked and prepared. It owns its agent +/// handle, so it runs without the executor: other turns run at the same +/// time. +pub struct PreparedTurn

{ + agent: P, + ctx: TurnContext, + max_context_tokens: u32, +} + +impl PreparedTurn

{ + /// Confirms the start with `on_confirmed_start`, then runs the turn. + /// The start is confirmed once, before the agent gets the task. + pub fn run( + mut self, + on_confirmed_start: &mut dyn FnMut() -> Result<(), ExecutionError>, + events: &mut dyn FnMut(ExecutionEvent), + ) -> Result { + on_confirmed_start()?; + let result = self.agent.start_turn_with_events(&self.ctx, events)?; + bounded_output(result, self.max_context_tokens) + } } + pub struct Executor

{ process: P, allowed_root: PathBuf, @@ -151,12 +182,9 @@ impl Executor

{ self.allowed_root.canonicalize().map_err(|_| ExecutionError::Path) } - pub fn execute_with_confirmed_start( - &mut self, - task: &Task, - on_confirmed_start: &mut dyn FnMut() -> Result<(), ExecutionError>, - events: &mut dyn FnMut(ExecutionEvent), - ) -> Result { + /// Checks `task` against the limits and the workspace, and builds the + /// context of its turn. + fn turn_context(&self, task: &Task) -> Result { if self.max_context_tokens == 0 || self.max_seconds == 0 || input_tokens(task) > self.max_context_tokens @@ -175,20 +203,27 @@ impl Executor

{ let deadline = Instant::now() .checked_add(std::time::Duration::from_secs(self.max_seconds)) .ok_or(ExecutionError::Limits)?; - let ctx = TurnContext { + Ok(TurnContext { task_id: task.id.clone(), skill: task.skill.clone(), text: task.remote_text.clone(), workspace, deadline, - }; + }) + } + + pub fn execute_with_confirmed_start( + &mut self, + task: &Task, + on_confirmed_start: &mut dyn FnMut() -> Result<(), ExecutionError>, + events: &mut dyn FnMut(ExecutionEvent), + ) -> Result { + let ctx = self.turn_context(task)?; on_confirmed_start()?; let result = self.process.start_turn_with_events(&ctx, events)?; - if token_count(&result) > self.max_context_tokens { - return Err(ExecutionError::Limits); - } - Ok(result) + bounded_output(result, self.max_context_tokens) } + pub fn cancel(&self, task_id: &str) { self.process.cancel(task_id); } @@ -208,6 +243,22 @@ impl Executor

{ } impl Executor

{ + /// Checks `task` and takes a handle of the agent for its turn. The + /// caller runs the turn without the executor, so turns of several tasks + /// run at the same time; the executor is needed only for this call. + /// + /// # Errors + /// + /// The `ExecutionError` of a task that the limits or the workspace + /// refuse. + pub fn prepare_turn(&self, task: &Task) -> Result, ExecutionError> { + Ok(PreparedTurn { + ctx: self.turn_context(task)?, + agent: self.process.clone(), + max_context_tokens: self.max_context_tokens, + }) + } + #[must_use] pub fn cancellation_handle(&self) -> P { self.process.clone() @@ -219,6 +270,17 @@ impl Executor

{ } } +/// `result`, unless it is longer than `max_context_tokens`. +fn bounded_output( + result: String, + max_context_tokens: u32, +) -> Result { + if token_count(&result) > max_context_tokens { + return Err(ExecutionError::Limits); + } + Ok(result) +} + fn input_tokens(task: &Task) -> u32 { token_count(&task.skill).saturating_add(token_count(&task.remote_text)) } diff --git a/crates/aether/src/fixture.rs b/crates/aether/src/fixture.rs index 25d7c1d..afcd135 100644 --- a/crates/aether/src/fixture.rs +++ b/crates/aether/src/fixture.rs @@ -23,6 +23,7 @@ pub struct PolicyLimits { pub max_seconds: u64, pub queue_global: u64, pub queue_per_peer: u64, + pub running_tasks: u64, } impl Default for PolicyLimits { @@ -32,6 +33,7 @@ impl Default for PolicyLimits { max_seconds: 10, queue_global: 1, queue_per_peer: 1, + running_tasks: 1, } } } @@ -157,6 +159,7 @@ pub fn policy_json( "maxSeconds": limits.max_seconds, "queueGlobal": limits.queue_global, "queuePerPeer": limits.queue_per_peer, + "runningTasks": limits.running_tasks, }) } diff --git a/crates/aether/src/hub_client.rs b/crates/aether/src/hub_client.rs index 6223815..02c06c1 100644 --- a/crates/aether/src/hub_client.rs +++ b/crates/aether/src/hub_client.rs @@ -95,6 +95,7 @@ impl HubClient { /// A client for the hub at `origin` that signs with `key`. pub fn new(origin: &str, key: iroh::SecretKey) -> Result { let origin = parse_origin(origin)?; + crate::node_runtime::install_crypto_provider(); // The long poll holds a request open for up to MAX_WAIT_SECONDS. let client = Client::builder() .redirect(Policy::none()) diff --git a/crates/aether/src/hub_client/protocol.rs b/crates/aether/src/hub_client/protocol.rs index 2a523b9..cc43f58 100644 --- a/crates/aether/src/hub_client/protocol.rs +++ b/crates/aether/src/hub_client/protocol.rs @@ -239,6 +239,7 @@ pub fn wire_error(status: u16, code: Option<&str>) -> HubError { (400 | 413, _) => HubError::Invalid, (429, _) => HubError::RateLimited, (426, _) => HubError::OldNode, + (503, _) => HubError::Unreachable, _ => HubError::Unexpected, } } @@ -451,6 +452,7 @@ mod tests { "limit" => HubError::Limit, "upgrade_required" => HubError::OldNode, "rate_limited" => HubError::RateLimited, + "unavailable" => HubError::Unreachable, _ => HubError::Unexpected, }; assert_eq!(mapped, expected, "{code}"); diff --git a/crates/aether/src/identity.rs b/crates/aether/src/identity.rs index 6e2bd13..96a0d5d 100644 --- a/crates/aether/src/identity.rs +++ b/crates/aether/src/identity.rs @@ -1,5 +1,6 @@ use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashSet}, + sync::{Mutex, PoisonError}, time::{Duration, SystemTime}, }; @@ -9,7 +10,51 @@ use aether_core::{ }; use ed25519_dalek::SigningKey; -use crate::signed::{SignedBytes, sign, verify}; +use crate::{ + settings::KeptStore, + signed::{SignedBytes, sign, verify}, +}; + +/// A signature that verified: the issuer key, the signature and the exact +/// bytes that it signs. +type VerifiedSignature = ([u8; 32], Vec, Vec); + +/// How many verified signatures the node remembers. +const VERIFIED_CAPACITY: usize = 1024; + +/// The signatures that [`verify_cached`] verified. +static VERIFIED: Mutex>> = Mutex::new(None); + +/// [`verify`] with a memory of the signatures that verified. A signature +/// that verified once verifies again for the same key and bytes, so an +/// admission does not run the ed25519 check twice for one grant. This keeps +/// only that cryptographic result. Whether the issuer is trusted, and the +/// expiry, scope and every other check, still run on each admission, and a +/// failed signature is not kept. +fn verify_cached( + signing_key: &[u8; 32], + message: &[u8], + signature: &[u8], +) -> Result<(), crate::signed::Forged> { + let key: VerifiedSignature = (*signing_key, signature.to_vec(), message.to_vec()); + if VERIFIED + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .is_some_and(|verified| verified.contains(&key)) + { + return Ok(()); + } + verify(signing_key, message, signature)?; + let mut guard = VERIFIED.lock().unwrap_or_else(PoisonError::into_inner); + let verified = guard.get_or_insert_with(HashSet::new); + if verified.len() >= VERIFIED_CAPACITY { + verified.clear(); + } + verified.insert(key); + drop(guard); + Ok(()) +} /// The issuer name of the node's own signing key, which the node always /// trusts. The admin UI signs a friend's access with it. @@ -22,7 +67,8 @@ pub struct SignedClaims { pub struct RosterClaims { signed_claims: SignedClaims, - data_dir: crate::data_dir::DataDir, + /// The roster store, which stays open between admissions. + roster: Mutex, } pub struct ClaimInput { @@ -87,11 +133,14 @@ struct Signed<'a> { impl RosterClaims { #[must_use] - pub const fn new( + pub fn new( signed_claims: SignedClaims, - data_dir: crate::data_dir::DataDir, + data_dir: &crate::data_dir::DataDir, ) -> Self { - Self { signed_claims, data_dir } + Self { + signed_claims, + roster: Mutex::new(KeptStore::new(data_dir.path().to_path_buf(), true)), + } } } @@ -115,9 +164,10 @@ impl TrustProvider for SignedClaims { { return Err(ProviderError::Invalid("claim is not trusted".to_owned())); } - verify(&claim.signing_key, &claim_bytes(claim), &claim.signature).map_err( - |_| ProviderError::Invalid("claim signature is invalid".to_owned()), - ) + verify_cached(&claim.signing_key, &claim_bytes(claim), &claim.signature) + .map_err(|_| { + ProviderError::Invalid("claim signature is invalid".to_owned()) + }) } fn verify_grant(&self, grant: &Grant, scope: &Scope) -> Result<(), ProviderError> { @@ -132,9 +182,10 @@ impl TrustProvider for SignedClaims { if !self.trusts(&signed, scope) { return Err(ProviderError::Invalid("grant is not trusted".to_owned())); } - verify(&grant.signing_key, &grant_bytes(grant), &grant.signature).map_err( - |_| ProviderError::Invalid("grant signature is invalid".to_owned()), - ) + verify_cached(&grant.signing_key, &grant_bytes(grant), &grant.signature) + .map_err(|_| { + ProviderError::Invalid("grant signature is invalid".to_owned()) + }) } } @@ -149,18 +200,19 @@ impl TrustProvider for RosterClaims { if scope.kind != ScopeKind::Managed { return Ok(()); } - let store = self.data_dir.store().map_err(|_| ProviderError::Unavailable)?; let now = aether_core::time::unix_timestamp(SystemTime::now()) .ok_or(ProviderError::Unavailable)?; - let active = store - .managed_members(scope.id.as_str()) - .map_err(|_| ProviderError::Unavailable)? - .into_iter() - .any(|member| { - member.agent_id == claim.subject_agent_id.as_str() - && member.endpoint_id == authenticated_endpoint.as_str() - && member.is_active(now) - }); + let members = self + .roster + .lock() + .unwrap_or_else(PoisonError::into_inner) + .read(|store| store.managed_members(scope.id.as_str())) + .map_err(|_| ProviderError::Unavailable)?; + let active = members.into_iter().any(|member| { + member.agent_id == claim.subject_agent_id.as_str() + && member.endpoint_id == authenticated_endpoint.as_str() + && member.is_active(now) + }); if active { Ok(()) } else { @@ -637,7 +689,7 @@ mod tests { nonce: [6; 32], }, ); - let trust = RosterClaims::new(provider(&key), data_dir); + let trust = RosterClaims::new(provider(&key), &data_dir); let scope = Scope { id: ScopeId::new("managed"), kind: ScopeKind::Managed }; assert!(trust.verify(&claim, &EndpointId::new("endpoint"), &scope,).is_ok()); store @@ -669,4 +721,88 @@ mod tests { assert_eq!(claim.subject_endpoint_id.as_str(), "friend-endpoint"); assert_eq!(claim.signing_key, grant.signing_key); } + + #[test] + fn a_remembered_signature_does_not_skip_the_other_grant_checks() { + let key = SigningKey::from_bytes(&[8; 32]); + let valid = signed_test_grant(&key, |_| {}); + assert!(verify_grant(&provider(&key), &valid)); + // The signature is remembered now; the issuer is still checked. + assert!(!verify_grant( + &SignedClaims::new(BTreeMap::new(), Duration::ZERO), + &valid + )); + // An expired grant is refused although its signature verified. + let expired = signed_test_grant(&key, |input| { + input.issued_at = SystemTime::now() - Duration::from_secs(120); + input.expires_at = SystemTime::now() - Duration::from_secs(60); + }); + super::verify_cached( + &expired.signing_key, + &super::grant_bytes(&expired), + &expired.signature, + ) + .expect("the signature is valid"); + assert!(!verify_grant(&provider(&key), &expired)); + // Another scope is refused too. + assert!( + provider(&key) + .verify_grant( + &valid, + &Scope { id: ScopeId::new("other"), kind: ScopeKind::Direct }, + ) + .is_err() + ); + } + + #[test] + fn a_remembered_signature_is_for_its_exact_bytes_and_key() { + let key = SigningKey::from_bytes(&[9; 32]); + let other = SigningKey::from_bytes(&[10; 32]); + let valid = signed_test_grant(&key, |_| {}); + let bytes = super::grant_bytes(&valid); + super::verify_cached(&valid.signing_key, &bytes, &valid.signature) + .expect("valid"); + super::verify_cached(&valid.signing_key, &bytes, &valid.signature) + .expect("valid again, from memory"); + let mut changed = bytes.clone(); + changed.push(0); + assert!( + super::verify_cached(&valid.signing_key, &changed, &valid.signature) + .is_err() + ); + let mut forged = valid.signature.clone(); + forged.reverse(); + assert!(super::verify_cached(&valid.signing_key, &bytes, &forged).is_err()); + assert!( + super::verify_cached( + &other.verifying_key().to_bytes(), + &bytes, + &valid.signature + ) + .is_err() + ); + // A failure is not remembered as a success. + assert!( + super::verify_cached(&valid.signing_key, &changed, &valid.signature) + .is_err() + ); + } + + #[test] + fn the_memory_of_signatures_stays_bounded() { + let key = SigningKey::from_bytes(&[11; 32]); + for index in 0..super::VERIFIED_CAPACITY.saturating_add(10) { + let message = index.to_le_bytes(); + let signature = super::sign(&key, &message); + super::verify_cached(&key.verifying_key().to_bytes(), &message, &signature) + .expect("valid"); + } + let size = super::VERIFIED + .lock() + .expect("lock") + .as_ref() + .map_or(0, std::collections::HashSet::len); + assert!(size <= super::VERIFIED_CAPACITY); + } } diff --git a/crates/aether/src/main.rs b/crates/aether/src/main.rs index 6877506..e062ce0 100644 --- a/crates/aether/src/main.rs +++ b/crates/aether/src/main.rs @@ -279,6 +279,7 @@ struct McpServe { #[tokio::main] async fn main() -> ExitCode { + aether::node_runtime::install_crypto_provider(); match Arguments::parse().command { CliCommand::Node(node) => Box::pin(run_node(*node)).await, CliCommand::Control(process) => run_control(process).await, @@ -327,7 +328,7 @@ async fn run_control(control: Control) -> ExitCode { let handle = axum_server::Handle::new(); let shutdown = handle.clone(); tokio::spawn(async move { - if tokio::signal::ctrl_c().await.is_ok() { + if aether::node_runtime::shutdown_signal().await.is_ok() { shutdown.graceful_shutdown(Some(std::time::Duration::from_secs(5))); } }); diff --git a/crates/aether/src/mcp/tools/admin.rs b/crates/aether/src/mcp/tools/admin.rs index 85527c7..9662ef4 100644 --- a/crates/aether/src/mcp/tools/admin.rs +++ b/crates/aether/src/mcp/tools/admin.rs @@ -53,6 +53,8 @@ pub struct PolicyUpdateArguments { pub max_seconds: Option, pub queue_global: Option, pub queue_per_peer: Option, + /// How many tasks the node runs at once, from 1 to 32. + pub running_tasks: Option, #[serde(default)] pub dry_run: bool, } @@ -114,6 +116,7 @@ impl McpServer { "maxSeconds": settings.max_seconds, "queueGlobal": settings.queue.global, "queuePerPeer": settings.queue.per_peer, + "runningTasks": settings.queue.running, }) }), Err(_) => return tool_error("the node policy is unavailable"), @@ -151,6 +154,7 @@ impl McpServer { && arguments.max_seconds.is_none() && arguments.queue_global.is_none() && arguments.queue_per_peer.is_none() + && arguments.running_tasks.is_none() { return tool_error("give at least one policy field"); } @@ -165,6 +169,7 @@ impl McpServer { max_seconds: arguments.max_seconds, queue_global: arguments.queue_global, queue_per_peer: arguments.queue_per_peer, + running_tasks: arguments.running_tasks, dry_run: arguments.dry_run, }) { Ok(Response::Validated) => tool_success( @@ -603,6 +608,7 @@ mod tests { max_seconds: Some(75), queue_global: Some(2), queue_per_peer: None, + running_tasks: None, dry_run: true, }; let validated = server.settings_update_policy(Parameters(request)).await; @@ -621,6 +627,7 @@ mod tests { max_seconds: Some(75), queue_global: None, queue_per_peer: None, + running_tasks: None, dry_run: false, })) .await; @@ -641,6 +648,7 @@ mod tests { max_seconds: Some(76), queue_global: Some(2), queue_per_peer: None, + running_tasks: None, dry_run: false, })) .await; diff --git a/crates/aether/src/node_builder.rs b/crates/aether/src/node_builder.rs index 1140ec1..bbd6c4e 100644 --- a/crates/aether/src/node_builder.rs +++ b/crates/aether/src/node_builder.rs @@ -25,6 +25,7 @@ use crate::{ policy::{ AgentAdapter, PolicyError, PolicyFile, PolicySandbox, decode_key, default_sandbox, keep, load_or_create, parse_scopes, stored_queue_limits, + stored_running_limit, }, proof::ProofNode, }; @@ -136,6 +137,7 @@ fn build( signed_claims.verify_grant(grant, scope).map_err(|_| PolicyError::Invalid)?; } let queue_limits = stored_queue_limits(&store, queue)?; + let running_limit = stored_running_limit(&store, queue)?; let stored_workspace = store.current_workspace().map_err(|_| PolicyError::Invalid)?; let stored_grants = store @@ -170,7 +172,7 @@ fn build( store .initialize_access_groups(&initial_members) .map_err(|_| PolicyError::Invalid)?; - let trust = RosterClaims::new(signed_claims, layout.clone()); + let trust = RosterClaims::new(signed_claims, &layout); let workspace = resolve_workspace(&policy.workspace, &layout)?; let agent = match sandbox { Some(sandbox) => NodeAgent::Codex(codex_agent( @@ -205,6 +207,7 @@ fn build( scopes, ) .map_err(|_| PolicyError::Invalid)?; + node.set_running_limit(running_limit).map_err(|_| PolicyError::Invalid)?; let task_folder_mode = matches!(sandbox, Some(PolicySandbox::TaskFolder)); // Fail closed the same way the policy file's own `workspace` field // already does: a named-but-missing approved directory is a @@ -503,6 +506,53 @@ mod tests { path } + #[test] + fn the_node_runs_one_task_at_a_time_unless_its_owner_says_more() { + let directory = tempfile::tempdir().expect("directory must create"); + let root = directory.path().to_path_buf(); + // A policy file from before the limit existed. + let path = minimal_policy(&root); + let service = load_service(&path, &root, "codex".into()).expect("policy loads"); + assert_eq!(service.running_limit().expect("limit reads"), 1); + drop(service); + // A limit that the owner changed on the running node is kept. + let mut store = NodeStore::in_dir(&root).expect("store must open"); + store + .apply_change( + aether_store::ChangeKind::Limit, + aether_core::limits::QueueLimitId::Running.as_str(), + "3", + aether_store::AuditActor::Ui, + 1, + ) + .expect("running limit must store"); + drop(store); + let service = load_service(&path, &root, "codex".into()) + .expect("stored running limit must load"); + assert_eq!(service.running_limit().expect("limit reads"), 3); + drop(service); + // A policy file that names the limit starts with it. + let mut policy: serde_json::Value = + serde_json::from_slice(&fs::read(&path).expect("policy reads")) + .expect("policy decodes"); + policy["runningTasks"] = json!(2); + let other = tempfile::tempdir().expect("directory must create"); + let other_root = other.path().to_path_buf(); + let other_path = minimal_policy(&other_root); + policy["workspace"] = json!(other_root.join("workspace")); + fs::write(&other_path, policy.to_string()).expect("policy writes"); + let service = load_service(&other_path, &other_root, "codex".into()) + .expect("policy with a running limit loads"); + assert_eq!(service.running_limit().expect("limit reads"), 2); + // A value that the owner could not set is refused at start. + policy["runningTasks"] = json!(33); + fs::write(&other_path, policy.to_string()).expect("policy writes"); + assert!(matches!( + load_service(&other_path, &other_root, "codex".into()), + Err(PolicyError::InvalidField(field)) if field == "runningTasks" + )); + } + #[test] fn task_folders_are_the_policy_default_and_refuse_workspace_changes() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/node_runtime.rs b/crates/aether/src/node_runtime.rs index e1ef612..28dc6db 100644 --- a/crates/aether/src/node_runtime.rs +++ b/crates/aether/src/node_runtime.rs @@ -462,7 +462,7 @@ pub async fn run(options: NodeServeOptions) -> Result<(), NodeRunError> { let router = transport::router(endpoint.clone(), move |peer, frames| { service.a2a().handle(peer, frames) }); - let mut result = match tokio::signal::ctrl_c().await { + let mut result = match shutdown_signal().await { Ok(()) => router .shutdown() .await @@ -647,6 +647,39 @@ async fn publish_record( Some((directory_publication, record)) } +/// Makes `ring` the process-wide rustls crypto provider, once. +/// +/// Without a default, reqwest builds its TLS client on `aws-lc-rs`, whose +/// first `RAND_bytes` call (the `ClientHello` random) seeds a jitter-entropy +/// source that costs about 100 ms of CPU. `ring` draws from the operating +/// system's generator, as `iroh` and the control service already do. A +/// default that is already installed stays. +pub fn install_crypto_provider() { + let _ = rustls::crypto::ring::default_provider().install_default(); +} + +/// Resolves when the process is asked to stop: Ctrl-C everywhere, and on +/// unix also SIGTERM, which `docker stop` and systemd send. An error means +/// a signal handler could not be installed. +/// +/// # Errors +/// Returns the I/O error from installing the signal handler. +pub async fn shutdown_signal() -> std::io::Result<()> { + #[cfg(unix)] + { + let mut terminate = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + tokio::select! { + result = tokio::signal::ctrl_c() => result, + _ = terminate.recv() => Ok(()), + } + } + #[cfg(not(unix))] + { + tokio::signal::ctrl_c().await + } +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -705,6 +738,29 @@ mod tests { ); } + #[cfg(unix)] + #[tokio::test] + async fn sigterm_ends_the_wait_for_a_shutdown_signal() { + let signal = super::shutdown_signal(); + tokio::pin!(signal); + // The first poll installs the handler; only then is SIGTERM safe to + // send to this process. + assert!( + tokio::time::timeout(std::time::Duration::from_millis(50), &mut signal) + .await + .is_err() + ); + let status = std::process::Command::new("kill") + .args(["-TERM", &std::process::id().to_string()]) + .status() + .expect("kill must run"); + assert!(status.success()); + tokio::time::timeout(std::time::Duration::from_secs(5), signal) + .await + .expect("SIGTERM must end the wait") + .expect("the handler must install"); + } + #[test] fn publication_flags_must_be_all_set_or_all_unset() { assert!(matches!(PublicationFlags::default().complete(), Ok(None))); diff --git a/crates/aether/src/node_service.rs b/crates/aether/src/node_service.rs index 3810046..ae31af3 100644 --- a/crates/aether/src/node_service.rs +++ b/crates/aether/src/node_service.rs @@ -185,6 +185,12 @@ where self.proof().queue_limits() } + /// How many tasks the node runs at once, as its owner set it. The agent + /// can run fewer; see [`ProofNode::effective_running_limit`]. + pub fn running_limit(&self) -> Result { + self.proof().current_queue_limit(aether_core::limits::QueueLimitId::Running) + } + pub fn shutdown(&self) where T: TrustProvider + 'static, diff --git a/crates/aether/src/outbox.rs b/crates/aether/src/outbox.rs index a5f237b..03e1d6d 100644 --- a/crates/aether/src/outbox.rs +++ b/crates/aether/src/outbox.rs @@ -21,6 +21,7 @@ use aether_store::{ use crate::{ direct::{InvitationBundle, RequestIds}, + settings::KeptStore, transport::{ A2aAuthorization, A2aTaskStatus, Frame, FrameKind, Link, TransportError, }, @@ -34,8 +35,17 @@ pub const LEASE: Duration = Duration::from_secs(90); pub const MAX_PARALLEL: usize = 4; pub const RETENTION: Duration = Duration::from_hours(7 * 24); pub const OFFLINE_PROBE: Duration = Duration::from_mins(30); +/// The longest pause between rounds while rounds fail. +const ERROR_PAUSE_CAP: Duration = Duration::from_secs(30); + +/// The pause before the next attempt after the rate limit of the agent shed +/// the requests of an attempt. It is short and does not grow: the limit +/// refills within a second, and the task is not stuck, as one behind a full +/// queue is. +const RATE_LIMITED_PAUSE: Duration = Duration::from_secs(2); const UNREACHABLE: &str = "the agent cannot be reached; it may be offline"; +const RATE_LIMITED: &str = "the agent is busy with other requests from this node"; const ACCESS_ENDED: &str = "the access to this agent ended"; const EXPIRED: &str = "the agent did not answer before the deadline"; const PURGE_KEY: &str = "outbox.last_purge"; @@ -149,7 +159,6 @@ pub fn enqueue( created_at: now, expires_at: now.saturating_add(seconds(MAX_WAIT)).min(access_ends), }; - let store = NodeStore::in_dir(data_dir).map_err(|_| OutboxError::Unavailable)?; store.insert_sent_task(&input).map_err(|_| OutboxError::Unavailable)?; store.sent_task(&ids.task_id).ok().flatten().ok_or(OutboxError::Unavailable) } @@ -161,6 +170,10 @@ pub enum Delay { Working, /// The queue of the agent is full. Busy, + /// The per-peer rate limit of the agent shed the requests of this node, + /// also after `follow` sent them again for a while. The agent has the + /// task, or room for it: the limit refills within a second. + RateLimited, /// The agent cannot be reached. Unreachable, } @@ -170,6 +183,7 @@ pub enum Delay { pub fn next_delay(delay: Delay, attempts: u64) -> Duration { let (first, cap) = match delay { Delay::Working => return Duration::from_secs(5), + Delay::RateLimited => return RATE_LIMITED_PAUSE, Delay::Busy => (Duration::from_secs(5), Duration::from_mins(5)), Delay::Unreachable => (Duration::from_secs(30), OFFLINE_PROBE), }; @@ -219,6 +233,12 @@ pub fn outcome(task_id: &str, result: Result, TransportError>) -> Out return Outcome::waiting(UNREACHABLE, Delay::Unreachable); }; let last_event_sequence = crate::transport::response_last_event_sequence(&frames); + // The rate limit sends the same message as a full queue, with + // `retryAfterMs` in its `data`. It admitted nothing, so the task is + // neither refused nor stuck behind a queue: ask again soon. + if crate::transport::is_rate_limited(&frames) { + return Outcome::waiting(RATE_LIMITED, Delay::RateLimited); + } if frames.last().is_some_and(|frame| frame.kind == FrameKind::Error) { let message = frames .last() @@ -302,16 +322,13 @@ pub async fn attempt( task: &SentTask, window: Duration, ) -> Result { - let data_dir = data_dir.to_path_buf(); + let store = open_shared(data_dir); let endpoint_id = task.endpoint_id.clone(); - let (store, bundle) = off_runtime(move || { - let store = - NodeStore::in_dir(&data_dir).map_err(|_| OutboxError::Unavailable)?; - let bundle = crate::direct::contact_by_endpoint(&store, &endpoint_id).ok(); - Ok((store, bundle)) + let bundle = with_store(&store, move |store| { + Ok(crate::direct::contact_by_endpoint(store, &endpoint_id).ok()) }) .await?; - attempt_in(&Arc::new(Mutex::new(store)), courier, task, bundle, window).await + attempt_in(&store, courier, task, bundle, window).await } /// [`attempt`] with an open store and the bundle of the task's contact. @@ -379,6 +396,8 @@ async fn follow( let mut after = task.last_event_sequence; let mut link = Link::default(); let mut replayed = false; + let mut shed_since: Option = None; + let mut shed_retries: u32 = 0; loop { let frame = crate::direct::resend_frame( authorization.clone(), @@ -395,6 +414,27 @@ async fn follow( replayed = true; continue; } + // The per-peer rate limit of the agent shed the frame before the + // agent saw it, also in the middle of a poll. Send it again a little + // later with a new frame, as `request_with_polling_on` does, but + // never past the attempt window. A full queue is not retried: it is + // the `Busy` delay of `outcome`. + if result.as_ref().is_ok_and(|frames| crate::transport::is_rate_limited(frames)) + { + let since = *shed_since.get_or_insert_with(std::time::Instant::now); + if let Some(wait) = crate::transport::overload_retry_wait( + shed_retries, + since.elapsed(), + window.saturating_sub(started.elapsed()), + ) { + tokio::time::sleep(wait).await; + shed_retries = shed_retries.saturating_add(1); + continue; + } + } else { + shed_since = None; + shed_retries = 0; + } // An ended status is not enough to stop: the host cut the page // before the last event when it says that more events remain. let more_events = result @@ -439,8 +479,10 @@ fn is_replay(result: &Result, TransportError>) -> bool { }) } -/// The node store of one round, shared by its attempts. -type SharedStore = Arc>; +/// The node store of a round and its attempts. It stays open between rounds +/// and opens again when the database file is replaced or migrated by another +/// binary (see [`KeptStore`]), so `enqueue` and the loop use the same file. +type SharedStore = Arc>; async fn off_runtime( work: impl FnOnce() -> Result + Send + 'static, @@ -448,13 +490,18 @@ async fn off_runtime( tokio::task::spawn_blocking(work).await.map_err(|_| OutboxError::Unavailable)? } +/// Runs `work` on the current store, off the runtime. The work runs once: +/// a store that fails to open is [`OutboxError::Unavailable`]. async fn with_store( store: &SharedStore, work: impl FnOnce(&mut NodeStore) -> Result + Send + 'static, ) -> Result { let store = Arc::clone(store); - off_runtime(move || work(&mut store.lock().unwrap_or_else(PoisonError::into_inner))) - .await + off_runtime(move || { + let mut kept = store.lock().unwrap_or_else(PoisonError::into_inner); + work(kept.current().map_err(|_| OutboxError::Unavailable)?) + }) + .await } /// What one round of the outbox did. @@ -477,15 +524,30 @@ pub async fn run_once( presence: Option<&BTreeMap>, now: i64, ) -> Result { - let data_dir = data_dir.to_path_buf(); + let store = open_shared(data_dir); + run_round(&store, courier, presence, now).await +} + +/// The node store of `data_dir`, for rounds to share. It opens on first use. +fn open_shared(data_dir: &Path) -> SharedStore { + Arc::new(Mutex::new(KeptStore::new(data_dir.to_path_buf(), false))) +} + +/// One round on an open `store`; [`run`] keeps one store for all its rounds. +async fn run_round( + store: &SharedStore, + courier: Arc, + presence: Option<&BTreeMap>, + now: i64, +) -> Result { let presence = presence.cloned(); - let Round { store, contacts, claimed } = - off_runtime(move || start_round(&data_dir, presence.as_ref(), now)).await?; - let store: SharedStore = Arc::new(Mutex::new(store)); + let Round { contacts, claimed } = + with_store(store, move |store| start_round(store, presence.as_ref(), now)) + .await?; let mut attempts = tokio::task::JoinSet::new(); for task in claimed { let courier = Arc::clone(&courier); - let store = Arc::clone(&store); + let store = Arc::clone(store); let bundle = contacts.get(&task.endpoint_id).cloned(); attempts.spawn(async move { let state = @@ -500,7 +562,7 @@ pub async fn run_once( report.attempted.push((task_id, state)); } } - report.active = with_store(&store, move |store| { + report.active = with_store(store, move |store| { purge_hourly(store, now); store.has_active_sent_tasks().map_err(|_| OutboxError::Unavailable) }) @@ -510,7 +572,6 @@ pub async fn run_once( /// A round after its store part, before its attempts. struct Round { - store: NodeStore, /// The bundle of each contact, by endpoint. contacts: BTreeMap, claimed: Vec, @@ -519,17 +580,15 @@ struct Round { /// The store part of a round before its attempts: it ends, wakes and defers /// tasks, and claims the due ones. fn start_round( - data_dir: &Path, + store: &mut NodeStore, presence: Option<&BTreeMap>, now: i64, ) -> Result { - let mut store = - NodeStore::in_dir(data_dir).map_err(|_| OutboxError::Unavailable)?; let busy = |_: StoreError| OutboxError::Unavailable; store.expire_sent_tasks(now, EXPIRED).map_err(busy)?; let active = store.active_sent_tasks().map_err(busy)?; // A contact that cannot be read counts as gone, as each lookup did. - let contacts = crate::direct::contacts_by_endpoint(&store).unwrap_or_default(); + let contacts = crate::direct::contacts_by_endpoint(store).unwrap_or_default(); let mut endpoints: BTreeMap> = BTreeMap::new(); for task in &active { endpoints.entry(task.endpoint_id.clone()).or_default().push(task); @@ -560,7 +619,7 @@ fn start_round( let claimed = store .claim_due_sent_tasks(now, now.saturating_add(seconds(LEASE)), MAX_PARALLEL) .map_err(busy)?; - Ok(Round { store, contacts, claimed }) + Ok(Round { contacts, claimed }) } /// Deletes the tasks that ended more than [`RETENTION`] ago, at most once an @@ -579,6 +638,23 @@ fn purge_hourly(store: &NodeStore, now: i64) { } } +/// The pause after `failures` rounds in a row that failed: [`POLL_INTERVAL`] +/// doubled for each failure after the first, up to [`ERROR_PAUSE_CAP`]. +fn error_pause(failures: u32) -> Duration { + let doublings = failures.saturating_sub(1).min(16); + let factor = 1_u32.checked_shl(doublings).unwrap_or(1); + POLL_INTERVAL.saturating_mul(factor).min(ERROR_PAUSE_CAP) +} + +/// One round of [`run`] on the `store` that all its rounds share. +async fn next_round( + store: &SharedStore, + courier: &Arc, + presence: Option<&BTreeMap>, +) -> Result { + run_round(store, Arc::clone(courier), presence, now()).await +} + /// Runs the outbox until the task is aborted. /// /// `wake` starts a round at once; else a round runs each second while tasks @@ -596,6 +672,11 @@ pub async fn run( let mut presence: Option> = None; let mut presence_read: Option = None; let mut active = true; + // The store stays open between rounds. It opens the file again when the + // path names another file or another binary migrated it, and a failed + // round makes it open again too. + let store = open_shared(&data_dir); + let mut failures: u32 = 0; loop { if active && presence_read.is_none_or(|read| read.elapsed() >= PRESENCE_INTERVAL) @@ -616,12 +697,22 @@ pub async fn run( }; presence_read = Some(std::time::Instant::now()); } - match run_once(&data_dir, Arc::clone(&courier), presence.as_ref(), now()).await - { - Ok(report) => active = report.active, - Err(_) => active = true, + let round = next_round(&store, &courier, presence.as_ref()).await; + if let Ok(report) = round { + active = report.active; + failures = 0; + } else { + active = true; + failures = failures.saturating_add(1); + store.lock().unwrap_or_else(PoisonError::into_inner).close(); } - let pause = if active { POLL_INTERVAL } else { Duration::from_secs(30) }; + let pause = if failures > 0 { + error_pause(failures) + } else if active { + POLL_INTERVAL + } else { + Duration::from_secs(30) + }; tokio::select! { () = wake.notified() => {} () = tokio::time::sleep(pause) => {} @@ -641,6 +732,15 @@ mod tests { use aether_store::{NodeStore, SentState}; + #[test] + fn failed_rounds_back_off_to_a_cap_and_a_good_round_resets_the_pause() { + let pauses: Vec = + (1..=8).map(|failures| super::error_pause(failures).as_secs()).collect(); + assert_eq!(pauses, [1, 2, 4, 8, 16, 30, 30, 30]); + assert_eq!(super::error_pause(u32::MAX), super::ERROR_PAUSE_CAP); + assert_eq!(super::error_pause(0), super::POLL_INTERVAL); + } + #[test] fn response_linger_outlives_the_poll_interval() { assert!( @@ -724,6 +824,20 @@ mod tests { }]) } + /// The "node overloaded" answer of the host's per-peer rate limit. + #[expect(clippy::unnecessary_wraps, reason = "a scripted answer is a Result")] + fn rate_limited() -> Result, TransportError> { + let request = Frame { + version: 0, + kind: FrameKind::Request, + exchange_id: "e".to_owned(), + scope_id: "direct".to_owned(), + task_id: None, + payload: serde_json::json!({}), + }; + Ok(crate::transport::rate_limited_response(&[request])) + } + /// A caller data directory with the contact `tudor`. fn caller() -> (tempfile::TempDir, tempfile::TempDir) { let host = tempfile::tempdir().expect("directory must create"); @@ -742,6 +856,14 @@ mod tests { let task = "00000000-0000-4000-8000-000000000001"; let busy = outcome(task, error("node overloaded")); assert_eq!((busy.state, busy.delay), (SentState::Waiting, Some(Delay::Busy))); + // The rate limit has the same message, and its own reason and delay. + let limited = outcome(task, rate_limited()); + assert_eq!( + (limited.state, limited.delay), + (SentState::Waiting, Some(Delay::RateLimited)) + ); + assert_eq!(limited.reason.as_deref(), Some(super::RATE_LIMITED)); + assert_eq!(busy.reason.as_deref(), Some("the queue of the agent is full")); for message in [ "permission denied", "task result has expired", @@ -787,6 +909,10 @@ mod tests { assert_eq!(next_delay(Delay::Unreachable, 2), Duration::from_secs(120)); assert_eq!(next_delay(Delay::Unreachable, 99), super::OFFLINE_PROBE); assert_eq!(next_delay(Delay::Working, 99), Duration::from_secs(5)); + // A rate-limited task waits briefly and the wait does not grow. + assert_eq!(next_delay(Delay::RateLimited, 0), super::RATE_LIMITED_PAUSE); + assert_eq!(next_delay(Delay::RateLimited, 99), super::RATE_LIMITED_PAUSE); + assert!(super::RATE_LIMITED_PAUSE < next_delay(Delay::Busy, 0)); } #[test] @@ -975,9 +1101,12 @@ mod tests { let first = run_once(caller.path(), courier.clone(), None, now()).await.expect("round"); assert_eq!(first.attempted, [(task.task_id.clone(), SentState::Waiting)]); + // A full queue is not sent again within the attempt. + assert_eq!(courier.requests().len(), 1); let store = NodeStore::in_dir(caller.path()).expect("store"); let waiting = store.sent_task(&task.task_id).expect("read").expect("exists"); assert!(waiting.next_attempt_at >= now().saturating_add(4)); + assert_eq!(waiting.reason.as_deref(), Some("the queue of the agent is full")); let early = run_once(caller.path(), courier.clone(), None, now()).await.expect("round"); assert!(early.attempted.is_empty()); @@ -989,6 +1118,145 @@ mod tests { assert!(!later.active); } + #[tokio::test] + async fn a_poll_that_the_rate_limit_shed_is_sent_again_in_the_attempt() { + let (_host, caller) = caller(); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let courier = Scripted::with(vec![ + result(A2aTaskStatus::Working, ""), + rate_limited(), + rate_limited(), + result(A2aTaskStatus::Completed, "done"), + ]); + let state = + attempt(caller.path(), courier.as_ref(), &task, Duration::from_secs(10)) + .await + .expect("attempt"); + assert_eq!(state, SentState::Answered); + let payloads: Vec = courier + .requests() + .iter() + .map(|frame| { + serde_json::from_value(frame.payload.clone()).expect("payload") + }) + .collect(); + assert_eq!(payloads.len(), 4); + assert!( + payloads + .iter() + .all(|payload| payload.idempotency_key == task.idempotency_key) + ); + let nonces: std::collections::BTreeSet<&str> = + payloads.iter().map(|payload| payload.request_nonce.as_str()).collect(); + assert_eq!(nonces.len(), 4, "every send is a new frame"); + } + + #[tokio::test] + async fn an_agent_that_keeps_shedding_makes_the_task_wait_briefly_with_its_own_reason() + { + let (_host, caller) = caller(); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let courier = Scripted::with((0..40).map(|_| rate_limited()).collect()); + let started = std::time::Instant::now(); + let state = + attempt(caller.path(), courier.as_ref(), &task, Duration::from_secs(20)) + .await + .expect("attempt"); + let elapsed = started.elapsed(); + assert_eq!(state, SentState::Waiting); + // The sends stop at the end of the overload window, not the attempt's. + assert!(elapsed >= crate::transport::OVERLOAD_RETRY_WINDOW, "{elapsed:?}"); + assert!( + elapsed + < crate::transport::OVERLOAD_RETRY_WINDOW + Duration::from_millis(600), + "{elapsed:?}" + ); + assert!(courier.requests().len() > 2); + let kept = NodeStore::in_dir(caller.path()) + .expect("store") + .sent_task(&task.task_id) + .expect("read") + .expect("the task exists"); + assert_eq!(kept.reason.as_deref(), Some(super::RATE_LIMITED)); + let pause = kept.next_attempt_at.saturating_sub(now()); + assert!( + (0..=super::seconds(super::RATE_LIMITED_PAUSE)).contains(&pause), + "{pause} s" + ); + } + + #[tokio::test] + async fn the_rate_limit_retry_stops_at_the_attempt_window() { + let (_host, caller) = caller(); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let courier = Scripted::with((0..40).map(|_| rate_limited()).collect()); + let started = std::time::Instant::now(); + let state = attempt(caller.path(), courier.as_ref(), &task, Duration::ZERO) + .await + .expect("attempt"); + assert_eq!(state, SentState::Waiting); + assert_eq!(courier.requests().len(), 1); + assert!(started.elapsed() < Duration::from_secs(1)); + } + + /// Changes `user_version` of the database in `directory` by `change`. + fn bump_schema_version(directory: &std::path::Path, change: i64) { + let connection = + rusqlite::Connection::open(directory.join(aether_store::NODE_DATABASE)) + .expect("database must open"); + let version: i64 = connection + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .expect("version must read"); + connection + .pragma_update(None, "user_version", version.saturating_add(change)) + .expect("version must write"); + } + + #[cfg(unix)] + #[tokio::test] + async fn rounds_that_share_a_store_follow_a_database_file_that_replaced_the_old_one() + { + let (host, caller) = caller(); + let store = super::open_shared(caller.path()); + let courier = Scripted::with(vec![result(A2aTaskStatus::Completed, "done")]); + let idle = super::run_round(&store, courier.clone(), None, now()) + .await + .expect("round"); + assert!(idle.attempted.is_empty()); + // An operator restores a backup over the database while the node runs. + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file( + caller.path().join(format!("{}{suffix}", aether_store::NODE_DATABASE)), + ); + } + let endpoint = crate::direct::endpoint_id(caller.path()).expect("endpoint"); + crate::direct::import_bundle( + caller.path(), + &crate::direct::test_bundle(host.path(), &endpoint, false), + ) + .expect("the contact must import"); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let round = + super::run_round(&store, courier, None, now()).await.expect("round"); + assert_eq!(round.attempted, [(task.task_id, SentState::Answered)]); + } + + #[tokio::test] + async fn rounds_that_share_a_store_fail_closed_for_a_newer_schema() { + let (_host, caller) = caller(); + let store = super::open_shared(caller.path()); + let courier = Scripted::with(Vec::new()); + super::run_round(&store, courier.clone(), None, now()).await.expect("round"); + // Another binary migrated the file while the loop kept its store. + bump_schema_version(caller.path(), 1); + assert_eq!( + super::run_round(&store, courier.clone(), None, now()).await.err(), + Some(OutboxError::Unavailable) + ); + bump_schema_version(caller.path(), -1); + super::run_round(&store, courier, None, now()).await.expect("round"); + } + #[tokio::test] async fn an_offline_contact_waits_until_presence_says_online() { let (host, caller) = caller(); diff --git a/crates/aether/src/policy.rs b/crates/aether/src/policy.rs index d21152c..1631dbc 100644 --- a/crates/aether/src/policy.rs +++ b/crates/aether/src/policy.rs @@ -20,12 +20,28 @@ pub struct QueuePolicyLimits { pub global: usize, #[serde(rename = "queuePerPeer")] pub per_peer: usize, + /// How many tasks the node runs at once. A policy file without it runs + /// one at a time, as every node did before the limit existed. + #[serde(rename = "runningTasks", default = "default_running")] + pub running: usize, +} + +const fn default_running() -> usize { + 1 } impl QueuePolicyLimits { + /// Limits that run one task at a time. #[must_use] pub const fn new(global: usize, per_peer: usize) -> Self { - Self { global, per_peer } + Self { global, per_peer, running: default_running() } + } + + /// These limits with `running` tasks at once. + #[must_use] + pub const fn with_running(mut self, running: usize) -> Self { + self.running = running; + self } #[must_use] @@ -33,6 +49,7 @@ impl QueuePolicyLimits { match id { QueueLimitId::Global => self.global, QueueLimitId::PerPeer => self.per_peer, + QueueLimitId::Running => self.running, } } @@ -40,6 +57,7 @@ impl QueuePolicyLimits { match id { QueueLimitId::Global => self.global = value, QueueLimitId::PerPeer => self.per_peer = value, + QueueLimitId::Running => self.running = value, } } } @@ -368,7 +386,7 @@ pub fn save_policy_settings_in_store( ..policy }; keep(store, &serde_json::to_string(&policy).map_err(|_| PolicyError::Invalid)?)?; - for id in [QueueLimitId::Global, QueueLimitId::PerPeer] { + for id in QueueLimitId::ALL { store .remove_applied_change(aether_store::ChangeKind::Limit, id.as_str()) .map_err(|_| PolicyError::Read)?; @@ -390,8 +408,9 @@ pub fn validate_policy_settings(settings: &PolicySettings) -> Result<(), PolicyE } if settings.max_context_tokens == 0 || settings.max_seconds == 0 - || settings.queue.get(QueueLimitId::Global) == 0 - || settings.queue.get(QueueLimitId::PerPeer) == 0 + || !QueueLimitId::ALL.into_iter().all(|id| { + u32::try_from(settings.queue.get(id)).is_ok_and(|value| id.accepts(value)) + }) { return Err(PolicyError::InvalidField("limits".to_owned())); } @@ -422,17 +441,47 @@ pub(crate) fn stored_queue_limits( }) } +/// How many tasks the node runs at once in force at the next node start: +/// the stored policy with the `admin.limit.running_tasks` override. `None` +/// when no policy is stored. +pub fn running_limit(data_dir: &Path) -> Result, PolicyError> { + let store = NodeStore::in_dir(data_dir).map_err(|_| PolicyError::Read)?; + let Some(policy) = stored(&store)? else { + return Ok(None); + }; + stored_running_limit(&store, policy.queue).map(Some) +} + +/// How many tasks the node runs at once: the policy's value with the +/// `admin.limit.running_tasks` override that `store` holds. A value outside +/// the range that the owner can set is an invalid policy. +pub(crate) fn stored_running_limit( + store: &NodeStore, + queue: QueuePolicyLimits, +) -> Result { + let id = QueueLimitId::Running; + let running = stored_limit(store, id, queue.get(id))?; + if u32::try_from(running).is_ok_and(|value| id.accepts(value)) { + Ok(running) + } else { + Err(PolicyError::InvalidField("runningTasks".to_owned())) + } +} + fn stored_limit( store: &NodeStore, id: QueueLimitId, fallback: usize, ) -> Result { match store.applied_change(aether_store::ChangeKind::Limit, id.as_str()) { - Ok(Some(value)) => { - value.parse::().ok().filter(|value| *value > 0).ok_or_else(|| { + Ok(Some(value)) => value + .parse::() + .ok() + .filter(|value| id.accepts(*value)) + .and_then(|value| usize::try_from(value).ok()) + .ok_or_else(|| { PolicyError::InvalidField(format!("admin.limit.{}", id.as_str())) - }) - } + }), Ok(None) => Ok(fallback), Err(_) => Err(PolicyError::Invalid), } @@ -471,7 +520,13 @@ pub(crate) fn decode_key(value: &str) -> Result<[u8; 32], PolicyError> { mod tests { use std::path::PathBuf; - use super::{AgentAdapter, PolicyFile, PolicySandbox}; + use aether_core::limits::QueueLimitId; + use aether_store::NodeStore; + + use super::{ + AgentAdapter, PolicyError, PolicyFile, PolicySandbox, PolicySettings, + QueuePolicyLimits, stored_running_limit, validate_policy_settings, + }; #[test] fn a_policy_file_with_a_pact_section_still_loads() { @@ -504,6 +559,71 @@ mod tests { assert_eq!(pact.brands[0].scope.id, "review:read_only"); } + #[test] + fn a_policy_file_without_a_running_limit_runs_one_task_at_a_time() { + let policy = |extra: &str| { + format!( + r#"{{ + "scope": {{ "id": "direct", "kind": "direct" }}, + "workspace": "/tmp/w", + "maxContextTokens": 4000, + "maxSeconds": 120, + "queueGlobal": 4, + "queuePerPeer": 2{extra} + }}"# + ) + }; + let old = PolicyFile::parse(policy("").as_bytes()).expect("policy must decode"); + assert_eq!(old.queue.running, 1); + let new = PolicyFile::parse(policy(r#", "runningTasks": 3"#).as_bytes()) + .expect("policy must decode"); + assert_eq!(new.queue.running, 3); + // The setting stays when the policy is saved and read again. + let source = serde_json::to_vec(&new).expect("policy must encode"); + assert_eq!( + PolicyFile::parse(&source).expect("policy must decode").queue.running, + 3 + ); + } + + #[test] + fn the_running_limit_must_be_in_range_and_the_stored_change_wins() { + let directory = tempfile::tempdir().expect("directory must create"); + let mut store = NodeStore::in_dir(directory.path()).expect("store must open"); + let queue = QueuePolicyLimits::new(4, 2); + assert_eq!(stored_running_limit(&store, queue), Ok(1)); + assert_eq!(stored_running_limit(&store, queue.with_running(8)), Ok(8)); + for bad in [0, 33] { + assert_eq!( + stored_running_limit(&store, queue.with_running(bad)), + Err(PolicyError::InvalidField("runningTasks".to_owned())) + ); + } + store + .apply_change( + aether_store::ChangeKind::Limit, + QueueLimitId::Running.as_str(), + "5", + aether_store::AuditActor::Ui, + 1, + ) + .expect("limit must store"); + assert_eq!(stored_running_limit(&store, queue), Ok(5)); + let settings = |running| PolicySettings { + workspace: directory.path().to_path_buf(), + max_context_tokens: 1, + max_seconds: 1, + queue: queue.with_running(running), + }; + assert!(validate_policy_settings(&settings(32)).is_ok()); + for bad in [0, 33] { + assert_eq!( + validate_policy_settings(&settings(bad)), + Err(PolicyError::InvalidField("limits".to_owned())) + ); + } + } + #[test] fn a_switch_to_a_connected_adapter_removes_the_codex_settings() { let mut policy = PolicyFile::direct(PathBuf::from("/w")); diff --git a/crates/aether/src/proof/mod.rs b/crates/aether/src/proof/mod.rs index 3f1df76..1937f42 100644 --- a/crates/aether/src/proof/mod.rs +++ b/crates/aether/src/proof/mod.rs @@ -3,7 +3,7 @@ use std::{ path::{Path, PathBuf}, sync::{ Arc, Mutex, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicUsize, Ordering}, mpsc::{self, SyncSender}, }, thread::{self, JoinHandle}, @@ -12,7 +12,7 @@ use std::{ use aether_core::{ Claim, Denial, EndpointId, PolicyEngine, Request, Scope, ScopeKind, TrustProvider, - limits::QueueLimitId, + limits::{DEFAULT_RUNNING_TASKS, QueueLimitId}, }; use aether_store::{NodeStore, QueueLimits, StoreError, TaskState}; use tokio::sync::broadcast; @@ -90,10 +90,12 @@ pub(crate) fn timestamp_after(duration: Duration) -> i64 { } mod admission; +#[cfg(test)] +mod running_tests; mod scheduler; mod worker; -use scheduler::SchedulerContext; +use scheduler::{RunningTasks, SchedulerContext}; use worker::StoreWorker; pub struct ProofNode { @@ -107,8 +109,10 @@ pub struct ProofNode { shutdown: Arc, scheduler_wake: SyncSender<()>, scheduler_thread: Mutex>>, - active_task: Arc>>, - execution_thread: Arc>>>, + running: Arc, + /// How many tasks the owner lets the node run at once. + running_limit: Arc, + execution_threads: Arc>>>, dispatch_serial: Arc>, executor: Arc>>, workspace: Workspace, @@ -171,9 +175,11 @@ where let canceller = executor.cancellation_handle(); let (event_sender, _) = broadcast::channel(64); let shutdown = Arc::new(AtomicBool::new(false)); - let executing = Arc::new(AtomicBool::new(false)); - let active_task = Arc::new(Mutex::new(None)); - let execution_thread = Arc::new(Mutex::new(None)); + let running = Arc::new(RunningTasks::default()); + let running_limit = Arc::new(AtomicUsize::new( + usize::try_from(DEFAULT_RUNNING_TASKS).unwrap_or(1), + )); + let execution_threads = Arc::new(Mutex::new(Vec::new())); let dispatch_serial = Arc::new(Mutex::new(())); let (scheduler_wake, scheduler_wake_rx) = mpsc::sync_channel(64); let executor = Arc::new(Mutex::new(executor)); @@ -184,9 +190,9 @@ where canceller: canceller.clone(), event_sender: event_sender.clone(), shutdown: Arc::clone(&shutdown), - executing: Arc::clone(&executing), - active_task: Arc::clone(&active_task), - execution_thread: Arc::clone(&execution_thread), + running: Arc::clone(&running), + running_limit: Arc::clone(&running_limit), + execution_threads: Arc::clone(&execution_threads), workspace: workspace.clone(), dispatch_serial: Arc::clone(&dispatch_serial), scheduler_wake: scheduler_wake.clone(), @@ -208,8 +214,9 @@ where shutdown, scheduler_wake, scheduler_thread: Mutex::new(Some(scheduler_thread)), - active_task, - execution_thread, + running, + running_limit, + execution_threads, dispatch_serial, executor, workspace, @@ -222,11 +229,7 @@ where } let started = Instant::now(); let _ = self.scheduler_wake.try_send(()); - if let Ok(active) = self.active_task.lock() - && let Some(task_id) = active.as_deref() - { - let task_id = task_id.to_owned(); - drop(active); + for task_id in self.running.active() { let _ = self.cancel(&task_id); } // Stop the scheduler loop first so it leases no further work, then @@ -239,21 +242,24 @@ where let _ = handle.join(); } // With the scheduler stopped, no new execution can start. Wait for - // the last execution (and, transitively, lease-renewal) thread within - // the deadline so storage never closes while it is still writing the - // task's final state. Past the deadline the thread is left to finish - // on its own rather than block shutdown forever. - let execution = - self.execution_thread.lock().ok().and_then(|mut slot| slot.take()); - if let Some(handle) = execution { - while !handle.is_finished() && started.elapsed() < SHUTDOWN_DEADLINE { - if let Ok(active) = self.active_task.lock() - && let Some(task_id) = active.as_deref() - { - self.canceller.cancel(task_id); - } - thread::sleep(Duration::from_millis(20)); + // every execution (and, transitively, lease-renewal) thread within + // the deadline so storage never closes while one is still writing + // its task's final state. Past the deadline the threads are left to + // finish on their own rather than block shutdown forever. + let executions = self + .execution_threads + .lock() + .map(|mut threads| std::mem::take(&mut *threads)) + .unwrap_or_default(); + while executions.iter().any(|handle| !handle.is_finished()) + && started.elapsed() < SHUTDOWN_DEADLINE + { + for task_id in self.running.active() { + self.canceller.cancel(&task_id); } + thread::sleep(Duration::from_millis(20)); + } + for handle in executions { if handle.is_finished() { let _ = handle.join(); } @@ -291,25 +297,54 @@ where id: QueueLimitId, limit: u32, ) -> Result<(), ProofError> { - let limit = usize::try_from(limit).map_err(|_| ProofError::Internal)?; + let value = usize::try_from(limit).map_err(|_| ProofError::Internal)?; let mut limits = self.limits.lock().map_err(|_| ProofError::Internal)?; match id { - QueueLimitId::Global => limits.global = limit, - QueueLimitId::PerPeer => limits.per_peer = limit, + QueueLimitId::Global => limits.global = value, + QueueLimitId::PerPeer => limits.per_peer = value, + QueueLimitId::Running => { + drop(limits); + return self.set_running_limit(value); + } } drop(limits); Ok(()) } + /// Sets how many tasks the node runs at once. It takes effect at the + /// next dispatch, without a restart. A lower value never stops a task + /// that runs: no task starts until fewer than `limit` run. + /// + /// # Errors + /// + /// `ProofError::Internal` when `limit` is not one that the owner can set. + pub fn set_running_limit(&self, limit: usize) -> Result<(), ProofError> { + if !u32::try_from(limit).is_ok_and(|value| QueueLimitId::Running.accepts(value)) + { + return Err(ProofError::Internal); + } + self.running_limit.store(limit, Ordering::Release); + // A higher limit may let a waiting task start now. + let _ = self.scheduler_wake.try_send(()); + Ok(()) + } + pub fn current_queue_limit(&self, id: QueueLimitId) -> Result { - let limits = self.queue_limits()?; let limit = match id { - QueueLimitId::Global => limits.global, - QueueLimitId::PerPeer => limits.per_peer, + QueueLimitId::Global => self.queue_limits()?.global, + QueueLimitId::PerPeer => self.queue_limits()?.per_peer, + QueueLimitId::Running => self.running_limit.load(Ordering::Acquire), }; u32::try_from(limit).map_err(|_| ProofError::Internal) } + /// How many tasks the node runs at once now: the owner's limit, or the + /// agent's own capacity when that is lower. + #[must_use] + pub fn effective_running_limit(&self) -> usize { + self.running_limit.load(Ordering::Acquire).min(self.canceller.capacity()).max(1) + } + /// Moves the executor and its agent to `path`. The executor /// canonicalizes the path; `workspace` then reads the new value. pub fn apply_workspace(&self, path: &Path) -> Result<(), ProofError> { @@ -603,7 +638,7 @@ mod tests { fn cancel(&self, _task_id: &str) {} } - fn test_grant(peer: &str, endpoint: &EndpointId) -> Grant { + pub(super) fn test_grant(peer: &str, endpoint: &EndpointId) -> Grant { let now = SystemTime::now(); Grant { id: GrantId::new(format!("grant-{peer}")), @@ -723,7 +758,7 @@ mod tests { } /// Admits a task as an Iroh caller and returns its id. - fn admit_task( + pub(super) fn admit_task( node: &ProofNode, request: &Request, claim: &Claim, @@ -782,7 +817,7 @@ mod tests { /// Polls instead of sleeping a fixed time: a loaded CI runner can take /// far longer than any fixed sleep to reach the state under test. - fn wait_until(what: &str, condition: impl Fn() -> bool) { + pub(super) fn wait_until(what: &str, condition: impl Fn() -> bool) { let deadline = Instant::now() + Duration::from_secs(10); while !condition() { assert!(Instant::now() < deadline, "timed out waiting for {what}"); @@ -790,7 +825,10 @@ mod tests { } } - fn test_request(id: &str, peer: &str) -> (Request, Claim, EndpointId, Task) { + pub(super) fn test_request( + id: &str, + peer: &str, + ) -> (Request, Claim, EndpointId, Task) { let endpoint = EndpointId::new(format!("endpoint-{peer}")); let request = Request { id: RequestId::new(format!("request-{id}")), diff --git a/crates/aether/src/proof/running_tests.rs b/crates/aether/src/proof/running_tests.rs new file mode 100644 index 0000000..1f1ca40 --- /dev/null +++ b/crates/aether/src/proof/running_tests.rs @@ -0,0 +1,473 @@ +//! Tests of a node that runs more than one task at a time: the cap, a +//! lowered cap, a cancel, a lost lease and a shutdown with several tasks +//! running. The agent is a fake behind the `Agent` seam; each of its turns +//! waits until the test releases or cancels its task. + +use std::{ + collections::BTreeSet, + sync::{ + Arc, Mutex, MutexGuard, + atomic::{AtomicUsize, Ordering}, + }, + thread, + time::Duration, +}; + +use aether_core::{ + Claim, EndpointId, PolicyEngine, Request, Scope, ScopeId, ScopeKind, + limits::{MAX_RUNNING_TASKS, QueueLimitId}, +}; +use aether_store::{NodeStore, QueueLimits, TaskState}; + +use super::{ + ProofNode, + scheduler::SchedulerContext, + tests::{admit_task, test_grant, test_request, wait_until}, +}; +use crate::{ + execution::{ + Agent, ExecutionError, ExecutionEvent, Executor, Limits, Task, TurnContext, + }, + test_support::Trusted, +}; + +fn locked(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().expect("lock must not be poisoned") +} + +#[derive(Default)] +struct TurnLog { + /// The tasks whose turn is in progress. + inside: Mutex>, + /// Every turn start, in order. + started: Mutex>, + /// The most turns that were in progress at one time. + peak: AtomicUsize, + released: Mutex>, + cancelled: Mutex>, + /// What the agent says it can run at once; 0 for no limit of its own. + capacity: AtomicUsize, +} + +impl TurnLog { + fn inside(&self) -> Vec { + locked(&self.inside).iter().cloned().collect() + } + + fn started(&self) -> Vec { + locked(&self.started).clone() + } + + fn release(&self, task_id: &str) { + locked(&self.released).insert(task_id.to_owned()); + } + + fn was_cancelled(&self, task_id: &str) -> bool { + locked(&self.cancelled).contains(task_id) + } +} + +#[derive(Clone)] +struct Parallel(Arc); + +impl Agent for Parallel { + fn start_turn_with_events( + &mut self, + ctx: &TurnContext, + events: &mut dyn FnMut(ExecutionEvent), + ) -> Result { + let log = &self.0; + { + let mut inside = locked(&log.inside); + inside.insert(ctx.task_id.clone()); + log.peak.fetch_max(inside.len(), Ordering::AcqRel); + } + locked(&log.started).push(ctx.task_id.clone()); + let result = loop { + if locked(&log.cancelled).contains(&ctx.task_id) { + break Err(ExecutionError::Cancelled); + } + if locked(&log.released).contains(&ctx.task_id) { + break Ok(format!("done:{}", ctx.task_id)); + } + thread::sleep(Duration::from_millis(5)); + }; + locked(&log.inside).remove(&ctx.task_id); + if result.is_ok() { + events(ExecutionEvent::Completed); + } + result + } + + fn cancel(&self, task_id: &str) { + locked(&self.0.cancelled).insert(task_id.to_owned()); + } + + fn capacity(&self) -> usize { + match self.0.capacity.load(Ordering::Acquire) { + 0 => usize::MAX, + capacity => capacity, + } + } +} + +type Submission = (Request, Claim, EndpointId, Task); + +struct Rig { + node: Arc>, + log: Arc, + submissions: Vec, + database: std::path::PathBuf, + _directory: tempfile::TempDir, +} + +impl Rig { + /// A node with `running` slots and `tasks` callers that each have one + /// task to send. + fn new(running: usize, tasks: usize) -> Self { + let directory = tempfile::tempdir().expect("directory must create"); + let workspace = directory.path().to_path_buf(); + let database = workspace.join(aether_store::NODE_DATABASE); + let submissions = (0..tasks) + .map(|index| { + test_request(&format!("task-{index}"), &format!("peer-{index}")) + }) + .collect::>(); + let grants = submissions + .iter() + .enumerate() + .map(|(index, (_, _, endpoint, _))| { + test_grant(&format!("peer-{index}"), endpoint) + }) + .collect::>(); + let log = Arc::new(TurnLog::default()); + let node = ProofNode::new( + PolicyEngine::new(Trusted, grants), + NodeStore::open(&database).expect("store must open"), + Executor::new( + Parallel(Arc::clone(&log)), + Limits { workspace, max_context_tokens: 32, max_seconds: 120 }, + ), + QueueLimits { global: 16, per_peer: 4 }, + Scope { id: ScopeId::new("direct"), kind: ScopeKind::Direct }, + ) + .expect("node must create"); + node.set_running_limit(running).expect("running limit must set"); + Self { node: Arc::new(node), log, submissions, database, _directory: directory } + } + + /// Admits the task at `index`; returns its ID. + fn admit(&self, index: usize) -> String { + let (request, claim, endpoint, task) = + self.submissions.get(index).expect("the submission must exist"); + admit_task(&self.node, request, claim, endpoint, &format!("key-{index}"), task) + .expect("task must admit") + } + + fn state(&self, task_id: &str) -> TaskState { + self.node.state(task_id).expect("state must load") + } + + fn wait_for_state(&self, task_id: &str, expected: TaskState) { + wait_until(&format!("{task_id} to be {expected:?}"), || { + self.node.state(task_id).is_ok_and(|state| state == expected) + }); + } + + fn wait_for_turns(&self, count: usize) { + wait_until(&format!("{count} turns in progress"), || { + self.log.inside().len() == count + }); + } + + /// Gives the scheduler's own context, so a test can run what its loop + /// runs. + fn scheduler(&self) -> SchedulerContext { + SchedulerContext { + store: self.node.store.clone(), + executor: Arc::clone(&self.node.executor), + canceller: self.node.canceller.clone(), + event_sender: self.node.event_sender.clone(), + shutdown: Arc::clone(&self.node.shutdown), + running: Arc::clone(&self.node.running), + running_limit: Arc::clone(&self.node.running_limit), + execution_threads: Arc::clone(&self.node.execution_threads), + workspace: self.node.workspace.clone(), + dispatch_serial: Arc::clone(&self.node.dispatch_serial), + scheduler_wake: self.node.scheduler_wake.clone(), + policy: Arc::clone(&self.node.policy), + scopes: self.node.scopes.clone(), + } + } + + /// Lets every turn that is still in progress finish, then stops the + /// node. + fn finish(self) { + for task_id in self.log.inside() { + self.log.release(&task_id); + } + self.node.shutdown(); + } +} + +#[test] +fn a_new_node_runs_one_task_at_a_time() { + let directory = tempfile::tempdir().expect("directory must create"); + let workspace = directory.path().to_path_buf(); + let log = Arc::new(TurnLog::default()); + let node = ProofNode::new( + PolicyEngine::new(Trusted, Vec::new()), + NodeStore::in_dir(&workspace).expect("store must open"), + Executor::new( + Parallel(log), + Limits { workspace, max_context_tokens: 32, max_seconds: 120 }, + ), + QueueLimits { global: 1, per_peer: 1 }, + Scope { id: ScopeId::new("direct"), kind: ScopeKind::Direct }, + ) + .expect("node must create"); + assert_eq!( + node.current_queue_limit(QueueLimitId::Running).expect("limit reads"), + 1 + ); + assert_eq!(node.effective_running_limit(), 1); + node.shutdown(); +} + +#[test] +fn the_running_limit_has_a_floor_and_a_ceiling() { + let rig = Rig::new(1, 0); + assert!(rig.node.set_running_limit(0).is_err()); + let too_many = + usize::try_from(MAX_RUNNING_TASKS).expect("the cap fits").saturating_add(1); + assert!(rig.node.set_running_limit(too_many).is_err()); + assert!(rig.node.set_queue_limit(QueueLimitId::Running, 0).is_err()); + assert_eq!(rig.node.effective_running_limit(), 1); + rig.node + .set_queue_limit(QueueLimitId::Running, MAX_RUNNING_TASKS) + .expect("max sets"); + assert_eq!( + rig.node.current_queue_limit(QueueLimitId::Running).expect("limit reads"), + MAX_RUNNING_TASKS + ); + rig.finish(); +} + +#[test] +fn a_limit_of_two_runs_two_tasks_at_once_and_never_more() { + let rig = Rig::new(2, 4); + let ids = (0..4).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(2); + // The first two run; the others wait for a slot. + let mut first = rig.log.started(); + first.sort(); + assert_eq!(first, ["task-0", "task-1"]); + thread::sleep(Duration::from_millis(100)); + assert_eq!(rig.log.inside().len(), 2); + assert_eq!(rig.state(&ids[2]), TaskState::Queued); + assert_eq!(rig.state(&ids[3]), TaskState::Queued); + // A task that ends hands its slot to the next one, in queue order. + rig.log.release(&ids[0]); + rig.wait_for_state(&ids[0], TaskState::Succeeded); + wait_until("task 2 to start", || rig.log.started().contains(&ids[2])); + assert_eq!(rig.state(&ids[3]), TaskState::Queued); + rig.log.release(&ids[1]); + wait_until("task 3 to start", || rig.log.started().contains(&ids[3])); + for id in &ids { + rig.log.release(id); + } + for id in &ids { + rig.wait_for_state(id, TaskState::Succeeded); + } + assert_eq!(rig.log.peak.load(Ordering::Acquire), 2); + // Each task's start is confirmed once: one turn for each. + let mut started = rig.log.started(); + started.sort(); + assert_eq!(started, ["task-0", "task-1", "task-2", "task-3"]); + wait_until("every slot to be free", || rig.node.running.reserved() == 0); + rig.finish(); +} + +#[test] +fn raising_the_limit_starts_waiting_tasks_without_a_restart() { + let rig = Rig::new(1, 3); + let ids = (0..3).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(1); + thread::sleep(Duration::from_millis(100)); + assert_eq!(rig.log.inside().len(), 1); + rig.node.set_queue_limit(QueueLimitId::Running, 3).expect("limit must raise"); + rig.wait_for_turns(3); + for id in &ids { + assert_eq!(rig.state(id), TaskState::Running); + } + rig.finish(); +} + +#[test] +fn lowering_the_limit_never_stops_a_running_task() { + let rig = Rig::new(3, 4); + let ids = (0..4).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(3); + assert_eq!(rig.state(&ids[3]), TaskState::Queued); + rig.node.set_queue_limit(QueueLimitId::Running, 1).expect("limit must lower"); + thread::sleep(Duration::from_millis(100)); + // All three run on, and nothing was cancelled. + assert_eq!(rig.log.inside().len(), 3); + for id in &ids[..3] { + assert_eq!(rig.state(id), TaskState::Running); + assert!(!rig.log.was_cancelled(id)); + } + // Two running tasks end: one still runs, which is the new limit, so the + // waiting task does not start yet. + rig.log.release(&ids[0]); + rig.log.release(&ids[1]); + rig.wait_for_state(&ids[0], TaskState::Succeeded); + rig.wait_for_state(&ids[1], TaskState::Succeeded); + thread::sleep(Duration::from_millis(150)); + assert_eq!(rig.state(&ids[3]), TaskState::Queued); + // The last running task ends: the waiting one starts. + rig.log.release(&ids[2]); + wait_until("the waiting task to start", || rig.log.started().contains(&ids[3])); + assert_eq!(rig.log.peak.load(Ordering::Acquire), 3); + rig.finish(); +} + +#[test] +fn an_agent_that_runs_fewer_tasks_lowers_the_limit() { + let rig = Rig::new(3, 3); + rig.log.capacity.store(1, Ordering::Release); + assert_eq!(rig.node.effective_running_limit(), 1); + let ids = (0..3).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(1); + thread::sleep(Duration::from_millis(100)); + assert_eq!(rig.log.inside().len(), 1); + // The agent now takes more: the waiting tasks start. + rig.log.capacity.store(0, Ordering::Release); + rig.node.set_running_limit(3).expect("limit must set"); + rig.wait_for_turns(3); + assert_eq!(rig.node.effective_running_limit(), 3); + for id in &ids { + assert_eq!(rig.state(id), TaskState::Running); + } + rig.finish(); +} + +#[test] +fn a_cancel_stops_only_its_task() { + let rig = Rig::new(2, 3); + let ids = (0..3).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(2); + rig.node.cancel(&ids[0]).expect("task must cancel"); + rig.wait_for_state(&ids[0], TaskState::Cancelled); + assert!(rig.log.was_cancelled(&ids[0])); + assert!(!rig.log.was_cancelled(&ids[1])); + // The other task runs on, and the freed slot starts the waiting one. + wait_until("task 2 to start", || rig.log.started().contains(&ids[2])); + assert_eq!(rig.state(&ids[1]), TaskState::Running); + rig.log.release(&ids[1]); + rig.wait_for_state(&ids[1], TaskState::Succeeded); + rig.log.release(&ids[2]); + rig.wait_for_state(&ids[2], TaskState::Succeeded); + assert_eq!(rig.state(&ids[0]), TaskState::Cancelled); + rig.finish(); +} + +#[test] +fn a_lost_lease_stops_only_its_task() { + let rig = Rig::new(2, 2); + let ids = (0..2).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(2); + // The lease of the first task runs out; the second keeps its own. + let connection = rusqlite::Connection::open(&rig.database).expect("database opens"); + connection.busy_timeout(Duration::from_secs(5)).expect("timeout sets"); + let changed = connection + .execute("UPDATE execution_leases SET expires_at=1 WHERE task_id=?1", [&ids[0]]) + .expect("lease must expire"); + assert_eq!(changed, 1); + drop(connection); + rig.scheduler().maintain(); + rig.wait_for_state(&ids[0], TaskState::UnknownResult); + wait_until("the turn of the lost task to stop", || { + rig.log.was_cancelled(&ids[0]) && rig.log.inside() == [ids[1].clone()] + }); + assert!(!rig.log.was_cancelled(&ids[1])); + assert_eq!(rig.state(&ids[1]), TaskState::Running); + rig.log.release(&ids[1]); + rig.wait_for_state(&ids[1], TaskState::Succeeded); + // The lost task stays as recovery left it. + assert_eq!(rig.state(&ids[0]), TaskState::UnknownResult); + rig.finish(); +} + +#[test] +fn shutdown_cancels_and_joins_every_running_task() { + let rig = Rig::new(3, 4); + let ids = (0..4).map(|index| rig.admit(index)).collect::>(); + rig.wait_for_turns(3); + let (node, log) = (Arc::clone(&rig.node), Arc::clone(&rig.log)); + node.shutdown(); + for id in &ids[..3] { + assert!(log.was_cancelled(id), "{id} must get the cancel"); + } + assert!(log.inside().is_empty(), "every turn must have ended"); + assert_eq!(node.running.reserved(), 0); + assert!(locked(&node.execution_threads).is_empty()); + let store = NodeStore::open(&rig.database).expect("store must reopen"); + for id in &ids[..3] { + assert_eq!(store.state(id).expect("task is durable"), TaskState::Cancelled); + } + // The task that did not run waits for the next start of the node. + assert_eq!(store.state(&ids[3]).expect("task is durable"), TaskState::Queued); +} + +#[test] +fn a_task_requeued_while_its_run_lives_gets_no_second_run() { + let rig = Rig::new(2, 1); + // The run waits before its turn: it holds a slot and the lease, and has + // not started the agent yet. + let executor = locked(&rig.node.executor); + let id = rig.admit(0); + rig.wait_for_state(&id, TaskState::Leased); + // The lease runs out and recovery puts the task back in the queue while + // its first run still lives. + rig.node + .store + .call(|store| store.recover_expired_leases(i64::MAX)) + .expect("recovery must run"); + assert_eq!(rig.state(&id), TaskState::Queued); + for _ in 0..5 { + let _ = rig.node.scheduler_wake.try_send(()); + thread::sleep(Duration::from_millis(30)); + } + // The scheduler leases it again only after that run ends: a second run + // now would be cancelled by the first run's lost lease. + assert_eq!(rig.state(&id), TaskState::Queued); + assert_eq!(rig.node.running.reserved(), 1); + drop(executor); + rig.wait_for_state(&id, TaskState::Running); + rig.log.release(&id); + rig.wait_for_state(&id, TaskState::Succeeded); + assert_eq!(rig.log.started(), std::slice::from_ref(&id), "the agent saw one turn"); + rig.finish(); +} + +#[test] +fn the_default_limit_runs_tasks_one_at_a_time_as_before() { + let rig = Rig::new(1, 3); + let ids = (0..3).map(|index| rig.admit(index)).collect::>(); + for (position, id) in ids.iter().enumerate() { + wait_until("the next task to start", || rig.log.started().contains(id)); + assert_eq!( + rig.log.inside(), + std::slice::from_ref(id), + "task {position} runs alone" + ); + thread::sleep(Duration::from_millis(50)); + assert_eq!(rig.log.inside().len(), 1); + rig.log.release(id); + rig.wait_for_state(id, TaskState::Succeeded); + } + assert_eq!(rig.log.peak.load(Ordering::Acquire), 1); + assert_eq!(rig.log.started(), ["task-0", "task-1", "task-2"]); + rig.finish(); +} diff --git a/crates/aether/src/proof/scheduler.rs b/crates/aether/src/proof/scheduler.rs index 4e94311..d0f087c 100644 --- a/crates/aether/src/proof/scheduler.rs +++ b/crates/aether/src/proof/scheduler.rs @@ -1,8 +1,8 @@ use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, sync::{ Arc, Mutex, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicUsize, Ordering}, mpsc::{self, RecvTimeoutError, SyncSender}, }, thread::{self, JoinHandle}, @@ -89,36 +89,136 @@ fn settlement(run: RunReport, cancelled: impl FnOnce() -> bool) -> Option, +} + +#[derive(Default)] +struct Running { + /// Slots that are taken: runs that are leased, being prepared or running. + reserved: usize, + /// Each run that leased a task and has not ended, by execution ID. + runs: BTreeMap, +} + +struct Run { + task_id: String, + /// The run is registered and can be cancelled. + active: bool, +} + +impl RunningTasks { + /// Takes a slot unless `limit` slots are taken. A lowered limit never + /// stops a run: it only refuses new slots until fewer are taken. + pub(in crate::proof) fn reserve(&self, limit: usize) -> bool { + let Ok(mut running) = self.inner.lock() else { return false }; + if running.reserved >= limit { + return false; + } + running.reserved = running.reserved.saturating_add(1); + true + } + + /// Gives back a slot that did not become a run. + pub(in crate::proof) fn release(&self) { + if let Ok(mut running) = self.inner.lock() { + running.reserved = running.reserved.saturating_sub(1); + } + } + + /// Records that the slot now holds the run `execution_id` of `task_id`. + pub(in crate::proof) fn begin(&self, execution_id: &str, task_id: &str) { + if let Ok(mut running) = self.inner.lock() { + running.runs.insert( + execution_id.to_owned(), + Run { task_id: task_id.to_owned(), active: false }, + ); + } + } + + fn set_active(&self, execution_id: &str, active: bool) { + if let Ok(mut running) = self.inner.lock() + && let Some(run) = running.runs.get_mut(execution_id) + { + run.active = active; + } + } + + /// The run `execution_id` ended: its slot is free. + fn end(&self, execution_id: &str) { + if let Ok(mut running) = self.inner.lock() { + running.runs.remove(execution_id); + running.reserved = running.reserved.saturating_sub(1); + } + } + + /// The tasks whose run can be cancelled now. + pub(in crate::proof) fn active(&self) -> Vec { + let tasks = self.inner.lock().map_or_else( + |_| BTreeSet::new(), + |running| { + running + .runs + .values() + .filter(|run| run.active) + .map(|run| run.task_id.clone()) + .collect::>() + }, + ); + tasks.into_iter().collect() + } + + /// The tasks that a run holds from its lease to its end. The scheduler + /// leases none of them again: a task that recovery gave back to the + /// queue while its first run still lives would get a second run, and the + /// first run's lost lease would cancel the second. + pub(in crate::proof) fn tasks_in_flight(&self) -> Vec { + let tasks = self.inner.lock().map_or_else( + |_| BTreeSet::new(), + |running| { + running + .runs + .values() + .map(|run| run.task_id.clone()) + .collect::>() + }, + ); + tasks.into_iter().collect() + } + + /// How many slots are taken. + #[cfg(test)] + pub(in crate::proof) fn reserved(&self) -> usize { + self.inner.lock().map_or(0, |running| running.reserved) + } +} + +/// Holds one execution slot for one run. Dropping it ends the run: it leaves +/// the run set, the slot is free and the scheduler wakes, on every exit of +/// the run. struct ExecutionSlot { - executing: Arc, - active_task: Arc>>, + running: Arc, scheduler_wake: SyncSender<()>, - task_id: String, + execution_id: String, } impl ExecutionSlot { fn activate(&self) { - if let Ok(mut active) = self.active_task.lock() { - *active = Some(self.task_id.clone()); - } + self.running.set_active(&self.execution_id, true); } fn deactivate(&self) { - if let Ok(mut active) = self.active_task.lock() - && active.as_deref() == Some(self.task_id.as_str()) - { - *active = None; - } + self.running.set_active(&self.execution_id, false); } } impl Drop for ExecutionSlot { fn drop(&mut self) { - self.deactivate(); - self.executing.store(false, Ordering::Release); + self.running.end(&self.execution_id); let _ = self.scheduler_wake.try_send(()); } } @@ -129,9 +229,10 @@ pub(in crate::proof) struct SchedulerContext { pub(in crate::proof) canceller: P, pub(in crate::proof) event_sender: broadcast::Sender, pub(in crate::proof) shutdown: Arc, - pub(in crate::proof) executing: Arc, - pub(in crate::proof) active_task: Arc>>, - pub(in crate::proof) execution_thread: Arc>>>, + pub(in crate::proof) running: Arc, + /// The owner's limit on running tasks; the agent can lower it. + pub(in crate::proof) running_limit: Arc, + pub(in crate::proof) execution_threads: Arc>>>, pub(in crate::proof) workspace: Workspace, pub(in crate::proof) dispatch_serial: Arc>, pub(in crate::proof) scheduler_wake: SyncSender<()>, @@ -147,9 +248,9 @@ impl Clone for SchedulerContext { canceller: self.canceller.clone(), event_sender: self.event_sender.clone(), shutdown: Arc::clone(&self.shutdown), - executing: Arc::clone(&self.executing), - active_task: Arc::clone(&self.active_task), - execution_thread: Arc::clone(&self.execution_thread), + running: Arc::clone(&self.running), + running_limit: Arc::clone(&self.running_limit), + execution_threads: Arc::clone(&self.execution_threads), workspace: self.workspace.clone(), dispatch_serial: Arc::clone(&self.dispatch_serial), scheduler_wake: self.scheduler_wake.clone(), @@ -193,9 +294,9 @@ where } fn notify_task(&self, task_id: &str) { - if self.event_sender.send(task_id.to_owned()).is_err() { - eprintln!("aether: scheduler event broadcast failed for {task_id}"); - } + // `send` fails only when no receiver is subscribed. That is normal: + // a poll that nobody waits on needs no wake-up. + let _ = self.event_sender.send(task_id.to_owned()); } /// Ends a leased task that will not run with `end` @@ -241,20 +342,34 @@ where let _dispatch_guard = self.dispatch_serial.lock().map_err(|_| ProofError::Internal)?; let execution_id = Uuid::new_v4().to_string(); + // Only this thread starts runs, so no run is added to this list + // before the lease below; a run that ends meanwhile only makes the + // list longer than it needs to be. + let in_flight = self.running.tasks_in_flight(); let leased = self.store.call({ let execution_id = execution_id.clone(); move |store| { - store.lease_next("scheduler", &execution_id, timestamp_after(LEASE_TTL)) + store.lease_next_except( + "scheduler", + &execution_id, + timestamp_after(LEASE_TTL), + &in_flight, + ) } })?; let Some(task_id) = leased else { return Ok(None); }; let prepared = self.prepare_leased(task_id, execution_id); - if !matches!(prepared, Ok(Some(_))) { + match &prepared { + Ok(Some(bundle)) => { + self.running.begin(&bundle.execution_id, &bundle.task_id); + } // The leased task does not run, so the next queued task does // not wait for the fallback poll. - let _ = self.scheduler_wake.try_send(()); + _ => { + let _ = self.scheduler_wake.try_send(()); + } } prepared } @@ -313,10 +428,9 @@ where fn run_execution(&self, bundle: ExecutionBundle) { let ExecutionBundle { task_id, execution_id, task } = bundle; let slot = ExecutionSlot { - executing: Arc::clone(&self.executing), - active_task: Arc::clone(&self.active_task), + running: Arc::clone(&self.running), scheduler_wake: self.scheduler_wake.clone(), - task_id: task_id.clone(), + execution_id: execution_id.clone(), }; if self.shutdown.load(Ordering::Acquire) { // Shutdown landed before this worker could register as the @@ -405,93 +519,94 @@ where let confirmed_flag = Arc::clone(&start_confirmed); let mut event_error = false; let mut settled_at_start = false; - let result = executor.lock().map_err(|_| ExecutionError::Unavailable).and_then( - |mut executor| { - executor.execute_with_confirmed_start( - &task, - &mut || { - let _dispatch_guard = dispatch_serial - .lock() - .map_err(|_| ExecutionError::Unavailable)?; - if shutdown.load(Ordering::Acquire) { - // The process never started, so the task goes - // back to the queue, as it does when shutdown - // lands before this worker registered. + // The executor is locked only to prepare the turn, so that turns of + // other tasks run at the same time. The start is still confirmed + // once for this task, under `dispatch_serial`. + let prepared = executor + .lock() + .map_err(|_| ExecutionError::Unavailable) + .and_then(|executor| executor.prepare_turn(&task)); + let result = prepared.and_then(|turn| { + turn.run( + &mut || { + let _dispatch_guard = dispatch_serial + .lock() + .map_err(|_| ExecutionError::Unavailable)?; + if shutdown.load(Ordering::Acquire) { + // The process never started, so the task goes + // back to the queue, as it does when shutdown + // lands before this worker registered. + let task_id = dispatch_task_id.clone(); + settled_at_start = start_store + .call(move |store| store.requeue_leased(&task_id)) + .is_ok(); + return Err(ExecutionError::Cancelled); + } + let execution_data = start_store + .call({ let task_id = dispatch_task_id.clone(); - settled_at_start = start_store - .call(move |store| store.requeue_leased(&task_id)) - .is_ok(); - return Err(ExecutionError::Cancelled); - } - let execution_data = start_store - .call({ - let task_id = dispatch_task_id.clone(); - move |store| store.task_execution_data(&task_id) - }) - .map_err(|_| ExecutionError::Unavailable)?; - if dispatch_ctx.dispatch_allowed(&execution_data).is_err() { - let rejected = dispatch_ctx.end_leased( - &dispatch_task_id, - &start_execution_id, - NodeStore::mark_rejected, - ); - settled_at_start = rejected.is_ok(); - Self::log_store("reject at start", rejected); - return Err(ExecutionError::Unavailable); - } - start_store - .call({ - let task_id = dispatch_task_id.clone(); - let execution_id = start_execution_id.clone(); - move |store| store.mark_running(&task_id, &execution_id) - }) - .map_err(|_| ExecutionError::Unavailable)?; - let outcome = match start_store.call({ + move |store| store.task_execution_data(&task_id) + }) + .map_err(|_| ExecutionError::Unavailable)?; + if dispatch_ctx.dispatch_allowed(&execution_data).is_err() { + let rejected = dispatch_ctx.end_leased( + &dispatch_task_id, + &start_execution_id, + NodeStore::mark_rejected, + ); + settled_at_start = rejected.is_ok(); + Self::log_store("reject at start", rejected); + return Err(ExecutionError::Unavailable); + } + start_store + .call({ let task_id = dispatch_task_id.clone(); - move |store| store.state(&task_id) - }) { - Ok(TaskState::Cancelled) => Err(ExecutionError::Cancelled), - Ok(TaskState::Leased | TaskState::Running) => Ok(()), - Ok(_) | Err(_) => Err(ExecutionError::Unavailable), - }; - if outcome.is_ok() { - confirmed_flag.store(true, Ordering::Release); - } - outcome - }, - &mut |event| { - if event_error { - return; - } - if event == ExecutionEvent::Completed { - let event_task_id = dispatch_task_id.clone(); - if matches!( - store.call(move |store| store.state(&event_task_id)), - Ok(TaskState::Cancelled) - ) { - return; - } - } + let execution_id = start_execution_id.clone(); + move |store| store.mark_running(&task_id, &execution_id) + }) + .map_err(|_| ExecutionError::Unavailable)?; + let outcome = match start_store.call({ + let task_id = dispatch_task_id.clone(); + move |store| store.state(&task_id) + }) { + Ok(TaskState::Cancelled) => Err(ExecutionError::Cancelled), + Ok(TaskState::Leased | TaskState::Running) => Ok(()), + Ok(_) | Err(_) => Err(ExecutionError::Unavailable), + }; + if outcome.is_ok() { + confirmed_flag.store(true, Ordering::Release); + } + outcome + }, + &mut |event| { + if event_error { + return; + } + if event == ExecutionEvent::Completed { let event_task_id = dispatch_task_id.clone(); - let event_type = event.event_type(); - if store - .call(move |store| { - store.append_event(&event_task_id, event_type) - }) - .is_err() - { - event_error = true; + if matches!( + store.call(move |store| store.state(&event_task_id)), + Ok(TaskState::Cancelled) + ) { return; } - if event_sender.send(dispatch_task_id.clone()).is_err() { - eprintln!( - "aether: scheduler event broadcast failed for {dispatch_task_id}" - ); - } - }, - ) - }, - ); + } + let event_task_id = dispatch_task_id.clone(); + let event_type = event.event_type(); + if store + .call(move |store| { + store.append_event(&event_task_id, event_type) + }) + .is_err() + { + event_error = true; + return; + } + // No receiver is normal; see `notify_task`. + let _ = event_sender.send(dispatch_task_id.clone()); + }, + ) + }); let _ = renewal.0.send(()); let _ = renewal.1.join(); slot.deactivate(); @@ -526,51 +641,75 @@ where self.notify_task(&task_id); } - fn dispatch_one(&self) { + /// How many tasks may run at once now: the owner's limit, or the + /// agent's own capacity when that is lower. It is read at each dispatch, + /// so a change takes effect at the next one; a task that runs is never + /// stopped by it. + fn effective_running_limit(&self) -> usize { + self.running_limit.load(Ordering::Acquire).min(self.canceller.capacity()).max(1) + } + + /// Joins the threads of runs that ended, so that their handles do not + /// pile up while the node runs. + fn reap_finished(&self) { + let Ok(mut threads) = self.execution_threads.lock() else { return }; + let (finished, live): (Vec<_>, Vec<_>) = std::mem::take(&mut *threads) + .into_iter() + .partition(JoinHandle::is_finished); + *threads = live; + drop(threads); + for handle in finished { + let _ = handle.join(); + } + } + + /// Leases the next queued task and starts its run, if a slot is free. + /// Returns whether the scheduler should try for another task now. + fn dispatch_one(&self) -> bool { if self.shutdown.load(Ordering::Acquire) { - return; + return false; } - if self.executing.swap(true, Ordering::AcqRel) { - return; + if !self.running.reserve(self.effective_running_limit()) { + return false; } let bundle = match self.prepare_execution() { Ok(Some(bundle)) => bundle, Ok(None) => { - self.executing.store(false, Ordering::Release); - return; + self.running.release(); + return false; } Err(error) => { eprintln!("aether: scheduler prepare execution: {error:?}"); - self.executing.store(false, Ordering::Release); + self.running.release(); let _ = self.scheduler_wake.try_send(()); - return; + // A task that the policy refused ended as rejected; the + // next queued task may run. + return matches!( + error, + ProofError::Denied(_) | ProofError::GroupDenied + ); } }; - // Join the previous execution thread's handle before replacing it. - // The `executing` gate above guarantees it has already returned; this - // just reclaims the `JoinHandle` so shutdown never has to guess - // whether a stale handle is still live. - if let Ok(mut previous) = self.execution_thread.lock() - && let Some(handle) = previous.take() - { - let _ = handle.join(); - } + self.reap_finished(); let ctx = self.clone(); let task_id = bundle.task_id.clone(); + let execution_id = bundle.execution_id.clone(); if let Ok(handle) = thread::Builder::new() .name("aether-execution".to_owned()) .spawn(move || ctx.run_execution(bundle)) { - if let Ok(mut slot) = self.execution_thread.lock() { - *slot = Some(handle); + if let Ok(mut threads) = self.execution_threads.lock() { + threads.push(handle); } + true } else { // The task never started: give the execution slot back and // return the lease to the queue so the scheduler retries it // instead of leaving it stranded in `Leased` forever. - self.executing.store(false, Ordering::Release); + self.running.end(&execution_id); let _ = self.store.call(move |store| store.requeue_leased(&task_id)); let _ = self.scheduler_wake.try_send(()); + false } } @@ -585,11 +724,13 @@ where self.maintain(); last_maintenance = Instant::now(); } - self.dispatch_one(); + // Fill every free slot: one wake-up may free, or add, room for + // more than one task. + while self.dispatch_one() {} } } - fn maintain(&self) { + pub(in crate::proof) fn maintain(&self) { let now = timestamp_after(Duration::ZERO); match self.store.call(move |store| store.recover_expired_leases(now)) { Ok(recovered) => self.stop_recovered(&recovered), @@ -605,14 +746,14 @@ where } fn stop_recovered(&self, recovered: &[String]) { - let active = self.active_task.lock().ok().and_then(|active| active.clone()); - if let Some(active_id) = active - && recovered.contains(&active_id) - { - // The active worker's lease was just reclaimed as - // `UnknownResult`; stop it promptly instead of letting it - // keep running unsupervised past its recovered deadline. - self.canceller.cancel(&active_id); + for active_id in self.running.active() { + if recovered.contains(&active_id) { + // The worker's lease was just reclaimed as `UnknownResult`; + // stop it promptly instead of letting it keep running + // unsupervised past its recovered deadline. The other + // running tasks keep their leases and run on. + self.canceller.cancel(&active_id); + } } for task_id in recovered { self.notify_task(task_id); diff --git a/crates/aether/src/settings.rs b/crates/aether/src/settings.rs index 8f99746..3b75976 100644 --- a/crates/aether/src/settings.rs +++ b/crates/aether/src/settings.rs @@ -1,7 +1,10 @@ //! Node settings in the configuration table. Each feature defines its own //! settings next to its code; this module only reads and writes them. -use std::path::Path; +use std::{ + path::{Path, PathBuf}, + sync::{Mutex, PoisonError}, +}; use aether_store::{NodeStore, StoreError}; @@ -42,13 +45,152 @@ pub trait Setting { /// A [`StoreError`] when the store fails, or as [`Setting::absent`] and /// [`Setting::decode`] return. pub fn setting(data_dir: &Path) -> Result { - match NodeStore::in_dir(data_dir)?.configuration(S::KEY) { + match stored_text(data_dir, S::KEY) { Ok(stored) => S::decode(stored), Err(StoreError::NotFound) => S::absent(), Err(error) => Err(error), } } +/// How many data directories keep an open reader. +const READERS: usize = 8; + +/// The readers of the settings, oldest first. A setting read is one short +/// query, so one lock covers the lookup and the read. +static READERS_OPEN: Mutex> = Mutex::new(Vec::new()); + +/// Which file a path names. +#[derive(Clone, Copy, Eq, PartialEq)] +struct FileId { + device: u64, + inode: u64, +} + +#[cfg(unix)] +fn file_id(path: &Path) -> Option { + use std::os::unix::fs::MetadataExt; + let metadata = std::fs::metadata(path).ok()?; + Some(FileId { device: metadata.dev(), inode: metadata.ino() }) +} + +/// Without a file identity a reader cannot tell a replaced database, so +/// every use opens the store. +#[cfg(not(unix))] +fn file_id(_path: &Path) -> Option { + None +} + +/// The node store of a directory, which stays open between uses, so that a +/// caller that reads often does not open the database and check its schema +/// each time. +/// +/// Each use starts a new read transaction, so it sees what another +/// connection or process committed. Before a use it checks two things that +/// a connection that stays open would not notice: that the path still names +/// the file that was opened (an operator restored a backup or made the data +/// directory again), and that `user_version` is the one of this binary +/// (another binary migrated the file). If either differs, the store opens +/// again through [`NodeStore::open`], which migrates an older schema and +/// refuses a newer one, so a kept store fails closed as a new open does. +pub(crate) struct KeptStore { + data_dir: PathBuf, + create_dir: bool, + /// The open store, with the file that it opened. Without a file identity + /// the store is never reused. + open: Option<(Option, NodeStore)>, +} + +impl KeptStore { + /// A store of `data_dir` that opens on first use. With `create_dir` the + /// first use creates a missing directory. + pub(crate) const fn new(data_dir: PathBuf, create_dir: bool) -> Self { + Self { data_dir, create_dir, open: None } + } + + /// Drops the open store, so that the next use opens the file again. + pub(crate) fn close(&mut self) { + self.open = None; + } + + fn database(&self) -> PathBuf { + self.data_dir.join(aether_store::NODE_DATABASE) + } + + /// Whether the open store is of the file that the path names now and has + /// the schema of this binary. + fn is_current(&self) -> bool { + let Some((Some(open_file), store)) = &self.open else { + return false; + }; + file_id(&self.database()) == Some(*open_file) && store.schema_is_current() + } + + /// The store for one use: the open one while it is current, else a new + /// one. It runs nothing on the store, so a caller can run work that must + /// not run twice. + /// + /// # Errors + /// + /// A [`StoreError`] when the store cannot open, for example + /// [`StoreError::Migration`] for a file that a newer binary migrated. + pub(crate) fn current(&mut self) -> Result<&mut NodeStore, StoreError> { + if !self.is_current() { + self.open = None; + if self.create_dir { + std::fs::create_dir_all(&self.data_dir)?; + } + let store = NodeStore::in_dir(&self.data_dir)?; + // The file that the store opened is the one that the path names + // now, unless it changed in between; then the next use sees the + // change. + self.open = Some((file_id(&self.database()), store)); + } + self.open.as_mut().map(|(_, store)| store).ok_or(StoreError::InvalidState) + } + + /// The result of `read` on the current store. + /// + /// # Errors + /// + /// A [`StoreError`] when the store cannot open, or as `read` returns. A + /// SQL error on a store that was open before is tried once on a new + /// store. + pub(crate) fn read( + &mut self, + read: impl Fn(&NodeStore) -> Result, + ) -> Result { + let was_open = self.is_current(); + match read(self.current()?) { + Err(StoreError::Sql(_)) if was_open => { + self.open = None; + read(self.current()?) + } + answer => answer, + } + } +} + +/// The stored text of `key`, read on an open store of `data_dir`. +fn stored_text(data_dir: &Path, key: &str) -> Result { + let mut readers = READERS_OPEN.lock().unwrap_or_else(PoisonError::into_inner); + let index = readers + .iter() + .position(|reader| reader.data_dir == data_dir) + .unwrap_or_else(|| { + if readers.len() >= READERS { + readers.remove(0); + } + readers.push(KeptStore::new(data_dir.to_path_buf(), false)); + readers.len().saturating_sub(1) + }); + let answer = readers + .get_mut(index) + .ok_or(StoreError::InvalidState)? + .read(|store| store.configuration(key)); + drop(readers); + answer +} + /// Keeps `value` for the setting `S`. /// /// # Errors @@ -64,3 +206,137 @@ pub fn store_setting( None => store.delete_configuration(S::KEY), } } + +#[cfg(test)] +mod tests { + use aether_store::{NODE_DATABASE, NodeStore, StoreError}; + + use super::{KeptStore, Setting, setting, store_setting}; + + struct Colour; + + impl Setting for Colour { + const KEY: &'static str = "test.colour"; + type Value = Option; + + fn absent() -> Result { + Ok(None) + } + + fn decode(stored: String) -> Result { + Ok(Some(stored)) + } + + fn encode(value: &Self::Value) -> Result, StoreError> { + Ok(value.clone()) + } + } + + fn colour(directory: &std::path::Path) -> Option { + setting::(directory).expect("setting must read") + } + + #[test] + fn a_reader_that_stays_open_sees_each_later_write_and_delete() { + let directory = tempfile::tempdir().expect("directory"); + assert_eq!(colour(directory.path()), None); + store_setting::(directory.path(), &Some("red".to_owned())) + .expect("store"); + assert_eq!(colour(directory.path()).as_deref(), Some("red")); + // Another connection writes, as another process or the admin UI does. + NodeStore::in_dir(directory.path()) + .expect("store") + .put_configuration(Colour::KEY, "blue") + .expect("write"); + assert_eq!(colour(directory.path()).as_deref(), Some("blue")); + store_setting::(directory.path(), &None).expect("delete"); + assert_eq!(colour(directory.path()), None); + } + + #[test] + fn a_replaced_database_file_is_read_again() { + let directory = tempfile::tempdir().expect("directory"); + store_setting::(directory.path(), &Some("red".to_owned())) + .expect("store"); + assert_eq!(colour(directory.path()).as_deref(), Some("red")); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file( + directory.path().join(format!("{NODE_DATABASE}{suffix}")), + ); + } + assert_eq!(colour(directory.path()), None); + store_setting::(directory.path(), &Some("green".to_owned())) + .expect("store"); + assert_eq!(colour(directory.path()).as_deref(), Some("green")); + } + + fn absent(kept: &mut KeptStore) -> Result { + kept.read(|store| store.configuration("absent").or(Ok(String::new()))) + } + + #[test] + fn a_kept_store_fails_closed_for_a_file_that_a_newer_binary_migrated() { + let directory = tempfile::tempdir().expect("directory"); + let mut kept = KeptStore::new(directory.path().to_path_buf(), false); + absent(&mut kept).expect("the first read opens the store"); + let database = directory.path().join(NODE_DATABASE); + let other = rusqlite::Connection::open(&database).expect("database must open"); + let version: i64 = other + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .expect("version must read"); + // A newer binary migrated the file while this connection stayed open. + other.pragma_update(None, "user_version", version + 1).expect("bump"); + assert!(matches!(absent(&mut kept), Err(StoreError::Migration(_)))); + assert!(kept.open.is_none(), "a store that failed the check is dropped"); + assert!(matches!(absent(&mut kept), Err(StoreError::Migration(_)))); + other.pragma_update(None, "user_version", version).expect("restore"); + assert_eq!(absent(&mut kept).as_deref(), Ok("")); + } + + #[cfg(unix)] + #[test] + fn a_kept_store_opens_a_file_that_replaced_the_old_one() { + let directory = tempfile::tempdir().expect("directory"); + let mut kept = KeptStore::new(directory.path().to_path_buf(), false); + kept.current() + .expect("open") + .put_configuration("test.k", "old") + .expect("write"); + let first = kept.open.as_ref().and_then(|(file, _)| *file); + // An operator restores a backup: the path names another file. + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file( + directory.path().join(format!("{NODE_DATABASE}{suffix}")), + ); + } + NodeStore::in_dir(directory.path()) + .expect("store") + .put_configuration("test.k", "restored") + .expect("write"); + let read = + |kept: &mut KeptStore| kept.read(|store| store.configuration("test.k")); + assert_eq!(read(&mut kept).as_deref(), Ok("restored")); + let second = kept.open.as_ref().and_then(|(file, _)| *file); + assert!(first.is_some() && second.is_some() && first != second); + } + + #[test] + fn a_kept_store_opens_once_for_many_reads() { + let directory = tempfile::tempdir().expect("directory"); + let mut kept = KeptStore::new(directory.path().join("node"), true); + let opened = std::cell::Cell::new(0_u32); + for _ in 0..3 { + kept.read(|store| { + opened.set(opened.get().saturating_add(1)); + store.configuration("absent").or(Ok(String::new())) + }) + .expect("read"); + } + assert_eq!(opened.get(), 3); + assert!(kept.open.is_some(), "the store stays open after a read"); + let first = kept.open.as_ref().map(|(file, _)| *file); + kept.read(|store| store.configuration("absent").or(Ok(String::new()))) + .expect("read"); + assert!(kept.open.as_ref().map(|(file, _)| *file) == first); + } +} diff --git a/crates/aether/src/transport/client.rs b/crates/aether/src/transport/client.rs index 188f472..4871a0e 100644 --- a/crates/aether/src/transport/client.rs +++ b/crates/aether/src/transport/client.rs @@ -10,11 +10,13 @@ use uuid::Uuid; use crate::discovery::{Record, validate_record}; use super::{ - server::{bind_node, read_frames, validate_response, write_frames}, + server::{ + a2a_error_message, bind_node, read_frames, validate_response, write_frames, + }, wire::{ A2aRequest, A2aTask, A2aTaskStatus, ALPN, EVENT_CURSOR, EVENT_SEQUENCE, Frame, - FrameKind, HANDSHAKE_TIMEOUT, MORE_EVENTS, STREAM_TIMEOUT, TASK_POLL_DEADLINE, - TASK_POLL_INTERVAL, TransportError, + FrameKind, HANDSHAKE_TIMEOUT, MORE_EVENTS, RETRY_AFTER_MS, STREAM_TIMEOUT, + TASK_POLL_DEADLINE, TransportError, overload_retry_wait, task_poll_delay, }, }; @@ -280,7 +282,7 @@ pub fn response_more_events_remain(response: &[Frame]) -> bool { ) } -async fn request_with_polling_on( +pub(super) async fn request_with_polling_on( endpoint: &iroh::Endpoint, remote: iroh::EndpointAddr, mut request: Frame, @@ -297,6 +299,9 @@ async fn request_with_polling_on( // last poll's response. let mut collected: Vec = Vec::new(); let mut link = Link::default(); + let mut polls: u32 = 0; + let mut overloaded_since: Option = None; + let mut overload_retries: u32 = 0; loop { payload.idempotency_key = idempotency_key.clone(); @@ -308,6 +313,27 @@ async fn request_with_polling_on( request.payload = serde_json::to_value(&payload).map_err(|_| TransportError::BadFrame)?; let response = link.exchange(endpoint, remote.clone(), request.clone()).await?; + // A host whose per-peer rate limit shed the exchange admitted nothing + // and sent no events. Every exchange carries the same idempotency + // key, so sending it again a little later is safe; after + // `OVERLOAD_RETRY_WINDOW` the error goes to the caller. A full queue + // is not retried: the host rejects that request at once, by design. + // No wait passes the end of the window or of `TASK_POLL_DEADLINE`. + if is_rate_limited(&response) { + let since = *overloaded_since.get_or_insert_with(std::time::Instant::now); + if let Some(wait) = overload_retry_wait( + overload_retries, + since.elapsed(), + TASK_POLL_DEADLINE.saturating_sub(started.elapsed()), + ) { + tokio::time::sleep(wait).await; + overload_retries = overload_retries.saturating_add(1); + continue; + } + } else { + overloaded_since = None; + overload_retries = 0; + } let is_error = response.last().is_some_and(|frame| frame.kind == FrameKind::Error); last_sequence = last_sequence.max(response_last_event_sequence(&response)); @@ -329,10 +355,22 @@ async fn request_with_polling_on( if started.elapsed() >= TASK_POLL_DEADLINE { return Err(TransportError::Timeout); } - tokio::time::sleep(TASK_POLL_INTERVAL).await; + // Poll again soon after the submit and back off to the steady + // rate; the wire protocol is unchanged, so old hosts still work. + tokio::time::sleep(task_poll_delay(polls)).await; + polls = polls.saturating_add(1); } } +/// Whether `response` is only the "node overloaded" error that the host's +/// per-peer rate limit sends: the one with `RETRY_AFTER_MS` in its `data`. +pub(crate) fn is_rate_limited(response: &[Frame]) -> bool { + matches!(response, [frame] if frame.kind == FrameKind::Error + && frame.payload.get("message").and_then(serde_json::Value::as_str) + == Some(a2a_error_message(&TransportError::Overloaded)) + && frame.payload.pointer(&format!("/data/{RETRY_AFTER_MS}")).is_some()) +} + async fn exchange_stream( connection: &iroh::endpoint::Connection, request: Frame, diff --git a/crates/aether/src/transport/server.rs b/crates/aether/src/transport/server.rs index d012872..46bbfa5 100644 --- a/crates/aether/src/transport/server.rs +++ b/crates/aether/src/transport/server.rs @@ -17,11 +17,12 @@ use tower::{ use super::wire::{ A2aError, ALPN, Frame, FrameKind, HANDLER_TIMEOUT, MAX_CONNECTIONS, MAX_EXCHANGE_BYTES, MAX_FRAME_BYTES, MAX_FRAMES, PEER_REQUESTS_PER_SECOND, - RESPONSE_LINGER, STREAM_TIMEOUT, TransportError, events_then_outcome, key_error, - payload, validate_header, validate_order, validate_payloads, + RESPONSE_LINGER, RETRY_AFTER_MS, STREAM_TIMEOUT, TransportError, + events_then_outcome, key_error, overload_retry_delay, payload, validate_header, + validate_order, validate_payloads, }; -type PeerLimiter = DefaultKeyedRateLimiter; +pub(crate) type PeerLimiter = DefaultKeyedRateLimiter; type HandlerService = BoxCloneSyncService<(String, Vec), Vec, BoxError>; pub async fn bind_node( @@ -88,6 +89,22 @@ pub async fn switch_relay( } pub fn router(endpoint: iroh::Endpoint, handler: F) -> iroh::protocol::Router +where + F: Fn(&str, Vec) -> Result, TransportError> + + Send + + Sync + + 'static, +{ + router_with_limiter(endpoint, handler, peer_limiter()) +} + +/// [`router`] with the per-peer limiter that the caller gives, so that a test +/// can use a small quota. The node uses [`peer_limiter`]. +pub(crate) fn router_with_limiter( + endpoint: iroh::Endpoint, + handler: F, + limiter: PeerLimiter, +) -> iroh::protocol::Router where F: Fn(&str, Vec) -> Result, TransportError> + Send @@ -99,7 +116,7 @@ where ALPN, AetherProtocol { handler: handler_service(handler), - limiter: Arc::new(peer_limiter()), + limiter: Arc::new(limiter), permits: Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS)), cancellation: CancellationToken::new(), tasks: TaskTracker::new(), @@ -205,7 +222,7 @@ async fn serve_stream( ) -> Result<(), TransportError> { let request = read_frames(&mut receive).await?; if limiter.check_key(&authenticated_endpoint.to_owned()).is_err() { - let response = error_response(&request, &TransportError::Overloaded); + let response = rate_limited_response(&request); write_frames(&mut send, &response).await?; return send .finish() @@ -280,6 +297,12 @@ pub(crate) fn peer_limiter() -> PeerLimiter { // The constant is not zero; the fallback only keeps the conversion total. let requests = std::num::NonZeroU32::new(PEER_REQUESTS_PER_SECOND) .unwrap_or(std::num::NonZeroU32::MIN); + peer_limiter_for(requests) +} + +/// A per-peer limiter that allows `requests` a second, with a burst of as +/// many. +pub(crate) fn peer_limiter_for(requests: std::num::NonZeroU32) -> PeerLimiter { RateLimiter::keyed(Quota::per_second(requests)) } @@ -330,6 +353,22 @@ const fn a2a_error_code(error: &TransportError) -> i32 { /// Safe state data a caller can act on without parsing the error message. /// Never includes task input or output, matching the redaction rules that /// already govern logs, UI, and MCP responses. +/// The "node overloaded" error of an exchange that the per-peer rate limit +/// shed. Its `data` names the wait (`RETRY_AFTER_MS`) for one more token, so +/// a caller can tell it from a full queue, which it must not retry. The +/// message and code are those of every other overloaded error, so a caller +/// that does not read `data` sees no change. +pub(crate) fn rate_limited_response(request: &[Frame]) -> Vec { + let mut response = error_response(request, &TransportError::Overloaded); + let wait = u64::try_from(overload_retry_delay(0).as_millis()).unwrap_or(u64::MAX); + if let Some(payload) = + response.first_mut().and_then(|frame| frame.payload.as_object_mut()) + { + payload.insert("data".to_owned(), serde_json::json!({ RETRY_AFTER_MS: wait })); + } + response +} + fn a2a_error_data(error: &TransportError) -> Option { match error { TransportError::OperatorReviewRequired(state) => { @@ -339,7 +378,7 @@ fn a2a_error_data(error: &TransportError) -> Option { } } -const fn a2a_error_message(error: &TransportError) -> &'static str { +pub(super) const fn a2a_error_message(error: &TransportError) -> &'static str { match error { TransportError::UnsupportedVersion => "unsupported version", TransportError::PermissionDenied => "permission denied", diff --git a/crates/aether/src/transport/tests.rs b/crates/aether/src/transport/tests.rs index ebc50d8..7bb7a38 100644 --- a/crates/aether/src/transport/tests.rs +++ b/crates/aether/src/transport/tests.rs @@ -376,6 +376,63 @@ fn task_polling_stays_under_the_peer_rate_limit() { assert!(polls_per_second * 2 <= u128::from(super::PEER_REQUESTS_PER_SECOND)); } +#[test] +fn task_poll_delay_starts_short_doubles_and_stops_at_the_interval() { + let delays: Vec = (0..8).map(super::task_poll_delay).collect(); + assert_eq!(delays.first(), Some(&super::TASK_POLL_INITIAL)); + assert!(delays.windows(2).all(|pair| pair[0] <= pair[1])); + assert_eq!(delays.last(), Some(&super::TASK_POLL_INTERVAL)); + assert_eq!(super::task_poll_delay(u32::MAX), super::TASK_POLL_INTERVAL); + assert!(super::TASK_POLL_INITIAL < super::TASK_POLL_INTERVAL / 4); +} + +#[test] +fn early_task_polls_leave_room_under_the_peer_rate_limit() { + // The submit and every re-poll in the first second fit in one burst of + // the per-peer quota. A second task from the same peer can exceed it; + // the client then sends again (see `overload_retry_delay`). + let mut elapsed = Duration::ZERO; + let mut requests: u32 = 1; + for polls in 0.. { + elapsed += super::task_poll_delay(polls); + if elapsed > Duration::from_secs(1) { + break; + } + requests += 1; + } + assert!(requests <= super::PEER_REQUESTS_PER_SECOND, "{requests} requests"); +} + +#[test] +fn overload_retries_start_at_one_rate_token_and_stay_in_the_window() { + let first = super::overload_retry_delay(0); + assert_eq!(first * super::PEER_REQUESTS_PER_SECOND, Duration::from_secs(1)); + let delays: Vec = (0..8).map(super::overload_retry_delay).collect(); + assert!(delays.windows(2).all(|pair| pair[0] <= pair[1])); + assert!(super::overload_retry_delay(u32::MAX) <= super::OVERLOAD_RETRY_WINDOW); + // At least two sends fit in the window, so a burst from one peer clears. + assert!(first + super::overload_retry_delay(1) < super::OVERLOAD_RETRY_WINDOW); +} + +#[test] +fn only_the_rate_limit_error_is_retried_not_a_full_queue() { + let frame = request(); + let request = std::slice::from_ref(&frame); + let rate_limited = super::server::rate_limited_response(request); + assert!(super::client::is_rate_limited(&rate_limited)); + // Same message and code as every other overloaded error. + let full_queue = + super::server::error_response(request, &TransportError::Overloaded); + assert_eq!(rate_limited[0].payload["message"], full_queue[0].payload["message"]); + assert_eq!(rate_limited[0].payload["code"], full_queue[0].payload["code"]); + assert!(!super::client::is_rate_limited(&full_queue)); + let denied = + super::server::error_response(request, &TransportError::PermissionDenied); + assert!(!super::client::is_rate_limited(&denied)); + assert!(!super::client::is_rate_limited(&[])); + assert!(!super::client::is_rate_limited(&[result()])); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn one_connection_serves_one_stream_after_another() { let (receiver, lookup) = bound_receiver().await; @@ -432,6 +489,184 @@ async fn a_rate_limited_peer_reads_the_overloaded_error_frame() { receiver.close().await; } +/// A per-peer limiter that lets one request through in a second, so the +/// second request of a peer in a row is shed. +fn one_a_second() -> super::PeerLimiter { + super::peer_limiter_for(std::num::NonZeroU32::MIN) +} + +/// A limiter that lets one request through in an hour: a shed peer stays shed. +fn one_an_hour() -> super::PeerLimiter { + governor::RateLimiter::keyed(governor::Quota::per_hour(std::num::NonZeroU32::MIN)) +} + +#[test] +fn a_rate_limited_response_passes_the_response_check() { + let frame = probe_request(); + let request = std::slice::from_ref(&frame); + let response = super::server::rate_limited_response(request); + assert_eq!(super::validate_response(request, &response), Ok(())); +} + +#[test] +fn an_overload_wait_never_passes_the_window_or_the_budget() { + // Follows the loop of the callers: each wait adds to the time since the + // first shed answer, and the budget is what the caller's own limit leaves. + let total = |limit: Duration| { + let mut shed_for = Duration::ZERO; + let mut retries: u32 = 0; + while let Some(wait) = super::overload_retry_wait( + retries, + shed_for, + limit.saturating_sub(shed_for), + ) { + assert!(!wait.is_zero()); + assert!(wait <= super::overload_retry_delay(retries)); + shed_for += wait; + retries += 1; + } + shed_for + }; + // The last send is at the end of the window, not up to a second after it. + assert_eq!(total(Duration::MAX), super::OVERLOAD_RETRY_WINDOW); + assert_eq!(total(Duration::from_millis(300)), Duration::from_millis(300)); + assert_eq!(total(Duration::ZERO), Duration::ZERO); + assert_eq!( + super::overload_retry_wait(0, super::OVERLOAD_RETRY_WINDOW, Duration::MAX), + None + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_exchange_that_the_peer_limit_shed_is_sent_again_and_answers() { + let (receiver, lookup) = bound_receiver().await; + let peer = bind_peer(&lookup).await; + let calls = Arc::new(AtomicUsize::new(0)); + let router = super::router_with_limiter( + receiver.clone(), + { + let calls = Arc::clone(&calls); + move |_peer, frames| { + calls.fetch_add(1, Ordering::SeqCst); + let request = frames.first().ok_or(TransportError::BadFrame)?; + Ok(vec![matching_result(request)]) + } + }, + one_a_second(), + ); + let started = std::time::Instant::now(); + for _ in 0..2 { + let response = super::client::request_with_polling_on( + &peer, + receiver.addr(), + probe_request(), + ) + .await + .expect("the request must answer"); + assert_eq!(response.last().map(|frame| frame.kind), Some(FrameKind::Result)); + } + // The limiter lets the second request through one second after the first, + // so the second call was shed, waited, and sent again. + assert!(started.elapsed() >= Duration::from_millis(900), "{:?}", started.elapsed()); + assert_eq!(calls.load(Ordering::SeqCst), 2, "a shed exchange is not admitted"); + router.shutdown().await.expect("router must stop"); + receiver.close().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_peer_that_stays_shed_gets_the_error_at_the_end_of_the_window() { + let (receiver, lookup) = bound_receiver().await; + let peer = bind_peer(&lookup).await; + let calls = Arc::new(AtomicUsize::new(0)); + let router = super::router_with_limiter( + receiver.clone(), + { + let calls = Arc::clone(&calls); + move |_peer, frames| { + calls.fetch_add(1, Ordering::SeqCst); + let request = frames.first().ok_or(TransportError::BadFrame)?; + Ok(vec![matching_result(request)]) + } + }, + one_an_hour(), + ); + super::client::request_with_polling_on(&peer, receiver.addr(), probe_request()) + .await + .expect("the first request must answer"); + let started = std::time::Instant::now(); + let response = + super::client::request_with_polling_on(&peer, receiver.addr(), probe_request()) + .await + .expect("a shed request ends with the error frame"); + let elapsed = started.elapsed(); + assert!(super::client::is_rate_limited(&response)); + assert_eq!(calls.load(Ordering::SeqCst), 1); + // No wait starts before the end of the window and runs past it. + assert!(elapsed >= super::OVERLOAD_RETRY_WINDOW, "{elapsed:?}"); + assert!( + elapsed < super::OVERLOAD_RETRY_WINDOW + Duration::from_millis(600), + "{elapsed:?}" + ); + router.shutdown().await.expect("router must stop"); + receiver.close().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_full_queue_is_returned_at_once_and_not_sent_again() { + let (receiver, lookup) = bound_receiver().await; + let peer = bind_peer(&lookup).await; + let calls = Arc::new(AtomicUsize::new(0)); + let router = super::router(receiver.clone(), { + let calls = Arc::clone(&calls); + move |_peer, _frames| { + calls.fetch_add(1, Ordering::SeqCst); + Err(TransportError::Overloaded) + } + }); + let response = + super::client::request_with_polling_on(&peer, receiver.addr(), probe_request()) + .await + .expect("an error frame is an answer"); + assert_eq!(response.len(), 1); + assert_eq!(response[0].kind, FrameKind::Error); + assert_eq!(response[0].payload["message"], "node overloaded"); + assert!(response[0].payload.get("data").is_none()); + assert!(!super::client::is_rate_limited(&response)); + assert_eq!(calls.load(Ordering::SeqCst), 1); + router.shutdown().await.expect("router must stop"); + receiver.close().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_link_passes_the_rate_limited_error_through_the_response_check() { + let (receiver, lookup) = bound_receiver().await; + let peer = bind_peer(&lookup).await; + let router = super::router_with_limiter( + receiver.clone(), + |_peer, frames| { + let request = frames.first().ok_or(TransportError::BadFrame)?; + Ok(vec![matching_result(request)]) + }, + one_an_hour(), + ); + let mut link = super::Link::default(); + let first = link + .exchange(&peer, receiver.addr(), probe_request()) + .await + .expect("the first exchange must answer"); + assert_eq!(first[0].kind, FrameKind::Result); + // `Link::exchange` runs `validate_response` on what it reads: the shed + // answer must pass it, or the caller would see an error and not retry. + let shed = link + .exchange(&peer, receiver.addr(), probe_request()) + .await + .expect("the shed exchange must pass the response check"); + assert!(super::client::is_rate_limited(&shed)); + drop(link); + router.shutdown().await.expect("router must stop"); + receiver.close().await; +} + #[tokio::test] async fn a_link_returns_one_snapshot_for_each_exchange_on_one_connection() { let (receiver, lookup) = bound_receiver().await; diff --git a/crates/aether/src/transport/wire.rs b/crates/aether/src/transport/wire.rs index 541091c..cae5b40 100644 --- a/crates/aether/src/transport/wire.rs +++ b/crates/aether/src/transport/wire.rs @@ -43,13 +43,69 @@ pub(crate) const HANDLER_TIMEOUT: Duration = Duration::from_secs(30); /// close would), so this does not truncate an already-`finish()`ed /// response. pub(crate) const RESPONSE_LINGER: Duration = Duration::from_secs(2); -/// At most half of `PEER_REQUESTS_PER_SECOND`, so one polling task never -/// trips the node's per-peer rate limit and a second concurrent task from -/// the same peer still fits under it. +/// The longest wait between two polls of one task: at most half of +/// `PEER_REQUESTS_PER_SECOND`, so a task that has run for a while polls at +/// 4 requests a second, and two such tasks fill the limit. The first second +/// of a task is faster (see `TASK_POLL_INITIAL`): its submit and early polls +/// are about 7 requests, so two tasks that start together send about 14 in +/// that second. They fit only because the limiter allows a burst of +/// `PEER_REQUESTS_PER_SECOND` and refills 8 tokens a second, and because the +/// client sends an exchange again when the limit sheds it (see +/// `overload_retry_wait`). pub(crate) const TASK_POLL_INTERVAL: Duration = Duration::from_millis(250); +/// The wait before the first re-poll. A task that finishes within moments +/// of its submit answers the first re-poll instead of waiting out +/// `TASK_POLL_INTERVAL`. Each later wait doubles, up to +/// `TASK_POLL_INTERVAL`, so a long task polls at the steady rate. +pub(crate) const TASK_POLL_INITIAL: Duration = Duration::from_millis(20); pub(crate) const TASK_POLL_DEADLINE: Duration = Duration::from_secs(120); pub(crate) const PEER_REQUESTS_PER_SECOND: u32 = 8; +/// The wait before the next poll, after `polls_so_far` re-polls: +/// `TASK_POLL_INITIAL`, doubled for each earlier re-poll and capped at +/// `TASK_POLL_INTERVAL`. +pub(crate) fn task_poll_delay(polls_so_far: u32) -> Duration { + let factor = 1u32.checked_shl(polls_so_far).unwrap_or(u32::MAX); + TASK_POLL_INITIAL.saturating_mul(factor).min(TASK_POLL_INTERVAL) +} + +/// The key in the `data` of a "node overloaded" error that the per-peer rate +/// limit sent: the milliseconds until the peer has one more token. A full +/// queue sends no `data`, and a caller does not retry it. +pub(crate) const RETRY_AFTER_MS: &str = "retryAfterMs"; +/// How long a request keeps sending an exchange again while the host +/// answers that its rate limit shed it, before the error goes to the caller. +pub(crate) const OVERLOAD_RETRY_WINDOW: Duration = Duration::from_secs(2); +/// The longest wait between two of those sends. +const OVERLOAD_RETRY_MAX: Duration = Duration::from_secs(1); + +/// The wait before the next send after `retries_so_far` overloaded answers: +/// one token of the per-peer rate limit (`1 s / PEER_REQUESTS_PER_SECOND`), +/// doubled for each earlier retry and capped at `OVERLOAD_RETRY_MAX`. +pub(crate) fn overload_retry_delay(retries_so_far: u32) -> Duration { + let factor = 1u32.checked_shl(retries_so_far).unwrap_or(u32::MAX); + let token = Duration::from_secs(1) + .checked_div(PEER_REQUESTS_PER_SECOND) + .unwrap_or(OVERLOAD_RETRY_MAX); + token.saturating_mul(factor).min(OVERLOAD_RETRY_MAX) +} + +/// How long to wait before sending a shed exchange again, or `None` when the +/// caller gives up and returns the error. `shed_for` is the time since the +/// first shed answer of this run; `budget` is the time that the caller's own +/// limit leaves (`TASK_POLL_DEADLINE`, the window of an outbox attempt). The +/// wait never passes the end of `OVERLOAD_RETRY_WINDOW` or the budget, so +/// the last send is at the end of the window, not up to +/// `OVERLOAD_RETRY_MAX` after it. +pub(crate) fn overload_retry_wait( + retries_so_far: u32, + shed_for: Duration, + budget: Duration, +) -> Option { + let left = OVERLOAD_RETRY_WINDOW.saturating_sub(shed_for).min(budget); + (!left.is_zero()).then(|| overload_retry_delay(retries_so_far).min(left)) +} + #[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum FrameKind { diff --git a/crates/aether/tests/steps/tasks.rs b/crates/aether/tests/steps/tasks.rs index 3dfba28..2e20281 100644 --- a/crates/aether/tests/steps/tasks.rs +++ b/crates/aether/tests/steps/tasks.rs @@ -167,6 +167,10 @@ pub struct State { root: Scratch, agent: Agent, max_context_tokens: Option, + /// How many tasks the owner lets the host run at once. + running_tasks: Option, + /// How many tasks the owner lets the host keep waiting. + waiting_tasks: Option, owner_codex_home: Option, callers: Vec, /// The next claim or grant nonce. @@ -409,6 +413,12 @@ impl State { if let Some(tokens) = self.max_context_tokens { limits.max_context_tokens = tokens; } + if let Some(running) = self.running_tasks { + limits.running_tasks = running; + } + if let Some(waiting) = self.waiting_tasks { + limits.queue_global = waiting; + } let mut policy = policy_for_grants( &workspace, &grants, @@ -721,6 +731,16 @@ const fn max_context_tokens(world: &mut World, tokens: u64) { world.tasks.max_context_tokens = Some(tokens); } +#[given(expr = "the host node runs {int} tasks at once")] +const fn running_tasks(world: &mut World, tasks: u64) { + world.tasks.running_tasks = Some(tasks); +} + +#[given(expr = "the host node keeps {int} waiting tasks")] +const fn waiting_tasks(world: &mut World, tasks: u64) { + world.tasks.waiting_tasks = Some(tasks); +} + #[given("the host node is running")] async fn host_running(world: &mut World) { world.tasks.start_host().await; @@ -1175,6 +1195,98 @@ async fn caller_task_in_state(world: &mut World, caller: usize, wanted: String) world.tasks.start_in_background(request, wanted).await; } +/// Starts one `node request` for each of the first `count` callers, all +/// before any of them is admitted. +#[when(expr = "{int} callers send a task at the same time")] +fn callers_send_together(world: &mut World, count: usize) { + let state = &mut world.tasks; + for index in 0..count { + let request = Request { + caller: index, + task_id: Some(overload_task_id(index)), + ..state.request(&format!("request {index}")) + }; + let child = state + .request_command(&request) + .stdout(Stdio::piped()) + .spawn() + .expect("request command must start"); + state.running.0.push(child); + } +} + +/// The states of the tasks that the callers sent together, as the store of +/// the host holds them. +async fn states_of_sent_tasks(world: &mut World, count: usize) -> Vec { + let ids = (0..count).map(overload_task_id).collect::>(); + world + .tasks + .store(move |store| { + ids.iter().filter_map(|id| store.state(id).ok()).collect::>() + }) + .await +} + +/// Polls until `done` holds for the states of the first `count` tasks. The +/// agent takes a second to answer, so the states hold while a poll sees them. +async fn wait_for_states( + world: &mut World, + count: usize, + what: &str, + done: impl Fn(&[TaskState]) -> bool, +) { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let states = states_of_sent_tasks(world, count).await; + if done(&states) { + return; + } + assert!( + Instant::now() < deadline, + "timed out waiting for {what}, last states {states:?}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +#[then("both tasks run at the same time")] +async fn both_tasks_run_together(world: &mut World) { + wait_for_states(world, 2, "both tasks to run", |states| { + states.len() == 2 && states.iter().all(|state| *state == TaskState::Running) + }) + .await; +} + +/// With one slot, the second task is admitted and waits until the first +/// ends: no poll ever sees both of them running. +#[then("one task runs while the other waits")] +async fn one_task_runs_the_other_waits(world: &mut World) { + wait_for_states(world, 2, "one task to run and one to wait", |states| { + let running = + states.iter().filter(|state| **state == TaskState::Running).count(); + let queued = states.iter().filter(|state| **state == TaskState::Queued).count(); + states.len() == 2 && running == 1 && queued == 1 + }) + .await; + // Both end, one after the other, and never run together. + let mut together = false; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let states = states_of_sent_tasks(world, 2).await; + together |= + states.iter().filter(|state| **state == TaskState::Running).count() > 1; + if states.iter().all(|state| *state == TaskState::Succeeded) { + break; + } + assert!( + Instant::now() < deadline, + "the tasks must end, last states {states:?}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(!together, "a node with one slot ran two tasks at once"); +} + #[when(expr = "caller {int} sends a task")] async fn caller_sends_task(world: &mut World, caller: usize) { let index = caller - 1; diff --git a/docs/configuration.md b/docs/configuration.md index d9c261c..9d831d2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -29,7 +29,48 @@ A connected agent speaks one JSON object on each line. It sends `progress`, `result` (`text`), `failed` or `cancelled`, each with the task `id`. The node sends no keys, grants, endpoint IDs or caller names. The socket file mode is `0600`. When no agent is connected, the node fails each -task as not available. At `maxSeconds`, the node cancels the turn. +task as not available. At `maxSeconds`, the node cancels the turn. The +`ready` message can also say `"max_tasks"`: how many tasks the agent takes at +once (see "Tasks that run at once"). + +## Tasks that run at once + +The node runs one task at a time unless its owner says more. The policy field +`runningTasks` is how many tasks run at the same time, for all callers +together. It is 1 for a new node and for a policy file that does not have the +field, so a node that you upgrade behaves as before. It can be 1 to 32: each +running task is a turn of the agent, and for Codex its own `codex app-server` +process, so a higher number needs a computer that can run that many agents. + +It is separate from the waiting limits `queueGlobal` and `queuePerPeer`, +which say how many tasks wait. A task that comes while `runningTasks` tasks +run waits in the queue, in the order that the node always used, and counts +against those limits. There is no limit for one caller or one group of running +tasks. + +Change it like the waiting limits, with the same checks and audit records: + +- On the **Advanced** page, **Task policy**, **Tasks running at once**. Saved + policy changes take effect after a restart. +- With `aether.settings.update_policy` (`running_tasks`) or with + `aether.change` (`{"type": "limit", "id": "running_tasks", "limit": 2}`). + `aether.change` changes the running node at once: a task that waits starts + as soon as there is room. A higher value waits for your confirmation under + Pending changes on the Advanced page; a lower value applies at once. + +Lowering the limit never stops a task that runs. The node starts no new task +until fewer than the new number of tasks run. + +The agent can allow fewer tasks than you do; the node uses the smaller +number: + +| Agent | Tasks at once | +| --- | --- | +| Codex, `sandbox` `task-folder` (default) | As many as `runningTasks`. Each task has its own folder and its own Codex process. | +| Codex, `sandbox` `workspace-write` | One. All tasks would write the same folder. | +| Hermes plugin, OpenClaw plugin | Up to 32: each task is its own session, and the plugin says so in `ready`. | +| Grok Bot bridge | One: a Bot claims one task at a time. | +| A connected agent that does not say `max_tasks` | One. | ## Real Codex diff --git a/docs/usage.md b/docs/usage.md index 0b9a04b..98e8dc1 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -14,7 +14,7 @@ database. `--policy` selects another file for this one-time import. After that, the database is the policy source and changes to the old file have no effect. On the **Advanced** page, **Task policy** sets the task folder root, context -and time limits, and queue limits. The folder must exist. Restart the node +and time limits, queue limits, and how many tasks run at once. The folder must exist. Restart the node after you save a policy change. **Permissions** links to the invite and access group controls on the Sharing page. @@ -27,7 +27,8 @@ The default policy has these values: "maxContextTokens": 20000, "maxSeconds": 120, "queueGlobal": 1, - "queuePerPeer": 1 + "queuePerPeer": 1, + "runningTasks": 1 } ``` @@ -80,7 +81,8 @@ endpoint ID. The default `friends` group stays available for new invites. The same node data directory serves MCP tools for these groups, task policy, relay and hub URLs, your hub name, invites, and direct access. Use `aether.settings.get` to read the saved policy and URLs. Use -`aether.settings.update_policy` to edit task limits or the task folder root. +`aether.settings.update_policy` to edit task limits (`queue_global`, `queue_per_peer`, +`running_tasks`) or the task folder root. A new task folder root or a higher limit waits until you confirm it under Pending changes on the Advanced page. Policy changes need a node restart. `aether.settings.set_relay` changes a running node at once, and @@ -215,6 +217,8 @@ list the agent again after a rename or a change of the card text. - People who get access by request share the task queue with your friends: the node keeps `queueGlobal` waiting tasks in all and `queuePerPeer` for each person. Change them in **Advanced**. + They wait for a free place to run: the node runs `runningTasks` tasks at the + same time, one by default (see [Tasks that run at once](configuration.md#tasks-that-run-at-once)). ## Access requests diff --git a/features/node/running-tasks.feature b/features/node/running-tasks.feature new file mode 100644 index 0000000..bf1a680 --- /dev/null +++ b/features/node/running-tasks.feature @@ -0,0 +1,23 @@ +Feature: Tasks that run at once + The owner of a node says how many tasks the node runs at the same time, + for all callers together. A new node, and a node from before the limit + existed, runs one task at a time and the others wait their turn. The + waiting limits of the queue are a separate setting. + + Background: + Given a host node whose agent takes a second to answer + And the host node keeps 4 waiting tasks + And 2 callers with a signed authorization for the "direct" scope + + Scenario: By default the node runs one task at a time + Given the host node is running + When 2 callers send a task at the same time + Then one task runs while the other waits + And the host node stops cleanly + + Scenario: A node whose owner allows two runs two tasks at once + Given the host node runs 2 tasks at once + And the host node is running + When 2 callers send a task at the same time + Then both tasks run at the same time + And the host node stops cleanly diff --git a/integrations/grokbot-bridge/README.md b/integrations/grokbot-bridge/README.md index 8a44909..35951c9 100644 --- a/integrations/grokbot-bridge/README.md +++ b/integrations/grokbot-bridge/README.md @@ -125,6 +125,12 @@ A manual Bot prompt works for the first proof. Scheduled polling is possible, but Grok's documented minimum interval is five minutes, beyond both the bridge and default node task lifetime of two minutes. It is not a reliable default. +## One task at a time + +The bridge says `max_tasks: 1` in its `ready` message, so the node sends it +one task at a time whatever the owner's `runningTasks` limit is: a Bot claims +one task, and a second task would wait in the mailbox until its time ran out. + ## Cancellation, recovery and shutdown - An unclaimed cancellation is immediately acknowledged as `cancelled`. diff --git a/integrations/grokbot-bridge/src/node-link.mjs b/integrations/grokbot-bridge/src/node-link.mjs index 696c4e3..df454d0 100644 --- a/integrations/grokbot-bridge/src/node-link.mjs +++ b/integrations/grokbot-bridge/src/node-link.mjs @@ -47,7 +47,9 @@ export class NodeLink { socket.on('connect', () => { this.socket = socket; connected = true; - this.send({ type: 'ready', protocol: contract.protocol }); + // One task at a time: a Bot claims one task and the rest wait in the mailbox + // until their time runs out, so the node must not send more than one. + this.send({ type: 'ready', protocol: contract.protocol, max_tasks: 1 }); this.status(true); }); socket.on('data', chunk => { diff --git a/integrations/grokbot-bridge/test/bridge.test.mjs b/integrations/grokbot-bridge/test/bridge.test.mjs index 895021d..40ea832 100644 --- a/integrations/grokbot-bridge/test/bridge.test.mjs +++ b/integrations/grokbot-bridge/test/bridge.test.mjs @@ -58,7 +58,7 @@ async function fixture(t, options = {}) { }); await client.connect(new StreamableHTTPClientTransport(url, { requestInit: { headers: { Authorization: `Bearer ${token}` } } })); await until(() => lines.length > 0); - assert.deepEqual(lines.shift(), { type: 'ready', protocol: contract.protocol }); + assert.deepEqual(lines.shift(), { type: 'ready', protocol: contract.protocol, max_tasks: 1 }); const call = async (name, args = {}) => { const response = await client.callTool({ name, arguments: args }); if (response.isError) return { error: response.content[0].text }; diff --git a/integrations/grokbot-bridge/test/transcript.test.mjs b/integrations/grokbot-bridge/test/transcript.test.mjs index 21951ea..c82f29d 100644 --- a/integrations/grokbot-bridge/test/transcript.test.mjs +++ b/integrations/grokbot-bridge/test/transcript.test.mjs @@ -115,7 +115,8 @@ async function replay(t, steps, outcomes) { const message = step.agent; if (message.type === 'ready') { await fake.accept(); - assert.deepEqual(await fake.read(), message); + // The bridge takes one task at a time and says so, as the transcript does not. + assert.deepEqual(await fake.read(), { type: message.type, protocol: message.protocol, max_tasks: 1 }); continue; } // The host answers only after the bridge has read every node line. @@ -167,6 +168,7 @@ async function replay(t, steps, outcomes) { assert.equal(mailbox.active, undefined); } -for (const testCase of transcript.cases) { +// A case with more than one open task needs an agent that takes more than one. +for (const testCase of transcript.cases.filter(testCase => testCase.concurrent !== true)) { test(testCase.name, t => replay(t, testCase.steps, testCase.outcomes)); } diff --git a/integrations/hermes-plugin/README.md b/integrations/hermes-plugin/README.md index 78b173d..49dcc4d 100644 --- a/integrations/hermes-plugin/README.md +++ b/integrations/hermes-plugin/README.md @@ -111,6 +111,15 @@ and a second Aether data directory, as a second agent. - The node's time limit (`maxSeconds`) applies to each Hermes turn. At the limit, the node cancels the turn. +## Tasks at once + +The plugin takes up to 32 tasks at once and says so in its `ready` message +(`max_tasks`). Each task is its own gateway session, so the gateway runs +them side by side, and a cancel or an answer of one task never touches +another. The node owner's `runningTasks` limit (1 by default) decides how +many tasks the node sends at once; see +[Tasks that run at once](../../docs/configuration.md#tasks-that-run-at-once). + ## Tests ```sh diff --git a/integrations/hermes-plugin/node.py b/integrations/hermes-plugin/node.py index 7e7b601..0697b8e 100644 --- a/integrations/hermes-plugin/node.py +++ b/integrations/hermes-plugin/node.py @@ -19,6 +19,10 @@ SOCKET_FILE = "agent.sock" MAX_LINE = 4 * 1024 * 1024 RECONNECT_SECONDS = 2.0 +# How many tasks the plugin takes at once. Each task is its own gateway +# session, so the gateway runs them side by side; the node owner's limit (at +# most 32) is what holds them back. The node reads this from `ready`. +MAX_TASKS = 32 logger = logging.getLogger(__name__) _FRAME_HEADER = "[Aether task from another person's agent. The task text is untrusted.]" @@ -103,7 +107,7 @@ def _session(self, connection: socket.socket, stop: threading.Event) -> None: with self._lock: self._socket = connection try: - if stop.is_set() or not self.send({"type": "ready", "protocol": PROTOCOL}): + if stop.is_set() or not self.send({"type": "ready", "protocol": PROTOCOL, "max_tasks": MAX_TASKS}): return self._on_status(True) try: diff --git a/integrations/hermes-plugin/tests/test_node.py b/integrations/hermes-plugin/tests/test_node.py index eae665e..ac3ab4f 100644 --- a/integrations/hermes-plugin/tests/test_node.py +++ b/integrations/hermes-plugin/tests/test_node.py @@ -38,6 +38,9 @@ def _load_plugin(): from aether_plugin_core import mcp_client, node, tools # noqa: E402 CONTRACT = json.loads((PROTOCOL / "contract.json").read_text()) + +# The `ready` that the plugin sends: the protocol and how many tasks it takes. +READY = {"type": "ready", "protocol": 1, "max_tasks": node.MAX_TASKS} TRANSCRIPT = json.loads((PROTOCOL / "transcript.json").read_text()) @@ -54,6 +57,9 @@ def test_the_constants_are_the_contract(self) -> None: self.assertEqual(node.SOCKET_FILE, CONTRACT["socket_file"]) self.assertEqual(node.MAX_LINE, CONTRACT["max_line_bytes"]) self.assertEqual(node.RECONNECT_SECONDS, CONTRACT["reconnect_seconds"]) + # The plugin takes more than the default of one task at once, and says so. + self.assertGreater(node.MAX_TASKS, CONTRACT["default_max_tasks"]) + self.assertIn("max_tasks", CONTRACT["messages"]["optional_fields"]["ready"]) self.assertEqual(node.socket_path(Path("/srv")), Path("/srv") / CONTRACT["socket_file"]) def test_the_default_data_dir_follows_the_contract(self) -> None: @@ -170,7 +176,7 @@ def on_message(message: dict) -> None: message = step["agent"] if message["type"] == "ready": fake.accept() - self.assertEqual(fake.read(), message) + self.assertEqual(fake.read(), READY) continue # The host answers only after the plugin has read every node line. _wait(lambda: len(received) == sent, "the plugin must read the node's lines") @@ -240,7 +246,7 @@ def on_status(connected: bool) -> None: self.addCleanup(stop.set) fake.accept() - self.assertEqual(fake.read(), {"type": "ready", "protocol": 1}) + self.assertEqual(fake.read(), READY) for task_id in ("task-1", "task-2"): fake.write(json.dumps({"type": "task", "id": task_id, "instructions": "", "text": "hi"}).encode() + b"\n") fake.write(b'{"type":"cancel","id":"task-1"}\n') @@ -249,11 +255,27 @@ def on_status(connected: bool) -> None: _wait(lambda: statuses == [True, False], "the session must report that it closed") self.assertEqual(host.stopped, ["task-2"]) fake.accept() - self.assertEqual(fake.read(), {"type": "ready", "protocol": 1}) + self.assertEqual(fake.read(), READY) self.assertTrue(runner.is_alive()) class TasksTest(unittest.TestCase): + def test_two_open_tasks_are_answered_and_stopped_separately(self) -> None: + sent: list[dict] = [] + stopped: list[str] = [] + tasks = node.Tasks(send=sent.append, start=lambda task_id, message: task_id, stop=stopped.append) + for task_id in ("task-1", "task-2"): + tasks.receive({"type": "task", "id": task_id, "instructions": "", "text": "hi"}) + tasks.result("task-2", "two") + tasks.receive({"type": "cancel", "id": "task-1"}) + # A late answer of a task that is closed changes nothing. + tasks.result("task-1", "late") + self.assertEqual( + sent, + [{"type": "result", "id": "task-2", "text": "two"}, {"type": "cancelled", "id": "task-1"}], + ) + self.assertEqual(stopped, ["task-1"]) + def test_a_turn_that_cannot_start_fails_its_task(self) -> None: sent: list[dict] = [] diff --git a/integrations/openclaw-plugin/README.md b/integrations/openclaw-plugin/README.md index bd6f76e..4456298 100644 --- a/integrations/openclaw-plugin/README.md +++ b/integrations/openclaw-plugin/README.md @@ -140,6 +140,17 @@ when your data directory is not the default. - When the node connection closes, the node fails the open tasks. The plugin stops their turns too. +## Tasks at once + +The plugin takes up to 32 tasks at once and says so in its `ready` message +(`max_tasks`). Each task has its own OpenClaw session and its own abort +signal, so a cancel or an answer of one task never touches another. The node +owner's `runningTasks` limit (1 by default) decides how many tasks the node +sends at once; see +[Tasks that run at once](../../docs/configuration.md#tasks-that-run-at-once). +OpenClaw's own limit on how many agent runs it does at the same time still +applies: a task above it waits inside OpenClaw and its time limit keeps running. + ## Sessions Each Aether task gets its own OpenClaw session. OpenClaw keeps these diff --git a/integrations/openclaw-plugin/src/node-socket.ts b/integrations/openclaw-plugin/src/node-socket.ts index 9e2816e..c93ab37 100644 --- a/integrations/openclaw-plugin/src/node-socket.ts +++ b/integrations/openclaw-plugin/src/node-socket.ts @@ -2,7 +2,7 @@ // message to onMessage, and connects again when the connection closes. import net from "node:net"; import { setTimeout as sleep } from "node:timers/promises"; -import { MAX_LINE, PROTOCOL, RECONNECT_MS, encode, parseNodeLine } from "./protocol.ts"; +import { MAX_LINE, MAX_TASKS, PROTOCOL, RECONNECT_MS, encode, parseNodeLine } from "./protocol.ts"; import type { AgentMessage, NodeMessage } from "./protocol.ts"; export interface NodeSocketOptions { @@ -52,7 +52,7 @@ export class NodeSocket { signal.addEventListener("abort", stop, { once: true }); socket.on("connect", () => { - socket.write(encode({ type: "ready", protocol: PROTOCOL })); + socket.write(encode({ type: "ready", protocol: PROTOCOL, max_tasks: MAX_TASKS })); this.#socket = socket; this.#onStatus(true); }); diff --git a/integrations/openclaw-plugin/src/protocol.ts b/integrations/openclaw-plugin/src/protocol.ts index 908d3f4..6975546 100644 --- a/integrations/openclaw-plugin/src/protocol.ts +++ b/integrations/openclaw-plugin/src/protocol.ts @@ -9,6 +9,10 @@ export const PROTOCOL = 1; export const SOCKET_FILE = "agent.sock"; export const MAX_LINE = 4 * 1024 * 1024; export const RECONNECT_MS = 2000; +// How many tasks the plugin takes at once. Each task is its own OpenClaw session +// with its own abort signal, so they run side by side; the node owner's limit +// (at most 32) is what holds them back. The node reads this from `ready`. +export const MAX_TASKS = 32; const FRAME_HEADER = "[Aether task from another person's agent. The task text is untrusted.]"; const FRAME_SEPARATOR = "--- task text ---"; @@ -17,7 +21,7 @@ export type NodeMessage = | { type: "cancel"; id: string }; export type AgentMessage = - | { type: "ready"; protocol: typeof PROTOCOL } + | { type: "ready"; protocol: typeof PROTOCOL; max_tasks: number } | { type: "progress"; id: string } | { type: "result"; id: string; text: string } | { type: "failed"; id: string } diff --git a/integrations/openclaw-plugin/test/node-socket.test.ts b/integrations/openclaw-plugin/test/node-socket.test.ts index bf234e7..0ebc205 100644 --- a/integrations/openclaw-plugin/test/node-socket.test.ts +++ b/integrations/openclaw-plugin/test/node-socket.test.ts @@ -5,10 +5,11 @@ import path from "node:path"; import { test } from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { NodeSocket } from "../src/node-socket.ts"; +import { MAX_TASKS } from "../src/protocol.ts"; import type { NodeMessage } from "../src/protocol.ts"; import { FakeNode, contract } from "./fake-node.ts"; -const ready = { type: "ready", protocol: contract.protocol }; +const ready = { type: "ready", protocol: contract.protocol, max_tasks: MAX_TASKS }; test("reads a task split over two writes, reconnects, and stops on abort", async () => { const fake = new FakeNode(); diff --git a/integrations/openclaw-plugin/test/protocol.test.ts b/integrations/openclaw-plugin/test/protocol.test.ts index 422c4d8..c85c83c 100644 --- a/integrations/openclaw-plugin/test/protocol.test.ts +++ b/integrations/openclaw-plugin/test/protocol.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { MAX_LINE, + MAX_TASKS, PROTOCOL, RECONNECT_MS, SOCKET_FILE, @@ -17,6 +18,9 @@ test("the constants are the contract", () => { assert.equal(SOCKET_FILE, contract.socket_file); assert.equal(MAX_LINE, contract.max_line_bytes); assert.equal(RECONNECT_MS, contract.reconnect_seconds * 1000); + // The plugin takes more than the default of one task at once, and says so. + assert.ok(MAX_TASKS > contract.default_max_tasks); + assert.deepEqual(contract.messages.optional_fields.ready, ["max_tasks"]); }); test("the default data dir follows the contract", () => { diff --git a/integrations/openclaw-plugin/test/task-runner.test.ts b/integrations/openclaw-plugin/test/task-runner.test.ts index f499c37..98320e3 100644 --- a/integrations/openclaw-plugin/test/task-runner.test.ts +++ b/integrations/openclaw-plugin/test/task-runner.test.ts @@ -83,3 +83,25 @@ test("the hooks of a cancelled run do not answer a later run with the same id", { type: "result", id: "t1", text: "new answer" }, ]); }); + +test("two open tasks are answered and cancelled separately", () => { + const { runner, sent, calls } = setup(); + runner.handle({ type: "task", id: "t1", instructions: "", text: "one" }); + runner.handle({ type: "task", id: "t2", instructions: "", text: "two" }); + assert.deepEqual( + calls.map((call) => call.id), + ["t1", "t2"], + ); + // The answer of t2 ends only t2. + calls[1].hooks.deliver("two", "final"); + assert.deepEqual(sent, [{ type: "result", id: "t2", text: "two" }]); + assert.equal(calls[0].signal.aborted, false); + // The cancel of t1 aborts only t1; the closed t2 is not touched again. + runner.handle({ type: "cancel", id: "t1" }); + assert.deepEqual(sent.at(-1), { type: "cancelled", id: "t1" }); + assert.equal(calls[0].signal.aborted, true); + assert.equal(calls[1].signal.aborted, false); + // A late answer of t1 changes nothing. + calls[0].hooks.deliver("late", "final"); + assert.equal(sent.length, 2); +}); diff --git a/integrations/openclaw-plugin/test/transcript.test.ts b/integrations/openclaw-plugin/test/transcript.test.ts index 348db26..a9755d3 100644 --- a/integrations/openclaw-plugin/test/transcript.test.ts +++ b/integrations/openclaw-plugin/test/transcript.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { NodeSocket } from "../src/node-socket.ts"; -import { parseNodeLine } from "../src/protocol.ts"; +import { MAX_TASKS, parseNodeLine } from "../src/protocol.ts"; import { TaskRunner } from "../src/task-runner.ts"; import type { Dispatch } from "../src/task-runner.ts"; import { FakeNode, noise, transcript, waitFor } from "./fake-node.ts"; @@ -47,7 +47,12 @@ async function replay(steps: any[], outcomes: Record): Promise + if fresh?(loaded_at), do: account, else: reload(endpoint, row) + + [{^endpoint, :loading, {_ref, started}}] = row -> + if System.monotonic_time(:second) - started > @claim_ttl, + do: reload(endpoint, row), + else: read(endpoint) + + [] -> + claim(endpoint) + end + end + + @doc """ + Forgets the account of `endpoint`. Call it for every write to its row, + inside the transaction that makes the write and again after it. + """ + def invalidate(endpoint) do + :ets.delete(@table, endpoint) + :ok + end + + # A copy of a clock that is behind its own load time (a test moved it) is + # not trusted. + defp fresh?(loaded_at) do + now = Clock.now() + loaded_at <= now and now - loaded_at < @ttl + end + + # An old copy or an abandoned mark goes, and the reader claims the row. If + # another reader claimed it first, this one only reads. + defp reload(endpoint, [row]) do + :ets.delete_object(@table, row) + claim(endpoint) + end + + defp claim(endpoint) do + mark = {make_ref(), System.monotonic_time(:second)} + + if :ets.insert_new(@table, {endpoint, :loading, mark}) do + load(endpoint, mark) + else + read(endpoint) + end + end + + defp load(endpoint, mark) do + # The time before the read: the copy is not younger than this. + loaded_at = Clock.now() + + case read(endpoint) do + nil -> + nil + + account -> + spec = [{{endpoint, :loading, mark}, [], [{{endpoint, {:const, account}, loaded_at}}]}] + :ets.select_replace(@table, spec) + account + end + after + # Gone already when the copy replaced it, or when a write took it. + :ets.delete_object(@table, {endpoint, :loading, mark}) + end + + defp read(endpoint) do + case Repo.get(Account, endpoint) do + nil -> nil + account -> %{account | version: nil} + end + end + + @impl true + def init(nil) do + :ets.new(@table, [:named_table, :public, :set, read_concurrency: true]) + {:ok, nil} + end +end diff --git a/server/lib/aether_hub/accounts.ex b/server/lib/aether_hub/accounts.ex index 4103c7f..5420875 100644 --- a/server/lib/aether_hub/accounts.ex +++ b/server/lib/aether_hub/accounts.ex @@ -5,8 +5,8 @@ defmodule AetherHub.Accounts do listed here, in one place. """ - alias AetherHub.{Account, Blocks, Clock, Contacts, Invites, Listings, Names, OwnerLinks} - alias AetherHub.{Protocol, Repo, Versions} + alias AetherHub.{Account, AccountCache, Blocks, Clock, Contacts, Invites, Listings, Names} + alias AetherHub.{OwnerLinks, Protocol, Repo, Versions} @kinds Protocol.kinds() @service Protocol.kind(:service) @@ -14,6 +14,12 @@ defmodule AetherHub.Accounts do def get(endpoint), do: Repo.get(Account, endpoint) + @doc """ + The account that a signed request acts as, from `AetherHub.AccountCache`. + Every write to the `accounts` table in this module invalidates the cache. + """ + def fetch(endpoint), do: AccountCache.fetch(endpoint) + def json(%Account{} = account) do %{ "handle" => Account.full_name(account), @@ -42,7 +48,13 @@ defmodule AetherHub.Accounts do name or the search setting of `account`. A rename keeps the current number when it is free for the new name. """ - def put(endpoint, account, %{} = body) do + def put(endpoint, account, body) do + result = write(endpoint, account, body) + AccountCache.invalidate(endpoint) + result + end + + defp write(endpoint, account, %{} = body) do with :ok <- valid_body(body) do # The values after the change: the body over the current ones. wanted = Map.merge(current(account), body) @@ -56,7 +68,7 @@ defmodule AetherHub.Accounts do end end - def put(_endpoint, _account, _body), do: {:error, :invalid} + defp write(_endpoint, _account, _body), do: {:error, :invalid} defp valid_body(body) do valid = @@ -86,16 +98,19 @@ defmodule AetherHub.Accounts do Repo.atomic(fn -> name = wanted["name"] - Repo.insert!(%Account{ - endpoint: endpoint, - name: name, - number: number!(name, endpoint, Names.released_numbers(name, endpoint)), - kind: kind, - searchable: searchable, - created_at: Clock.now(), - version: 1 - }) - |> json() + account = + Repo.insert!(%Account{ + endpoint: endpoint, + name: name, + number: number!(name, endpoint, Names.released_numbers(name, endpoint)), + kind: kind, + searchable: searchable, + created_at: Clock.now(), + version: 1 + }) + + AccountCache.invalidate(endpoint) + json(account) end) end end @@ -109,8 +124,11 @@ defmodule AetherHub.Accounts do rename(account, name, searchable) true -> - {:ok, - account |> Ecto.Changeset.change(searchable: searchable) |> Repo.update!() |> json()} + Repo.atomic(fn -> + changed = account |> Ecto.Changeset.change(searchable: searchable) |> Repo.update!() + AccountCache.invalidate(account.endpoint) + json(changed) + end) end end @@ -125,6 +143,7 @@ defmodule AetherHub.Accounts do |> Ecto.Changeset.change(name: name, number: number, searchable: searchable) |> Repo.update!() + AccountCache.invalidate(endpoint) {json(renamed), [endpoint | Invites.counterparts(endpoint)]} end) end @@ -147,15 +166,20 @@ defmodule AetherHub.Accounts do Its tag stays with the key, with its type; blocks stay too. """ def delete(%Account{endpoint: endpoint} = account) do - Versions.commit(fn -> - touched = Enum.uniq(Invites.counterparts(endpoint) ++ Contacts.of(endpoint)) - Names.release(account.name, account.number, endpoint, account.kind) - Invites.delete_for(endpoint) - Contacts.delete_for(endpoint) - end_named_rows(endpoint) - Repo.delete!(account) - {:ok, touched} - end) + result = + Versions.commit(fn -> + touched = Enum.uniq(Invites.counterparts(endpoint) ++ Contacts.of(endpoint)) + Names.release(account.name, account.number, endpoint, account.kind) + Invites.delete_for(endpoint) + Contacts.delete_for(endpoint) + end_named_rows(endpoint) + Repo.delete!(account) + AccountCache.invalidate(endpoint) + {:ok, touched} + end) + + AccountCache.invalidate(endpoint) + result end ## Blocks diff --git a/server/lib/aether_hub/application.ex b/server/lib/aether_hub/application.ex index 0f4fe49..065f003 100644 --- a/server/lib/aether_hub/application.ex +++ b/server/lib/aether_hub/application.ex @@ -14,9 +14,12 @@ defmodule AetherHub.Application do [ AetherHub.Repo, {Ecto.Migrator, repos: [AetherHub.Repo], skip: false}, + AetherHub.ReadRepo, {Registry, keys: :duplicate, name: AetherHub.Waiters}, AetherHub.RateLimit, AetherHub.Presence, + AetherHub.AccountCache, + AetherHub.DirectoryCache, AetherHub.Sweeper ] ++ server() diff --git a/server/lib/aether_hub/directory.ex b/server/lib/aether_hub/directory.ex index b03b874..520ea7f 100644 --- a/server/lib/aether_hub/directory.ex +++ b/server/lib/aether_hub/directory.ex @@ -7,65 +7,92 @@ defmodule AetherHub.Directory do owner when an owner link is active. A row has no endpoint and no signature. For people it gives only a count: no name and no presence, because only contacts see the presence of a person. + + Building the view reads every live listing, so the route serves it from + `AetherHub.DirectoryCache`, which builds it once in 15 seconds at most. """ import Ecto.Query - alias AetherHub.{Account, Clock, Listing, Listings, OwnerLinks, Presence, Repo} + alias AetherHub.{Account, Clock, DirectoryCache, Listing, Listings, Names, OwnerLinks} + alias AetherHub.{Presence, Repo} @max_agents AetherHub.Protocol.limit(:max_directory_agents) @personal AetherHub.Protocol.kind(:personal) @doc """ - The listed service agents, online agents first, then by the latest - update, at most #{@max_agents}. Also the counts of listed agents, of - online listed agents, and of personal accounts. + The directory as the route serves it: the cached view, at most 15 seconds + old, with its age in whole seconds. `{:error, :unavailable}` when the cache + cannot answer. See `AetherHub.DirectoryCache`. + """ + def cached do + {view, age_ms} = DirectoryCache.fetch() + {:ok, view, div(age_ms, 1000)} + rescue + DirectoryCache.Unavailable -> {:error, :unavailable} + end + + @doc """ + Builds the directory now: the listed service agents, online agents first, + then by the latest update, at most #{@max_agents}. Also the counts of + listed agents, of online listed agents, and of personal accounts. + + It reads only the cheap columns of every live listing, and decodes the + listing text of the agents on the page. The hub checked each listing when + the node sent it, so the counts do not decode. A listing that does not + read is a bad row: the page leaves it out and the next agent takes its + place, but `listed` and `online` still count it. """ def snapshot do rows = - Repo.all( - from l in Listing, - join: a in Account, - on: a.endpoint == l.endpoint, - where: l.expires_at > ^Clock.now(), - order_by: [desc: l.updated_at], - select: {l.endpoint, l.listing, a} + from(l in Listing, + join: a in Account, + on: a.endpoint == l.endpoint, + where: l.expires_at > ^Clock.now(), + order_by: [desc: l.updated_at, asc: l.id], + select: {l.id, l.endpoint, a.name, a.number} ) + |> Repo.all() + |> Enum.map(fn {id, endpoint, name, number} -> + {id, endpoint, Names.format(name, number), Presence.online?(endpoint)} + end) - # The hub checked a listing when the node sent it, so a listing that - # does not read is a bad row: the page leaves it out. - agents = - rows - |> Enum.flat_map(fn {endpoint, text, account} -> - case Listings.card(text) do - {:ok, card} -> - online = Presence.online?(endpoint) - - [ - {endpoint, - Map.merge(card, %{"handle" => Account.full_name(account), "online" => online})} - ] + # Online agents first, each group by the latest update. + {online, offline} = Enum.split_with(rows, fn {_id, _endpoint, _handle, online} -> online end) - :error -> - [] - end - end) - |> Enum.sort_by(fn {_endpoint, agent} -> not agent["online"] end) + agents = (online ++ offline) |> cards() |> Enum.take(@max_agents) - page = - agents - |> Enum.take(@max_agents) - # The full name of the owner only: never the owner's presence or - # endpoint. - |> Enum.map(fn {endpoint, agent} -> - Map.put(agent, "owner", OwnerLinks.active_owner(endpoint)) - end) + # The full name of the owner only: never the owner's presence or + # endpoint. + owners = OwnerLinks.active_owners(Enum.map(agents, fn {endpoint, _agent} -> endpoint end)) %{ - "agents" => page, - "listed" => length(agents), - "online" => Enum.count(agents, fn {_endpoint, agent} -> agent["online"] end), + "agents" => + Enum.map(agents, fn {endpoint, agent} -> Map.put(agent, "owner", owners[endpoint]) end), + "listed" => length(rows), + "online" => length(online), "people" => Repo.aggregate(from(a in Account, where: a.kind == ^@personal), :count) } end + + # The agents of the rows in pages of the directory size. A page reads its + # listing texts in one query, and the next page is read only when bad rows + # left the page short. + defp cards(rows) do + rows + |> Stream.chunk_every(@max_agents) + |> Stream.flat_map(fn page -> + ids = Enum.map(page, fn {id, _endpoint, _handle, _online} -> id end) + texts = Map.new(Repo.all(from l in Listing, where: l.id in ^ids, select: {l.id, l.listing})) + + Enum.flat_map(page, fn {id, endpoint, handle, online} -> + with text when is_binary(text) <- texts[id], + {:ok, card} <- Listings.card(text) do + [{endpoint, Map.merge(card, %{"handle" => handle, "online" => online})}] + else + _ -> [] + end + end) + end) + end end diff --git a/server/lib/aether_hub/directory_cache.ex b/server/lib/aether_hub/directory_cache.ex new file mode 100644 index 0000000..69e7239 --- /dev/null +++ b/server/lib/aether_hub/directory_cache.ex @@ -0,0 +1,202 @@ +defmodule AetherHub.DirectoryCache do + @moduledoc """ + Keeps the built directory for 15 seconds, and builds it once at a time. + + A read inside the 15 seconds takes the value from an ETS table and sends + no message. The first read after that asks this process to build a new + value. The other readers wait in its mailbox; each one finds the new value + when its turn comes, so a crowd of readers makes one build, not one each. + + A build that fails starts a pause of 2 seconds (`:retry`). In the pause no + reader asks for a build, and a reader that was already waiting does not + start one either: with an old value they all get it, and without one they + fail at once with `AetherHub.DirectoryCache.Unavailable`, instead of + queueing a build each behind a database that does not answer. The first + reader that fails gets the error of the build itself. A build that works + ends the pause. + + `get/1` returns the value and `fetch/1` the value with its age in + milliseconds, which the route sends as the `age` header. A value that was + served after a failed build can be older than the time to live. + + `get/1` and `fetch/1` raise `Unavailable` when this process is not running + (the table is gone while the supervisor restarts it), or when it does not + answer in 30 seconds and there is no old value. + + The time to live is `config :aether_hub, :directory_cache_ms`, 15 seconds + when it is not set. At `0` there is no cache: the caller builds the value + itself, which is what the tests do, because they set the clock of their + own process. + + `start_link/1` also takes `:name`, `:build` (a function with no argument), + `:ttl` (milliseconds, or a function that returns them), `:retry` + (milliseconds) and `:now` (a function that returns milliseconds), for a + second cache with its own table. + """ + use GenServer + + defmodule Unavailable do + @moduledoc "The directory cannot be served now: the route answers 503." + defexception message: "the directory cache is not available" + end + + @default_ttl :timer.seconds(AetherHub.Protocol.directory_cache_seconds()) + @default_retry :timer.seconds(2) + @call_timeout :timer.seconds(30) + + def start_link(opts \\ []) do + GenServer.start_link(__MODULE__, opts, name: Keyword.get(opts, :name, __MODULE__)) + end + + @doc "The directory, at most the time to live old (see the module)." + def get(server \\ __MODULE__) do + {value, _age} = fetch(server) + value + end + + @doc "The directory and its age in milliseconds." + def fetch(server \\ __MODULE__) do + [{:config, build, ttl, now, _retry}] = lookup(server, :config) + + ttl = ttl(ttl) + + if ttl <= 0 do + {build.(), 0} + else + case serve(server, ttl, now) do + {:ok, served} -> + served + + :unavailable -> + raise Unavailable, message: "the directory is not built and a build failed" + + :build -> + server |> refresh() |> unwrap(server, now) + end + end + end + + @doc "Forgets the value and the pause: the next read builds a new one." + def clear(server \\ __MODULE__), do: GenServer.call(server, :clear) + + # What a read does without a build: the fresh value, the old value while a + # failed build pauses the next one, nothing to serve in that pause, or a + # build. Used by the readers, and by the process for the readers that + # waited in its mailbox. + defp serve(server, ttl, now) do + t = now.() + value = value(server) + + case value do + {built_at, value} when t - built_at < ttl -> + {:ok, {value, t - built_at}} + + {built_at, value} -> + if paused?(server, t), do: {:ok, {value, t - built_at}}, else: :build + + nil -> + if paused?(server, t), do: :unavailable, else: :build + end + end + + defp value(server) do + case lookup(server, :value) do + [{:value, built_at, value}] -> {built_at, value} + [] -> nil + end + end + + defp paused?(server, t) do + [{:config, _build, _ttl, _now, retry}] = lookup(server, :config) + + case lookup(server, :failed_at) do + [{:failed_at, failed_at}] -> t - failed_at < retry + [] -> false + end + end + + defp refresh(server) do + GenServer.call(server, :refresh, @call_timeout) + catch + # Stopped, restarting, or a build that takes longer than the timeout. + :exit, _ -> :down + end + + defp unwrap({:ok, value, age}, _server, _now), do: {value, age} + defp unwrap(:unavailable, _server, _now), do: raise(Unavailable) + + defp unwrap(failed, server, now) do + # The old value is better than an error page. + case value(server) do + {built_at, value} -> + {value, now.() - built_at} + + nil -> + case failed do + {:error, kind, reason, stacktrace} -> :erlang.raise(kind, reason, stacktrace) + :down -> raise Unavailable, message: "the directory cache did not answer" + end + end + end + + # The table is gone while the process restarts. + defp lookup(server, key) do + :ets.lookup(server, key) + rescue + ArgumentError -> + reraise Unavailable, [message: "the directory cache is not running"], __STACKTRACE__ + end + + defp ttl(fun) when is_function(fun, 0), do: fun.() + defp ttl(ms) when is_integer(ms), do: ms + + @impl true + def init(opts) do + server = Keyword.get(opts, :name, __MODULE__) + build = Keyword.get(opts, :build, &AetherHub.Directory.snapshot/0) + now = Keyword.get(opts, :now, fn -> System.monotonic_time(:millisecond) end) + retry = Keyword.get(opts, :retry, @default_retry) + + ttl = + Keyword.get(opts, :ttl, fn -> + Application.get_env(:aether_hub, :directory_cache_ms, @default_ttl) + end) + + :ets.new(server, [:named_table, :protected, :set, read_concurrency: true]) + :ets.insert(server, {:config, build, ttl, now, retry}) + {:ok, server} + end + + @impl true + def handle_call(:refresh, _from, server) do + [{:config, build, ttl, now, _retry}] = :ets.lookup(server, :config) + + # A reader that waited behind a build finds its value here, or the pause + # that the failure of that build started. + case serve(server, ttl(ttl), now) do + {:ok, {value, age}} -> + {:reply, {:ok, value, age}, server} + + :unavailable -> + {:reply, :unavailable, server} + + :build -> + try do + value = build.() + :ets.insert(server, {:value, now.(), value}) + :ets.delete(server, :failed_at) + {:reply, {:ok, value, 0}, server} + catch + kind, reason -> + :ets.insert(server, {:failed_at, now.()}) + {:reply, {:error, kind, reason, __STACKTRACE__}, server} + end + end + end + + def handle_call(:clear, _from, server) do + :ets.delete(server, :value) + :ets.delete(server, :failed_at) + {:reply, :ok, server} + end +end diff --git a/server/lib/aether_hub/invites.ex b/server/lib/aether_hub/invites.ex index e82f3f4..0e871ab 100644 --- a/server/lib/aether_hub/invites.ex +++ b/server/lib/aether_hub/invites.ex @@ -24,10 +24,14 @@ defmodule AetherHub.Invites do Notify, Params, Protocol, + ReadRepo, Repo, Versions } + # Rows that one sweep transaction deletes. 500 rows and up to 1,000 + # endpoints stay far under the variable limit of SQLite (32,766). + @sweep_chunk 500 @ttl Protocol.limit(:invite_seconds) @days Protocol.limit(:access_days) @bundle_prefix Protocol.limit(:invite_prefix) @@ -285,8 +289,10 @@ defmodule AetherHub.Invites do end end + # A pure read: one deferred transaction on the read pool, so the rows and + # the version come from one committed state and the read takes no write lock. defp snapshot(endpoint) do - Repo.atomic(fn -> + ReadRepo.snapshot(fn -> invites = from(i in open(), join: s in Account, @@ -298,7 +304,7 @@ defmodule AetherHub.Invites do order_by: [asc: i.created_at, asc: i.id], select: {i, s, r} ) - |> Repo.all() + |> ReadRepo.all() |> limit_requests(endpoint) |> Enum.map(fn {i, from, to} -> json(i, Account.full_name(from), Account.full_name(to), endpoint) @@ -356,13 +362,40 @@ defmodule AetherHub.Invites do :ok end - @doc "Deletes every expired row and wakes both sides of each." - def delete_expired do - Versions.commit(fn -> - expired = Repo.all(from i in Invite, where: i.created_at <= ^cutoff()) - Repo.delete_all(from i in Invite, where: i.id in ^Enum.map(expired, & &1.id)) - {:ok, Enum.flat_map(expired, &[&1.sender_endpoint, &1.receiver_endpoint])} - end) + @doc """ + Deletes every expired row and wakes both sides of each. It deletes at most + `chunk` rows in one transaction, and bumps the versions of that chunk's + endpoints in the same transaction: a large backlog neither exceeds the + variable limit of SQLite nor holds the writer for long. `:ok`, or the + `{:error, reason}` of the chunk that failed. + """ + def delete_expired(chunk \\ @sweep_chunk) when is_integer(chunk) and chunk > 0 do + delete_expired_chunks(cutoff(), chunk) + end + + defp delete_expired_chunks(cutoff, chunk) do + result = + Versions.commit(fn -> + rows = + Repo.all( + from i in Invite, + where: i.created_at <= ^cutoff, + limit: ^chunk, + select: {i.id, i.sender_endpoint, i.receiver_endpoint} + ) + + ids = for {id, _sender, _receiver} <- rows, do: id + Repo.delete_all(from i in Invite, where: i.id in ^ids) + + touched = Enum.flat_map(rows, fn {_id, sender, receiver} -> [sender, receiver] end) + {length(rows), Enum.uniq(touched)} + end) + + case result do + {:ok, ^chunk} -> delete_expired_chunks(cutoff, chunk) + {:ok, _fewer} -> :ok + {:error, _} = error -> error + end end ## Helpers diff --git a/server/lib/aether_hub/listings.ex b/server/lib/aether_hub/listings.ex index 49f00e1..752a723 100644 --- a/server/lib/aether_hub/listings.ex +++ b/server/lib/aether_hub/listings.ex @@ -264,7 +264,9 @@ defmodule AetherHub.Listings do [match, Clock.now(), limit] ) - contacts = Contacts.known(asker, Enum.map(rows, &hd/1)) + endpoints = Enum.map(rows, &hd/1) + contacts = Contacts.known(asker, endpoints) + owners = OwnerLinks.active_owners(endpoints) agents = rows @@ -276,7 +278,7 @@ defmodule AetherHub.Listings do expires_at: expires_at } - row(listing, Names.format(name, number), contacts) + row(listing, Names.format(name, number), contacts, owners[endpoint]) end) |> Enum.sort_by(&(not &1["online"])) @@ -300,11 +302,13 @@ defmodule AetherHub.Listings do {:error, :not_found} {listing, account} -> - {:ok, row(listing, Account.full_name(account), Contacts.known(asker, [listing.endpoint]))} + contacts = Contacts.known(asker, [listing.endpoint]) + owner = OwnerLinks.active_owner(listing.endpoint) + {:ok, row(listing, Account.full_name(account), contacts, owner)} end end - defp row(%Listing{endpoint: endpoint} = listing, handle, contacts) do + defp row(%Listing{endpoint: endpoint} = listing, handle, contacts, owner) do contact = MapSet.member?(contacts, endpoint) row = %{ @@ -316,7 +320,7 @@ defmodule AetherHub.Listings do "contact" => contact, # The full name of the owner only: never the owner's presence or # endpoint. - "owner" => OwnerLinks.active_owner(endpoint) + "owner" => owner } if contact, do: Map.put(row, "endpoint", endpoint), else: row diff --git a/server/lib/aether_hub/owner_links.ex b/server/lib/aether_hub/owner_links.ex index bdce288..6176d5d 100644 --- a/server/lib/aether_hub/owner_links.ex +++ b/server/lib/aether_hub/owner_links.ex @@ -151,19 +151,29 @@ defmodule AetherHub.OwnerLinks do end @doc "The full name of the active owner of the service agent `service`, or `nil`." - def active_owner(service) do + def active_owner(service), do: Map.get(active_owners([service]), service) + + @doc """ + The full names of the active owners of the service agents in `services`, + as a map from the service endpoint, in one query. A service without an + active owner is not a key. + """ + def active_owners([]), do: %{} + + def active_owners(services) when is_list(services) do from(l in live(), join: p in Account, on: p.endpoint == l.personal_endpoint, - where: l.service_endpoint == ^service and not is_nil(l.confirm_signature), - select: p, - limit: 1 + where: l.service_endpoint in ^services and not is_nil(l.confirm_signature), + order_by: [asc: l.created_at, asc: l.id], + select: {l.service_endpoint, p.name, p.number} ) - |> Repo.one() - |> case do - nil -> nil - personal -> Account.full_name(personal) - end + |> Repo.all() + # A service has at most one active owner; the oldest link wins if a bad + # row ever gives it two. + |> Enum.reduce(%{}, fn {service, name, number}, owners -> + Map.put_new(owners, service, Names.format(name, number)) + end) end @doc "Removes the expired links, and the claims that waited too long." diff --git a/server/lib/aether_hub/protocol.ex b/server/lib/aether_hub/protocol.ex index d396110..47a1f1d 100644 --- a/server/lib/aether_hub/protocol.ex +++ b/server/lib/aether_hub/protocol.ex @@ -23,7 +23,8 @@ defmodule AetherHub.Protocol do limit: 409, too_large: 413, upgrade_required: 426, - rate_limited: 429 + rate_limited: 429, + unavailable: 503 } @patterns %{ endpoint: "^[0-9a-f]{64}$", @@ -94,6 +95,9 @@ defmodule AetherHub.Protocol do def header(name), do: Map.fetch!(@headers, name) def errors, do: @errors def status(code), do: Map.fetch!(@errors, code) + + @doc "How long a reader may keep `/directory.json`: the route's `cacheSeconds`." + def directory_cache_seconds, do: 15 def kinds, do: @kinds def default_kind, do: @default_kind def kind(name), do: Map.fetch!(@kind, name) diff --git a/server/lib/aether_hub/read_repo.ex b/server/lib/aether_hub/read_repo.ex new file mode 100644 index 0000000..0990ab3 --- /dev/null +++ b/server/lib/aether_hub/read_repo.ex @@ -0,0 +1,26 @@ +defmodule AetherHub.ReadRepo do + @moduledoc """ + A read-only pool on the same SQLite file as `AetherHub.Repo`. In WAL mode, + readers do not block the writer or each other, so reads run in parallel + while `AetherHub.Repo` keeps its one connection for writes. + + Use it only for a read that decides nothing about a write: a read that a + write depends on stays on `AetherHub.Repo`, in the transaction of the + write. A read here sees what was committed when its transaction started, + so a read after `AetherHub.Repo` returned from a commit sees that commit. + + The repo does not run migrations and is not in `:ecto_repos`. It starts + after `Ecto.Migrator`, because a read-only connection cannot create the + file. + """ + use Ecto.Repo, + otp_app: :aether_hub, + adapter: Ecto.Adapters.SQLite3, + read_only: true + + @doc """ + Runs `fun` in one deferred read transaction, so every query in it sees + the same committed state: `{:ok, value}`. + """ + def snapshot(fun), do: transact(fn -> {:ok, fun.()} end) +end diff --git a/server/lib/aether_hub/router.ex b/server/lib/aether_hub/router.ex index 0cee07b..1af73d0 100644 --- a/server/lib/aether_hub/router.ex +++ b/server/lib/aether_hub/router.ex @@ -53,9 +53,24 @@ defmodule AetherHub.Router do get "/directory.json" do case RateLimit.hit(:directory_ip, conn.assigns.client_ip) do :ok -> - conn - |> put_resp_header("cache-control", "public, max-age=15") - |> reply({:ok, Directory.snapshot()}) + case Directory.cached() do + # `age` makes `max-age` honest: a view that is 10 seconds old is + # fresh for 5 more, not for 15. + {:ok, view, age} -> + conn + |> put_resp_header( + "cache-control", + "public, max-age=#{Protocol.directory_cache_seconds()}" + ) + |> put_resp_header("age", Integer.to_string(age)) + |> reply({:ok, view}) + + {:error, :unavailable} -> + conn + |> put_resp_header("cache-control", "no-store") + |> put_resp_header("retry-after", "2") + |> reply({:error, :unavailable}) + end :rate_limited -> reply(conn, {:error, :rate_limited}) @@ -213,7 +228,7 @@ defmodule AetherHub.Router do case RateLimit.hit(:request, endpoint) do :ok -> Presence.seen(endpoint) - assign(conn, :account, Accounts.get(endpoint)) + assign(conn, :account, Accounts.fetch(endpoint)) :rate_limited -> conn |> Reply.error(:rate_limited) |> halt() diff --git a/server/lib/aether_hub/versions.ex b/server/lib/aether_hub/versions.ex index 9efd98f..e2b23fe 100644 --- a/server/lib/aether_hub/versions.ex +++ b/server/lib/aether_hub/versions.ex @@ -8,10 +8,18 @@ defmodule AetherHub.Versions do import Ecto.Query - alias AetherHub.{Account, Notify, Repo} + alias AetherHub.{Account, Notify, ReadRepo, Repo} + # Endpoints in one `IN` list. SQLite refuses a statement with more than + # 32,766 variables (999 before 3.32), so a bump goes in bounded chunks. + @bump_chunk 500 + + @doc """ + The version of `endpoint`, from the read pool. Inside a write transaction, + read it with `Repo` instead. + """ def current(endpoint), - do: Repo.one(from a in Account, where: a.endpoint == ^endpoint, select: a.version) + do: ReadRepo.one(from a in Account, where: a.endpoint == ^endpoint, select: a.version) @doc """ Runs `fun` in a transaction. `fun` returns `{value, touched}`: the @@ -35,13 +43,12 @@ defmodule AetherHub.Versions do end end - defp bump([]), do: :ok - defp bump(endpoints) do - Repo.update_all(from(a in Account, where: a.endpoint in ^Enum.uniq(endpoints)), - inc: [version: 1] - ) - - :ok + endpoints + |> Enum.uniq() + |> Enum.chunk_every(@bump_chunk) + |> Enum.each(fn chunk -> + Repo.update_all(from(a in Account, where: a.endpoint in ^chunk), inc: [version: 1]) + end) end end diff --git a/server/test/account_cache_test.exs b/server/test/account_cache_test.exs new file mode 100644 index 0000000..23067ec --- /dev/null +++ b/server/test/account_cache_test.exs @@ -0,0 +1,263 @@ +defmodule AetherHub.AccountCacheTest do + @moduledoc """ + A signed request reads its account from the cache, so every write to an + account must end the copy that the cache holds: a rename, a change of the + search setting, a deletion and a claim. A request after the write, from + the same key, never sees the account as it was. + """ + use ExUnit.Case, async: true + + import Ecto.Query + import AetherHub.TestClient + + alias AetherHub.{Account, AccountCache, Accounts, Clock, Repo} + + defp account(node), do: json(request(node, "GET", "/v1/account")) + + defp cached?(node), do: :ets.lookup(:aether_hub_accounts, node.endpoint) != [] + + defp queries(fun) do + test = self() + id = {__MODULE__, make_ref()} + + :telemetry.attach( + id, + [:aether_hub, :repo, :query], + fn _event, _measure, _meta, _config -> if self() == test, do: send(test, {:query, id}) end, + nil + ) + + try do + fun.() + count_queries(id, 0) + after + :telemetry.detach(id) + end + end + + defp count_queries(id, n) do + receive do + {:query, ^id} -> count_queries(id, n + 1) + after + 0 -> n + end + end + + test "a signed request loads its account once, and not again" do + node = claimed_node() + assert account(node)["handle"] == node.handle + assert cached?(node) + + assert queries(fn -> assert account(node)["handle"] == node.handle end) == 0 + end + + test "the cache holds no version, so nobody reads a counter that it cannot keep" do + node = claimed_node() + account(node) + + assert [{_, %Account{version: nil}, _loaded_at}] = + :ets.lookup(:aether_hub_accounts, node.endpoint) + + assert Repo.get!(Account, node.endpoint).version > 0 + end + + test "a key without an account is not kept" do + node = new_node() + + assert request(node, "GET", "/v1/account").status == 404 + refute cached?(node) + end + + test "a first claim shows at once" do + node = new_node() + assert request(node, "GET", "/v1/account").status == 404 + + name = unique_name() + assert request(node, "PUT", "/v1/account", %{"name" => name}).status == 200 + assert account(node)["name"] == name + end + + test "a rename shows at once" do + node = claimed_node() + assert account(node)["name"] == node.name + assert cached?(node) + + name = unique_name() + assert request(node, "PUT", "/v1/account", %{"name" => name}).status == 200 + refute cached?(node) + assert account(node)["name"] == name + end + + test "a change of the search setting shows at once" do + node = claimed_node() + assert account(node)["searchable"] == false + + assert request(node, "PUT", "/v1/account", %{"searchable" => true}).status == 200 + assert account(node)["searchable"] == true + + assert request(node, "PUT", "/v1/account", %{"searchable" => false}).status == 200 + assert account(node)["searchable"] == false + end + + test "a refused change keeps the account as it was" do + node = claimed_node() + assert account(node)["kind"] == "personal" + + assert request(node, "PUT", "/v1/account", %{"kind" => "service"}).status == 400 + assert account(node)["kind"] == "personal" + assert account(node)["name"] == node.name + end + + test "a deleted account cannot act" do + node = claimed_node() + assert account(node)["handle"] == node.handle + assert cached?(node) + + assert request(node, "DELETE", "/v1/account").status == 204 + refute cached?(node) + + assert request(node, "GET", "/v1/account").status == 404 + assert request(node, "GET", "/v1/contacts").status == 403 + assert request(node, "GET", "/v1/blocks").status == 403 + + assert request(node, "POST", "/v1/invites", %{"to" => new_node().endpoint, "days" => 1}).status == + 403 + end + + test "a key that deleted its account claims a new name, and it shows" do + node = claimed_node() + account(node) + assert request(node, "DELETE", "/v1/account").status == 204 + assert request(node, "GET", "/v1/account").status == 404 + + name = unique_name() + assert request(node, "PUT", "/v1/account", %{"name" => name}).status == 200 + assert account(node)["name"] == name + end + + test "a service agent that renames loses its listing, and the cache has the new name" do + node = claimed_node("service") + put = put_listing(node, listing(node)) + assert put.status == 200 + assert account(node)["handle"] == node.handle + + name = unique_name() + assert request(node, "PUT", "/v1/account", %{"name" => name}).status == 200 + assert account(node)["name"] == name + assert request(node, "GET", "/v1/listing").status == 404 + + # A listing needs the new name: the old one is refused. + assert put_listing(node, listing(node)).status == 400 + end + + test "a reader never keeps an account that a write ended while it loaded" do + node = claimed_node() + endpoint = node.endpoint + me = self() + + readers = + for _ <- 1..4 do + spawn_link(fn -> + loop = fn loop -> + receive do + :stop -> send(me, {:done, self()}) + after + 0 -> + AccountCache.fetch(endpoint) + loop.(loop) + end + end + + loop.(loop) + end) + end + + for i <- 1..40 do + name = "w#{i}x#{unique_name()}" + account = Accounts.get(endpoint) + assert {:ok, _} = Accounts.put(endpoint, account, %{"name" => name}) + + # The write returned: the cache never answers with the old name, and + # the table never holds a copy of it, not even for a moment. + assert AccountCache.fetch(endpoint).name == name + + for _ <- 1..50 do + case :ets.lookup(:aether_hub_accounts, endpoint) do + [{_, %Account{name: held}, _loaded_at}] -> assert held == name + _ -> :ok + end + end + end + + for reader <- readers, do: send(reader, :stop) + for reader <- readers, do: assert_receive({:done, ^reader}, 1_000) + + assert AccountCache.fetch(endpoint) == %{Repo.get!(Account, endpoint) | version: nil} + end + + describe "the time to live" do + # A write that the hub does not see: no `invalidate/1`. + defp write_outside(node, changes) do + from(a in Account, where: a.endpoint == ^node.endpoint) + |> Repo.update_all(set: changes) + end + + setup do + on_exit(fn -> Clock.set(nil) end) + end + + test "a copy ends after 60 seconds, and a write from outside shows then" do + node = claimed_node() + start = Clock.now() + Clock.set(start) + + assert AccountCache.fetch(node.endpoint).searchable == false + write_outside(node, searchable: true) + + Clock.set(start + 59) + assert AccountCache.fetch(node.endpoint).searchable == false + + Clock.set(start + 60) + assert AccountCache.fetch(node.endpoint).searchable == true + + # The new copy lives its own 60 seconds, without a read of the database. + Clock.set(start + 61) + assert queries(fn -> assert AccountCache.fetch(node.endpoint).searchable == true end) == 0 + end + + test "a copy from a clock that is ahead is not trusted by a clock that is behind" do + node = claimed_node() + start = Clock.now() + + Clock.set(start + 1_000) + assert AccountCache.fetch(node.endpoint).searchable == false + write_outside(node, searchable: true) + + Clock.set(start) + assert AccountCache.fetch(node.endpoint).searchable == true + end + end + + describe "the mark of a reader" do + test "a reader that finds the mark of another one reads, and stores nothing" do + node = claimed_node() + mark = {make_ref(), System.monotonic_time(:second)} + :ets.insert(:aether_hub_accounts, {node.endpoint, :loading, mark}) + + assert AccountCache.fetch(node.endpoint).name == node.name + assert :ets.lookup(:aether_hub_accounts, node.endpoint) == [{node.endpoint, :loading, mark}] + + AccountCache.invalidate(node.endpoint) + end + + test "a mark that a killed reader left is taken over" do + node = claimed_node() + mark = {make_ref(), System.monotonic_time(:second) - 11} + :ets.insert(:aether_hub_accounts, {node.endpoint, :loading, mark}) + + assert AccountCache.fetch(node.endpoint).name == node.name + assert cached?(node) + assert [{_, %Account{}, _}] = :ets.lookup(:aether_hub_accounts, node.endpoint) + end + end +end diff --git a/server/test/agent_search_batch_test.exs b/server/test/agent_search_batch_test.exs new file mode 100644 index 0000000..c0631ad --- /dev/null +++ b/server/test/agent_search_batch_test.exs @@ -0,0 +1,180 @@ +defmodule AetherHub.AgentSearchBatchTest do + @moduledoc """ + The search reads the owners of all its results in one query. Its results, + and their order, are the ones that the search had with one query for the + owner of each result. + """ + use ExUnit.Case, async: true + + import AetherHub.TestClient + + alias AetherHub.{Account, Clock, Contacts, Listings, Names, OwnerLinks, Presence, Repo, Seed} + + # The search as it was: the same query, and `active_owner/1` for each row. + defp reference(%Account{endpoint: asker}, words, limit) do + match = Enum.map_join(words, " ", &(~s(") <> &1 <> ~s("*))) + + %{rows: rows} = + Repo.query!( + """ + SELECT l.endpoint, l.listing, l.signature, l.expires_at, a.name, a.number + FROM listing_search + JOIN listings l ON l.id = listing_search.rowid + JOIN accounts a ON a.endpoint = l.endpoint + WHERE listing_search MATCH ?1 AND l.expires_at > ?2 + ORDER BY bm25(listing_search), l.updated_at DESC + LIMIT ?3 + """, + [match, Clock.now(), limit] + ) + + contacts = Contacts.known(asker, Enum.map(rows, &hd/1)) + + agents = + rows + |> Enum.map(fn [endpoint, text, signature, expires_at, name, number] -> + contact = MapSet.member?(contacts, endpoint) + + row = %{ + "handle" => Names.format(name, number), + "listing" => text, + "signature" => signature, + "expiresAt" => expires_at, + "online" => Presence.online?(endpoint), + "contact" => contact, + "owner" => OwnerLinks.active_owner(endpoint) + } + + if contact, do: Map.put(row, "endpoint", endpoint), else: row + end) + |> Enum.sort_by(&(not &1["online"])) + + {:ok, %{"agents" => agents}} + end + + defp queries(fun) do + test = self() + id = {__MODULE__, make_ref()} + + :telemetry.attach( + id, + [:aether_hub, :repo, :query], + fn _event, _measure, _meta, _config -> if self() == test, do: send(test, {:query, id}) end, + nil + ) + + try do + result = fun.() + {result, count_queries(id, 0)} + after + :telemetry.detach(id) + end + end + + defp count_queries(id, n) do + receive do + {:query, ^id} -> count_queries(id, n + 1) + after + 0 -> n + end + end + + # Listings that all hold `word`, some more often than others so that the + # ranks differ, and some with the same rank and the same update time. + setup do + word = unique_name() + now = Clock.now() + asker = Seed.personal() + + agents = + for i <- 1..30 do + repeats = String.duplicate(word <> " ", rem(i, 4) + 1) + + Seed.service( + description: "#{repeats}agent #{i}", + updated_at: now - rem(i, 3), + online: rem(i, 5) == 0, + owner: Enum.at([nil, :active, :claim, :expired], rem(i, 4)) + ) + end + + for agent <- Enum.take_every(agents, 6), do: Seed.contact(asker, agent.account) + + %{word: word, asker: asker, agents: agents} + end + + test "the results and their order are the ones of the search before", %{ + word: word, + asker: asker + } do + for limit <- [1, 3, 7, 10, 20] do + assert Listings.search(asker, [word], limit) == reference(asker, [word], limit) + end + + assert {:ok, %{"agents" => agents}} = Listings.search(asker, [word], 20) + assert length(agents) == 20 + end + + test "more than one word and a prefix give the same results", %{word: word, asker: asker} do + prefix = String.slice(word, 0, 5) + + for words <- [[word, "agent"], [prefix], ["agent", word, "answers"]], limit <- [5, 20] do + assert Listings.search(asker, words, limit) == reference(asker, words, limit) + end + end + + test "the online agents come first inside the page", %{word: word, asker: asker} do + {:ok, %{"agents" => agents}} = Listings.search(asker, [word], 20) + online = Enum.map(agents, & &1["online"]) + + assert Enum.any?(online) and not Enum.all?(online) + assert online == Enum.sort_by(online, &(not &1)) + end + + test "each result shows its own active owner and no other", %{ + word: word, + asker: asker, + agents: agents + } do + {:ok, %{"agents" => found}} = Listings.search(asker, [word], 20) + expected = Map.new(agents, &{&1.handle, &1.owner}) + + # One listing in four has an active link, and the others have a claim, + # an ended link or none: only the active link shows an owner. + assert Enum.count(found, & &1["owner"]) > 0 + assert Enum.count(found, &(&1["owner"] == nil)) > 0 + assert Enum.all?(found, &(&1["owner"] == expected[&1["handle"]])) + end + + test "an expired listing is not found", %{word: word, asker: asker} do + ended = Seed.service(description: word, expires_at: Clock.now() - 1) + {:ok, %{"agents" => agents}} = Listings.search(asker, [word], 20) + + refute Enum.any?(agents, &(&1["handle"] == ended.handle)) + end + + test "a search takes three queries however many results it has", %{word: word, asker: asker} do + {{:ok, %{"agents" => agents}}, count} = queries(fn -> Listings.search(asker, [word], 20) end) + + assert length(agents) == 20 + # The matches, the contacts, the owners. + assert count == 3 + end + + test "a search with no result takes the same queries", %{asker: asker} do + {{:ok, %{"agents" => agents}}, count} = + queries(fn -> Listings.search(asker, [unique_name()], 20) end) + + assert agents == [] + assert count <= 3 + end + + test "the route answers with the same results", %{word: word} do + node = claimed_node() + conn = request(node, "GET", "/v1/agents?q=#{word}&limit=20") + assert conn.status == 200 + + account = Repo.get!(Account, node.endpoint) + assert json(conn) == JSON.decode!(JSON.encode!(elem(reference(account, [word], 20), 1))) + end +end diff --git a/server/test/directory_cache_test.exs b/server/test/directory_cache_test.exs new file mode 100644 index 0000000..27c3123 --- /dev/null +++ b/server/test/directory_cache_test.exs @@ -0,0 +1,254 @@ +defmodule AetherHub.DirectoryCacheTest do + @moduledoc """ + The directory cache serves a value for its time to live, and builds a new + one once, however many readers ask for it at the same moment. Each test + starts its own cache with a build that it counts and a clock that it sets. + """ + use ExUnit.Case, async: true + + alias AetherHub.DirectoryCache + + @ttl 15_000 + @retry 2_000 + + # A cache whose build counts its calls, with a clock in milliseconds. + defp start_cache(opts \\ []) do + name = :"directory_cache_#{System.unique_integer([:positive])}" + {:ok, counter} = Agent.start_link(fn -> 0 end) + {:ok, clock} = Agent.start_link(fn -> 0 end) + + build = + Keyword.get(opts, :build, fn -> + Process.sleep(Keyword.get(opts, :build_ms, 0)) + n = Agent.get_and_update(counter, &{&1 + 1, &1 + 1}) + %{"build" => n} + end) + + start_supervised!(%{ + id: name, + start: + {DirectoryCache, :start_link, + [ + [ + name: name, + build: build, + ttl: Keyword.get(opts, :ttl, @ttl), + retry: @retry, + now: fn -> Agent.get(clock, & &1) end + ] + ]} + }) + + %{ + name: name, + builds: fn -> Agent.get(counter, & &1) end, + advance: fn ms -> Agent.update(clock, &(&1 + ms)) end + } + end + + test "serves the same value for 15 seconds, then builds a new one" do + cache = start_cache() + + assert DirectoryCache.get(cache.name) == %{"build" => 1} + cache.advance.(@ttl - 1) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert cache.builds.() == 1 + + cache.advance.(1) + assert DirectoryCache.get(cache.name) == %{"build" => 2} + assert DirectoryCache.get(cache.name) == %{"build" => 2} + assert cache.builds.() == 2 + end + + test "readers at the same moment make one build" do + cache = start_cache(build_ms: 100) + + values = + 1..50 + |> Enum.map(fn _ -> Task.async(fn -> DirectoryCache.get(cache.name) end) end) + |> Task.await_many() + + assert Enum.uniq(values) == [%{"build" => 1}] + assert cache.builds.() == 1 + end + + test "readers after the time to live make one build" do + cache = start_cache(build_ms: 100) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + cache.advance.(@ttl) + + values = + 1..50 + |> Enum.map(fn _ -> Task.async(fn -> DirectoryCache.get(cache.name) end) end) + |> Task.await_many() + + assert Enum.uniq(values) == [%{"build" => 2}] + assert cache.builds.() == 2 + end + + test "clear makes the next read build a new value" do + cache = start_cache() + assert DirectoryCache.get(cache.name) == %{"build" => 1} + :ok = DirectoryCache.clear(cache.name) + assert DirectoryCache.get(cache.name) == %{"build" => 2} + end + + test "a time to live of 0 builds in the process of the reader, every time" do + cache = start_cache(ttl: 0) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert DirectoryCache.get(cache.name) == %{"build" => 2} + end + + test "a failed build serves the old value, and raises when there is none" do + {:ok, mode} = Agent.start_link(fn -> :fail end) + + cache = + start_cache( + build: fn -> + if Agent.get(mode, & &1) == :fail, do: raise("database is busy"), else: %{"ok" => true} + end + ) + + assert_raise RuntimeError, "database is busy", fn -> DirectoryCache.get(cache.name) end + + # The failure paused the next build for a short time. + Agent.update(mode, fn _ -> :ok end) + cache.advance.(@retry) + assert DirectoryCache.get(cache.name) == %{"ok" => true} + + Agent.update(mode, fn _ -> :fail end) + cache.advance.(@ttl) + assert DirectoryCache.get(cache.name) == %{"ok" => true} + end + + test "fetch tells the age of the value in milliseconds" do + cache = start_cache() + + assert DirectoryCache.fetch(cache.name) == {%{"build" => 1}, 0} + cache.advance.(5_000) + assert DirectoryCache.fetch(cache.name) == {%{"build" => 1}, 5_000} + end + + # A build that counts its attempts, and works or fails as `mode` says. + defp flaky_cache(build_ms \\ 0) do + {:ok, mode} = Agent.start_link(fn -> :ok end) + {:ok, attempts} = Agent.start_link(fn -> 0 end) + + cache = + start_cache( + build: fn -> + Process.sleep(build_ms) + n = Agent.get_and_update(attempts, &{&1 + 1, &1 + 1}) + if Agent.get(mode, & &1) == :fail, do: raise("database is busy"), else: %{"build" => n} + end + ) + + Map.merge(cache, %{ + attempts: fn -> Agent.get(attempts, & &1) end, + mode: fn value -> Agent.update(mode, fn _ -> value end) end + }) + end + + defp readers(cache, count) do + 1..count + |> Enum.map(fn _ -> + Task.async(fn -> + try do + {:ok, DirectoryCache.get(cache.name)} + rescue + error -> {:error, error} + end + end) + end) + |> Task.await_many() + end + + test "after a failed build the old value is served without a new build for a while" do + cache = flaky_cache() + assert DirectoryCache.get(cache.name) == %{"build" => 1} + + cache.mode.(:fail) + cache.advance.(@ttl) + + # The first read after the time to live tries, and fails. + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert cache.attempts.() == 2 + + for _ <- 1..20, do: assert(DirectoryCache.get(cache.name) == %{"build" => 1}) + cache.advance.(@retry - 1) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert cache.attempts.() == 2 + + # The pause ends: one more try, which fails again and pauses again. + cache.advance.(1) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert cache.attempts.() == 3 + assert DirectoryCache.get(cache.name) == %{"build" => 1} + assert cache.attempts.() == 3 + + # A try that works ends the failures. + cache.mode.(:ok) + cache.advance.(@retry) + assert DirectoryCache.get(cache.name) == %{"build" => 4} + assert cache.attempts.() == 4 + assert DirectoryCache.get(cache.name) == %{"build" => 4} + end + + test "without an old value the first read gets the error and the next ones fail at once" do + cache = flaky_cache() + cache.mode.(:fail) + + assert_raise RuntimeError, "database is busy", fn -> DirectoryCache.get(cache.name) end + assert cache.attempts.() == 1 + + for _ <- 1..5 do + assert_raise DirectoryCache.Unavailable, fn -> DirectoryCache.get(cache.name) end + end + + assert cache.attempts.() == 1 + + # After the pause there is one more try, and when it works the cache serves. + cache.mode.(:ok) + cache.advance.(@retry) + assert DirectoryCache.get(cache.name) == %{"build" => 2} + end + + test "readers that wait behind a slow failing build do not build again" do + cache = flaky_cache(100) + assert DirectoryCache.get(cache.name) == %{"build" => 1} + cache.mode.(:fail) + cache.advance.(@ttl) + + results = readers(cache, 50) + + assert Enum.uniq(results) == [{:ok, %{"build" => 1}}] + assert cache.attempts.() == 2 + end + + test "without an old value, readers behind a failing build get one error and the rest fail at once" do + cache = flaky_cache(100) + cache.mode.(:fail) + + results = readers(cache, 50) + + assert [%RuntimeError{message: "database is busy"}] = + for({:error, %RuntimeError{} = error} <- results, do: error) + + assert length(for({:error, %DirectoryCache.Unavailable{}} <- results, do: :unavailable)) == 49 + assert cache.attempts.() == 1 + end + + test "a read while the cache process is down is unavailable, not an ArgumentError" do + cache = start_cache() + assert DirectoryCache.get(cache.name) == %{"build" => 1} + + :ok = stop_supervised(cache.name) + + assert_raise DirectoryCache.Unavailable, fn -> DirectoryCache.get(cache.name) end + assert_raise DirectoryCache.Unavailable, fn -> DirectoryCache.fetch(cache.name) end + + assert_raise DirectoryCache.Unavailable, fn -> + DirectoryCache.get(:no_such_directory_cache) + end + end +end diff --git a/server/test/directory_view_test.exs b/server/test/directory_view_test.exs new file mode 100644 index 0000000..a1244ee --- /dev/null +++ b/server/test/directory_view_test.exs @@ -0,0 +1,235 @@ +defmodule AetherHub.DirectoryViewTest do + @moduledoc """ + The directory is built from a few queries, and the route serves it from + the cache. The first tests compare the view with the one that the hub built + before: one query for the owner of each agent, and every listing decoded. + They run alone, because they read the whole table of listings. + """ + use ExUnit.Case, async: false + + import Ecto.Query + import AetherHub.TestClient + + alias AetherHub.{Account, Clock, Directory, DirectoryCache, Listing, Listings, OwnerLinks} + alias AetherHub.{Presence, Repo, Seed} + + @max_agents AetherHub.Contract.get(["limits", "maxDirectoryAgents"]) + + # The directory as it was before the cache: all the rows, decoded, and the + # owner of each agent on the page by its own query. + defp reference do + rows = + Repo.all( + from l in Listing, + join: a in Account, + on: a.endpoint == l.endpoint, + where: l.expires_at > ^Clock.now(), + order_by: [desc: l.updated_at, asc: l.id], + select: {l.endpoint, l.listing, a} + ) + + agents = + rows + |> Enum.flat_map(fn {endpoint, text, account} -> + case Listings.card(text) do + {:ok, card} -> + [ + {endpoint, + Map.merge(card, %{ + "handle" => Account.full_name(account), + "online" => Presence.online?(endpoint) + })} + ] + + :error -> + [] + end + end) + |> Enum.sort_by(fn {_endpoint, agent} -> not agent["online"] end) + + %{ + "agents" => + agents + |> Enum.take(@max_agents) + |> Enum.map(fn {endpoint, agent} -> + Map.put(agent, "owner", OwnerLinks.active_owner(endpoint)) + end), + "listed" => length(agents), + "online" => Enum.count(agents, fn {_endpoint, agent} -> agent["online"] end), + "people" => Repo.aggregate(from(a in Account, where: a.kind == "personal"), :count) + } + end + + defp queries(fun) do + test = self() + id = {__MODULE__, make_ref()} + + :telemetry.attach( + id, + [:aether_hub, :repo, :query], + fn _event, _measure, _meta, _config -> if self() == test, do: send(test, {:query, id}) end, + nil + ) + + try do + result = fun.() + {result, count_queries(id, 0)} + after + :telemetry.detach(id) + end + end + + defp count_queries(id, n) do + receive do + {:query, ^id} -> count_queries(id, n + 1) + after + 0 -> n + end + end + + setup do + now = Clock.now() + + # More agents than a page, in two ages, so that ties in the update time + # and the online agents' place in the order both matter. + for i <- 1..(@max_agents + 30) do + Seed.service( + description: "Agent number #{i}", + updated_at: now - rem(i, 7), + online: rem(i, 9) == 0, + owner: Enum.at([nil, :active, :claim, :expired], rem(i, 4)) + ) + end + + :ok + end + + test "the view is the one that the hub built before" do + view = Directory.snapshot() + + assert view == reference() + assert length(view["agents"]) == @max_agents + assert view["listed"] >= @max_agents + 30 + end + + test "the online agents come first, then the latest update" do + agents = Directory.snapshot()["agents"] + online = Enum.map(agents, & &1["online"]) + + assert Enum.any?(online) + assert online == Enum.sort_by(online, &(not &1)) + end + + test "an agent shows the full name of an active owner and no other" do + active = Seed.service(owner: :active, updated_at: Clock.now() + 100, online: true) + claim = Seed.service(owner: :claim, updated_at: Clock.now() + 100, online: true) + ended = Seed.service(owner: :expired, updated_at: Clock.now() + 100, online: true) + alone = Seed.service(updated_at: Clock.now() + 100, online: true) + + owners = Map.new(Directory.snapshot()["agents"], &{&1["handle"], &1["owner"]}) + + assert owners[active.handle] == active.owner + assert owners[claim.handle] == nil + assert owners[ended.handle] == nil + assert owners[alone.handle] == nil + end + + test "a listing that does not read is left out and the next agent takes its place" do + before_view = Directory.snapshot() + bad = Seed.service(bad: true, updated_at: Clock.now() + 100, online: true) + # The other tests compare the counts with a view that decodes every row. + on_exit(fn -> Listings.delete(bad.account.endpoint) end) + view = Directory.snapshot() + + refute Enum.any?(view["agents"], &(&1["handle"] == bad.handle)) + assert length(view["agents"]) == @max_agents + # The counts take no decoding: a bad row is a bug the page hides. + assert view["listed"] == before_view["listed"] + 1 + end + + test "an expired listing is not shown or counted" do + before_view = Directory.snapshot() + ended = Seed.service(expires_at: Clock.now() - 1, updated_at: Clock.now() + 100, online: true) + view = Directory.snapshot() + + refute Enum.any?(view["agents"], &(&1["handle"] == ended.handle)) + assert view["listed"] == before_view["listed"] + end + + test "building the view takes a few queries, not one for each agent" do + {_view, count} = queries(&Directory.snapshot/0) + + # The rows, the texts of the page, the owners, the people. + assert count <= 5 + end + + describe "the route" do + setup do + previous = Application.fetch_env!(:aether_hub, :directory_cache_ms) + Application.put_env(:aether_hub, :directory_cache_ms, 15_000) + DirectoryCache.clear() + + on_exit(fn -> + Application.put_env(:aether_hub, :directory_cache_ms, previous) + DirectoryCache.clear() + end) + end + + defp directory, do: json(public_request(:get, "/directory.json")) + + test "serves the cached view, and a new one after the cache is cleared" do + first = directory() + late = Seed.service(updated_at: Clock.now() + 100, online: true) + + assert directory() == first + refute Enum.any?(directory()["agents"], &(&1["handle"] == late.handle)) + + DirectoryCache.clear() + assert Enum.any?(directory()["agents"], &(&1["handle"] == late.handle)) + end + + test "reads the database once for many requests" do + {_, count} = + queries(fn -> for _ <- 1..10, do: public_request(:get, "/directory.json") end) + + # One build of a few queries, and no more for the other nine requests. + assert count <= 5 + end + + test "tells the age of the cached view, so a cache counts the 15 seconds from the build" do + DirectoryCache.clear() + assert Plug.Conn.get_resp_header(public_request(:get, "/directory.json"), "age") == ["0"] + + # A view that is a few seconds old says so; the clock of the cache is + # in milliseconds and cannot be moved, so wait for one whole second. + Process.sleep(1_100) + assert Plug.Conn.get_resp_header(public_request(:get, "/directory.json"), "age") == ["1"] + end + + test "answers 503 when the cache does not answer, and works again after it restarts" do + DirectoryCache.clear() + :ok = Supervisor.terminate_child(AetherHub.Supervisor, AetherHub.DirectoryCache) + on_exit(fn -> Supervisor.restart_child(AetherHub.Supervisor, AetherHub.DirectoryCache) end) + + conn = public_request(:get, "/directory.json") + assert conn.status == 503 + assert json(conn) == %{"error" => "unavailable"} + assert Plug.Conn.get_resp_header(conn, "cache-control") == ["no-store"] + + {:ok, _} = Supervisor.restart_child(AetherHub.Supervisor, AetherHub.DirectoryCache) + assert public_request(:get, "/directory.json").status == 200 + end + + test "keeps its shape and its cache header" do + conn = public_request(:get, "/directory.json") + + assert conn.status == 200 + assert Plug.Conn.get_resp_header(conn, "cache-control") == ["public, max-age=15"] + assert json(conn) |> Map.keys() |> Enum.sort() == AetherHub.Contract.keys("directory") + + for agent <- json(conn)["agents"] do + assert agent |> Map.keys() |> Enum.sort() == AetherHub.Contract.keys("directoryAgent") + end + end + end +end diff --git a/server/test/protocol_test.exs b/server/test/protocol_test.exs index 9dda4d8..77a8bee 100644 --- a/server/test/protocol_test.exs +++ b/server/test/protocol_test.exs @@ -163,6 +163,11 @@ defmodule AetherHub.ProtocolTest do end end + test "the directory's max-age is the contract's cacheSeconds" do + [route] = Enum.filter(Contract.get(["routes"]), &(&1["path"] == "/directory.json")) + assert Protocol.directory_cache_seconds() == route["cacheSeconds"] + end + test "the router has every route of the contract" do opts = AetherHub.Router.init([]) diff --git a/server/test/read_pool_and_sweep_test.exs b/server/test/read_pool_and_sweep_test.exs new file mode 100644 index 0000000..04506c5 --- /dev/null +++ b/server/test/read_pool_and_sweep_test.exs @@ -0,0 +1,168 @@ +defmodule AetherHub.ReadPoolAndSweepTest do + @moduledoc """ + The read pool is read-only and sees each commit of the writer, and the + invite sweep deletes a backlog of any size in bounded transactions. + + The module is not async: a sweep removes the expired rows of every test. + """ + use ExUnit.Case, async: false + + import Ecto.Query + + alias AetherHub.{Account, Clock, Invite, Invites, Protocol, ReadRepo, Repo, Versions} + + @ttl Protocol.limit(:invite_seconds) + # SQLite's limit on the variables of one statement. + @variable_limit 32_766 + + setup do + on_exit(fn -> + Repo.delete_all(from i in Invite, where: like(i.sender_endpoint, "sweeptest-%")) + Repo.delete_all(from a in Account, where: like(a.endpoint, "sweeptest-%")) + end) + end + + defp accounts(count) do + rows = + for i <- 1..count do + %{ + endpoint: "sweeptest-#{i}", + name: "sweeptest#{i}", + number: 1, + kind: "personal", + searchable: false, + created_at: 0, + version: 0 + } + end + + rows |> Enum.chunk_every(500) |> Enum.each(&Repo.insert_all(Account, &1)) + for i <- 1..count, do: "sweeptest-#{i}" + end + + # One invite for each ordered pair of `endpoints` that `pairs?` accepts. + defp insert_invites(endpoints, created_at, pairs? \\ fn _from, _to -> true end) do + rows = + for from <- endpoints, to <- endpoints, from != to, pairs?.(from, to) do + %{ + id: Repo.new_id(), + sender_endpoint: from, + receiver_endpoint: to, + days: 7, + status: "pending", + origin: "invite", + created_at: created_at + } + end + + rows |> Enum.chunk_every(500) |> Enum.each(&Repo.insert_all(Invite, &1)) + length(rows) + end + + defp expired_at, do: Clock.now() - @ttl - 10 + + defp invite_count, + do: Repo.aggregate(from(i in Invite, where: like(i.sender_endpoint, "sweeptest-%")), :count) + + defp version(endpoint), do: Versions.current(endpoint) + + describe "the read pool" do + test "refuses a write" do + # `read_only: true` leaves the write functions out of the repo. + refute function_exported?(ReadRepo, :insert, 1) + refute function_exported?(ReadRepo, :delete_all, 1) + + assert {:error, %Exqlite.Error{message: message}} = + ReadRepo.query("DELETE FROM invites") + + assert message =~ "readonly" + end + + test "sees each commit of the writer, also under load from other writes" do + [endpoint] = accounts(1) + + for expected <- 1..100 do + assert :ok = Versions.commit(fn -> {:ok, [endpoint]} end) + assert version(endpoint) == expected + end + end + + test "a long poll wakes after the commit and reads the new version" do + [endpoint] = accounts(1) + account = Repo.get!(Account, endpoint) + + poll = + Task.async(fn -> + Invites.list(account, %{"after" => "0", "wait" => "20"}) + end) + + # Wait until the poll waits, then change the account. + Enum.reduce_while(1..200, nil, fn _, _ -> + if AetherHub.Notify.waiting?(endpoint), + do: {:halt, nil}, + else: Process.sleep(10) && {:cont, nil} + end) + + assert :ok = Versions.commit(fn -> {:ok, [endpoint]} end) + assert {:ok, %{"version" => 1, "invites" => []}} = Task.await(poll, 5_000) + end + + test "the snapshot reads the rows and the version in one state" do + [a, b] = accounts(2) + insert_invites([a, b], Clock.now()) + account = Repo.get!(Account, a) + + assert {:ok, %{"version" => 0, "invites" => [_, _]}} = Invites.list(account, %{}) + end + end + + describe "the sweep" do + test "deletes in chunks, keeps open rows and bumps each endpoint of the swept rows" do + endpoints = accounts(6) + # 30 ordered pairs: the pairs from the first three accounts are + # expired, the others open. + expired_from = Enum.take(endpoints, 3) + + insert_invites(endpoints, expired_at(), fn from, _to -> from in expired_from end) + open = insert_invites(endpoints, Clock.now(), fn from, _to -> from not in expired_from end) + assert invite_count() == 30 + + before = Map.new(endpoints, &{&1, version(&1)}) + + # A chunk of 4 needs several transactions for 15 rows. + assert :ok = Invites.delete_expired(4) + + assert invite_count() == open + + # Every account is the sender or the receiver of an expired row. + for endpoint <- endpoints, do: assert(version(endpoint) > before[endpoint]) + end + + test "a sweep of nothing changes nothing" do + [endpoint] = accounts(1) + assert :ok = Invites.delete_expired() + assert version(endpoint) == 0 + end + + test "deletes more expired rows than SQLite has variables" do + # 200 accounts make 39,800 ordered pairs. + endpoints = accounts(200) + total = insert_invites(endpoints, expired_at()) + assert total > @variable_limit + assert invite_count() == total + + assert :ok = Invites.delete_expired() + assert invite_count() == 0 + assert version(hd(endpoints)) > 0 + end + + test "a bump of more endpoints than SQLite has variables succeeds" do + [endpoint] = accounts(1) + others = for i <- 1..(@variable_limit + 1000), do: "sweeptest-none-#{i}" + + assert :ok = Versions.commit(fn -> {:ok, [endpoint | others] ++ [endpoint]} end) + # One bump for an endpoint that the list names twice. + assert version(endpoint) == 1 + end + end +end diff --git a/server/test/support/seed.ex b/server/test/support/seed.ex new file mode 100644 index 0000000..0774dfa --- /dev/null +++ b/server/test/support/seed.ex @@ -0,0 +1,106 @@ +defmodule AetherHub.Seed do + @moduledoc """ + Rows for a test that needs many accounts and listings: they go straight + into the database, with no signed request, as the hub would have kept + them. A listing has its search row, and an owner link is kept as it is + after the service confirmed it. + """ + + alias AetherHub.{Account, Clock, Listing, OwnerLink, Presence, Repo} + + @doc "The endpoint of a new key: 64 lowercase hex characters." + def endpoint, do: Base.encode16(:crypto.strong_rand_bytes(32), case: :lower) + + @doc "A personal account. Returns the `%Account{}`." + def personal(name \\ AetherHub.TestClient.unique_name()), do: account(name, "personal") + + defp account(name, kind) do + Repo.insert!(%Account{ + endpoint: endpoint(), + name: name, + number: Enum.random(1..9999), + kind: kind, + created_at: Clock.now(), + version: 1 + }) + end + + @doc """ + A service agent with a listing. Options: + + * `:description`, `:skill`, `:tags` - the text of the listing + * `:updated_at` - when the node sent it (default: now) + * `:expires_at` - default: in 7 days + * `:online` - the agent has a recent request (default: `false`) + * `:owner` - `:active` (confirmed), `:claim` (not confirmed) or + `:expired` (confirmed, then ended): the link to a new personal account + * `:bad` - the listing text does not read + """ + def service(opts \\ []) do + now = Clock.now() + account = account(AetherHub.TestClient.unique_name(), "service") + handle = Account.full_name(account) + description = Keyword.get(opts, :description, "Answers questions.") + skill = Keyword.get(opts, :skill, "General") + tags = Keyword.get(opts, :tags, ["general"]) + + text = + if opts[:bad] do + "not base64url!" + else + %{ + "name" => handle, + "description" => description, + "skills" => [ + %{"id" => "general", "name" => skill, "description" => "Does tasks.", "tags" => tags} + ] + } + |> JSON.encode!() + |> Base.url_encode64(padding: false) + end + + listing = + Repo.insert!(%Listing{ + endpoint: account.endpoint, + listing: text, + signature: "signature", + expires_at: Keyword.get(opts, :expires_at, now + 7 * 86_400), + updated_at: Keyword.get(opts, :updated_at, now) + }) + + Repo.query!( + "INSERT INTO listing_search(rowid, name, description, skills, tags) VALUES (?1, ?2, ?3, ?4, ?5)", + [listing.id, account.name, description, skill <> "\nDoes tasks.", Enum.join(tags, " ")] + ) + + if opts[:online], do: Presence.seen(account.endpoint) + owner = if opts[:owner], do: link(account, handle, opts[:owner], now) + + # `owner` is the owner that the hub shows: only an active link has one. + %{account: account, handle: handle, owner: if(opts[:owner] == :active, do: owner)} + end + + defp link(service, handle, state, now) do + personal = personal() + + Repo.insert!(%OwnerLink{ + id: Repo.new_id(), + service_endpoint: service.endpoint, + personal_endpoint: personal.endpoint, + service_handle: handle, + expires_at: if(state == :expired, do: now - 10, else: now + 86_400), + claim_signature: "claim", + confirm_signature: if(state == :claim, do: nil, else: "confirm"), + created_at: now + }) + + Account.full_name(personal) + end + + @doc "`asker` has `contact` as a contact." + def contact(asker, contact) do + Repo.insert_all(AetherHub.Contact, [ + %{owner_endpoint: asker.endpoint, contact_endpoint: contact.endpoint} + ]) + end +end diff --git a/server/test/test_helper.exs b/server/test/test_helper.exs index b7468ce..53ba062 100644 --- a/server/test/test_helper.exs +++ b/server/test/test_helper.exs @@ -4,4 +4,9 @@ ExUnit.after_suite(fn _ -> for suffix <- ["", "-wal", "-shm"], do: File.rm(database <> suffix) end) +# The scenarios read the directory right after they change it, in a process +# with its own clock: they run without the 15 second cache. Its own test +# turns the cache on. +Application.put_env(:aether_hub, :directory_cache_ms, 0) + ExUnit.start() diff --git a/specs/ConnectedAgent.cfg b/specs/ConnectedAgent.cfg index faa8c88..8d84860 100644 --- a/specs/ConnectedAgent.cfg +++ b/specs/ConnectedAgent.cfg @@ -1,10 +1,12 @@ \* ConnectedAgent: the agent socket. See ConnectedAgent.tla. -\* One task ID that gets two turns, and two connections (the second -\* replaces the first, or attaches after it closed). +\* Two task IDs, so two turns are open on one connection at once. One turn for +\* each task ID and one connection. The replace path and a second turn of a task +\* ID need more room than TLC has in its default memory with two tasks: they +\* are checked by ConnectedAgentRerun (one task ID, two turns, two connections). CONSTANTS - Tasks = {t1} - MaxConns = 2 - MaxTurns = 2 + Tasks = {t1, t2} + MaxConns = 1 + MaxTurns = 1 SPECIFICATION Spec diff --git a/specs/ConnectedAgent.tla b/specs/ConnectedAgent.tla index 31da679..74b6f75 100644 --- a/specs/ConnectedAgent.tla +++ b/specs/ConnectedAgent.tla @@ -18,9 +18,18 @@ (* connection has its own `pending` turns (`Turns`: the open task IDs and *) (* the `closed` flag). A turn is one call of *) (* `start_turn_with_events`; each task has one thread that can run *) -(* MaxTurns turns, one after the other. Turns of different tasks can run *) -(* at the same time, which is more than the scheduler does (it runs one *) -(* execution at a time). *) +(* MaxTurns turns, one after the other. Turns of different tasks run at *) +(* the same time, on one connection: the scheduler runs up to the owner's *) +(* running-task limit at once (at most what the agent said in `max_tasks`, *) +(* see below), and the cfg checks two tasks. Each answer, cancel and close *) +(* names its task, and none touches the turn of another. *) +(* *) +(* `max_tasks`: the first `ready` of a connection can say how many tasks *) +(* the agent takes at once (`Connection.max_tasks`, which *) +(* `ConnectedAgent::capacity` reads under the `connection` mutex; one when *) +(* the `ready` says nothing or no agent is attached). The scheduler reads *) +(* it before it starts a task; `run_turn` itself takes any number of open *) +(* tasks, so no variable of this spec holds it. *) (* *) (* The agent is not trusted to follow the protocol. When `honest` is *) (* FALSE, an agent can answer any task ID that the node ever sent to an *) diff --git a/specs/ConnectedAgentRerun.cfg b/specs/ConnectedAgentRerun.cfg new file mode 100644 index 0000000..c901ee9 --- /dev/null +++ b/specs/ConnectedAgentRerun.cfg @@ -0,0 +1,31 @@ +\* ConnectedAgentRerun: ConnectedAgent with the same task ID turns twice. See ConnectedAgent.tla. +\* One task ID that gets two turns, and two connections (the second +\* replaces the first, or attaches after it closed). +CONSTANTS + Tasks = {t1} + MaxConns = 2 + MaxTurns = 2 + +SPECIFICATION Spec + +INVARIANTS + TypeOK + PendingIsOpenTurn + NoProtocolError + AnswerFromHolder + TurnEndsOnce + NoLostCancel + NoStaleCancel + NoOrphanWait + +PROPERTIES + NoAgentNoTask + EarlyCancelHonored + LateCancelDropped + CancelToldToHolder + AnswerAfterSent + TaskOnlyToAttached + AnswerWhileAttached + TurnEnds + LostAgentFailsTurn + CancelStopsHonestTurn diff --git a/specs/ConnectedAgentRerun.tla b/specs/ConnectedAgentRerun.tla new file mode 100644 index 0000000..560a437 --- /dev/null +++ b/specs/ConnectedAgentRerun.tla @@ -0,0 +1,12 @@ +------------------------- MODULE ConnectedAgentRerun ------------------------- +(***************************************************************************) +(* ConnectedAgent with one task ID that gets two turns, one after the *) +(* other, and two connections. It checks that a cancel, an answer or an *) +(* end of the first turn never reaches the second turn of the same task *) +(* (NoStaleCancel, EarlyCancelHonored, LateCancelDropped). ConnectedAgent *) +(* itself checks two tasks that are open at once, one turn each. The *) +(* constants are in ConnectedAgentRerun.cfg. *) +(***************************************************************************) +EXTENDS ConnectedAgent + +============================================================================= diff --git a/specs/EventPaging.tla b/specs/EventPaging.tla index 8312b49..72a5768 100644 --- a/specs/EventPaging.tla +++ b/specs/EventPaging.tla @@ -264,6 +264,17 @@ OutboxReceive == /\ rep' = None /\ UNCHANGED <> +\* A shed exchange is not an action: the per-peer rate limit of the host +\* answers "node overloaded" with `retryAfterMs`, before the host admits +\* anything or reads the journal. `request_with_polling_on` and `follow` +\* send the frame again with the same cursor for up to +\* `OVERLOAD_RETRY_WINDOW`, with every wait cut to the end of that window +\* and of the poll deadline or attempt window. No state that this model +\* tracks changes (the journal, the cursor, `got`), so it is a stutter step +\* of `Poll`. When the window ends, the caller gets the error, which +\* `CliReceive` and `OutboxReceive` take as an "error" reply. A full queue +\* sends the same message without `retryAfterMs` and is not sent again. + \* The frame or its answer is lost, or the exchange times out. The cli loop \* returns the error and drops what it collected. The outbox keeps the \* cursor in `sent_tasks` (`record_sent_attempt`), and the next attempt diff --git a/specs/ExecutionLease.cfg b/specs/ExecutionLease.cfg index d500ab5..8718742 100644 --- a/specs/ExecutionLease.cfg +++ b/specs/ExecutionLease.cfg @@ -1,15 +1,23 @@ +\* ExecutionLease: up to two executions at once (MaxCap), two tasks, a clock of +\* four ticks. A node restart is not in this run (MaxRestarts = 0): it needs a +\* larger state space than TLC finishes in minutes; ExecutionLeaseSerial checks +\* restarts with one execution at a time, and a restart only resets every worker. SPECIFICATION FairSpec CONSTANTS Tasks = {t1, t2} MaxExec = 3 TTL = 2 - MaxTime = 5 - MaxRestarts = 1 + MaxTime = 4 + MaxRestarts = 0 + MaxCap = 2 INVARIANTS TypeOK LeaseIffActive AtMostOneStart TurnMatchesState NoSpuriousCancel + OneStartAtATime PROPERTIES CancelReachesTurn + RunningWithinCap + CapChangeTouchesNothing diff --git a/specs/ExecutionLease.tla b/specs/ExecutionLease.tla index 48ca862..233e097 100644 --- a/specs/ExecutionLease.tla +++ b/specs/ExecutionLease.tla @@ -8,26 +8,36 @@ (* `mark_rejected`, `cancel`, `requeue_leased`, *) (* `recover_expired_leases`). *) (* Node side: `SchedulerContext` in crates/aether/src/proof/scheduler.rs *) -(* (`prepare_execution`, `prepare_leased`, `run_execution` with its *) -(* lease-renewal thread and `on_confirmed_start`, `settlement`, *) -(* `maintain`), and `ProofNode::cancel` / `ProofNode::shutdown` in *) -(* crates/aether/src/proof/mod.rs. *) -(* Agent side: `Agent::start_turn_with_events` and `Agent::cancel` in *) -(* crates/aether/src/agent/{codex,connected}.rs, and `EarlyCancels` in *) -(* crates/aether/src/agent.rs. An adapter keeps a cancel for a turn that *) -(* it did not register yet, and cancels that turn when it registers it. *) -(* It drops a cancel for a turn that ended, and `Agent::forget` drops a *) -(* kept cancel when the execution ends. *) +(* (`dispatch_one` with `RunningTasks::reserve`, `prepare_execution`, *) +(* `prepare_leased`, `run_execution` with its lease-renewal thread and *) +(* `on_confirmed_start`, `settlement`, `maintain`, `stop_recovered`), *) +(* and `ProofNode::cancel` / `ProofNode::shutdown` / *) +(* `ProofNode::set_running_limit` in crates/aether/src/proof/mod.rs. *) +(* Agent side: `Agent::start_turn_with_events`, `Agent::cancel` and *) +(* `Agent::capacity` in crates/aether/src/agent/{codex,connected}.rs, *) +(* and `EarlyCancels` in crates/aether/src/agent.rs. An adapter keeps a *) +(* cancel for a turn that it did not register yet, and cancels that turn *) +(* when it registers it. It drops a cancel for a turn that ended, and *) +(* `Agent::forget` drops a kept cancel when the execution ends. *) (* *) -(* One node process runs one scheduler, so at most one execution is *) -(* active. The process can stop (crash or exit) and start again. Each *) -(* store call is one atomic step, as each runs in one SQLite transaction *) -(* on the store worker thread. The clock is a small counter. *) +(* One node process runs one scheduler. The scheduler runs up to `cap` *) +(* executions at once, each on its own execution thread: a worker for each *) +(* execution ID (`Uuid::new_v4`, one for each lease). `cap` is the smaller *) +(* of the owner's running-task limit and the agent's capacity; either can *) +(* change at any time, so `SetCap` sets it to any value. A lower `cap` *) +(* stops no execution: it only keeps the scheduler from leasing another *) +(* task until fewer than `cap` executions are active. `dispatch_serial` is *) +(* one lock for all of them: one execution at a time confirms its start *) +(* and a cancel waits for that. The process can stop (crash or exit) and *) +(* start again. Each store call is one atomic step, as each runs in one *) +(* SQLite transaction on the store worker thread. The clock is a small *) +(* counter. *) (* *) (* Abstracted away: task input and output, events, retention, the order *) (* in which `lease_next` picks a queued task, queue limits, and the *) (* `event_error` path of `run_execution`, and the bound of 256 task IDs *) -(* in each `EarlyCancels` list. *) +(* in each `EarlyCancels` list. A slot is taken at the lease: the reserve *) +(* and `lease_next` are one step. *) (***************************************************************************) EXTENDS Naturals, FiniteSets @@ -36,7 +46,8 @@ CONSTANTS MaxExec, \* how many execution IDs (`Uuid::new_v4`) the model hands out TTL, \* LEASE_TTL, in clock ticks MaxTime, \* the clock stops here - MaxRestarts \* how often the node process may stop and start again + MaxRestarts,\* how often the node process may stop and start again + MaxCap \* the most executions that `cap` can allow at once States == {"pending_approval", "queued", "leased", "running", "unknown_result", "operator_reviewed", "succeeded", "failed", "rejected", "cancelled"} @@ -56,7 +67,9 @@ Allows(from, to) == Execs == 1..MaxExec NoLease == [exec |-> 0, exp |-> 0] -Phases == {"idle", "leased", "prepared", "confirm", "confirm_check", +\* "start": the run began and waits for `dispatch_serial`. "confirm" and +\* "confirm_check" hold it. +Phases == {"idle", "leased", "prepared", "start", "confirm", "confirm_check", "starting", "turn", "finish", "finish_renewal"} Outcomes == {"none", "ok", "err", "cancelled"} @@ -66,29 +79,30 @@ VARIABLES now, \* the clock nextExec, \* the next fresh execution ID grant, \* whether policy and access groups still allow the task - w, \* the one execution thread (`run_execution`) - turn, \* the agent turn that the execution started, and the - \* adapter's `EarlyCancels` + w, \* the execution thread (`run_execution`) of each execution + cap, \* how many executions the scheduler may have active + turn, \* the agent turn of each task + early, \* `EarlyCancels.cancelled` of the adapter + ended, \* `EarlyCancels.ended` of the adapter + spurious, \* ghost: see NoSpuriousCancel signals, \* tasks with an `Agent::cancel` call that is not made yet shutdown, \* the `shutdown` flag restarts, \* how often the process stopped starts \* how often an agent turn started for each task -vars == <> +vars == <> -IdleWorker == [phase |-> "idle", task |-> CHOOSE t \in Tasks : TRUE, exec |-> 0, +IdleWorker == [phase |-> "idle", task |-> CHOOSE t \in Tasks : TRUE, confirmed |-> FALSE, renewFailed |-> FALSE, outcome |-> "none"] -\* `early` and `ended` are the two lists of `EarlyCancels`. `spurious` is a -\* ghost: the adapter cancelled a turn at its start with a cancel that an -\* earlier execution of the task left behind (see NoSpuriousCancel). -NoTurn == [live |-> FALSE, registered |-> FALSE, interrupted |-> FALSE, - task |-> CHOOSE t \in Tasks : TRUE, early |-> {}, ended |-> {}, - spurious |-> FALSE] +NoTurn == [live |-> FALSE, registered |-> FALSE, interrupted |-> FALSE] -\* The turn is over: `NoTurn`, with the adapter's lists kept. -TurnOver(early, ended, spurious) == - [NoTurn EXCEPT !.early = early, !.ended = ended, !.spurious = spurious] +\* The executions that hold a slot of the scheduler. +Busy == {e \in Execs : w[e].phase # "idle"} +\* The executions that hold `dispatch_serial`. +Holders == {e \in Execs : w[e].phase \in {"confirm", "confirm_check"}} +\* The execution of `t` that holds a slot, if there is one. +RunsTask(e, t) == w[e].phase # "idle" /\ w[e].task = t TypeOK == /\ state \in [Tasks -> States] @@ -96,11 +110,14 @@ TypeOK == /\ now \in 0..MaxTime /\ nextExec \in 1..(MaxExec + 1) /\ grant \in [Tasks -> BOOLEAN] - /\ w \in [phase : Phases, task : Tasks, exec : 0..MaxExec, - confirmed : BOOLEAN, renewFailed : BOOLEAN, outcome : Outcomes] - /\ turn \in [live : BOOLEAN, registered : BOOLEAN, interrupted : BOOLEAN, - task : Tasks, early : SUBSET Tasks, ended : SUBSET Tasks, - spurious : BOOLEAN] + /\ w \in [Execs -> [phase : Phases, task : Tasks, confirmed : BOOLEAN, + renewFailed : BOOLEAN, outcome : Outcomes]] + /\ cap \in 1..MaxCap + /\ turn \in [Tasks -> [live : BOOLEAN, registered : BOOLEAN, + interrupted : BOOLEAN]] + /\ early \subseteq Tasks + /\ ended \subseteq Tasks + /\ spurious \in BOOLEAN /\ signals \subseteq Tasks /\ shutdown \in BOOLEAN /\ restarts \in 0..MaxRestarts @@ -112,8 +129,12 @@ Init == /\ now = 0 /\ nextExec = 1 /\ grant = [t \in Tasks |-> TRUE] - /\ w = IdleWorker - /\ turn = NoTurn + /\ w = [e \in Execs |-> IdleWorker] + /\ cap = 1 + /\ turn = [t \in Tasks |-> NoTurn] + /\ early = {} + /\ ended = {} + /\ spurious = FALSE /\ signals = {} /\ shutdown = FALSE /\ restarts = 0 @@ -146,60 +167,75 @@ Requeue(t) == Apply(r) == state' = r.st /\ lease' = r.ls +SetW(e, r) == w' = [w EXCEPT ![e] = r] + \* `Agent::cancel`: it interrupts a turn that the adapter registered. \* Otherwise `EarlyCancels::cancel` keeps it, unless the turn of the task -\* already ended. +\* already ended. It touches the turn of `t` and no other. Interrupt(t) == - turn' = IF turn.live /\ turn.registered /\ turn.task = t - THEN [turn EXCEPT !.interrupted = TRUE] - ELSE IF t \in turn.ended THEN turn - ELSE [turn EXCEPT !.early = @ \cup {t}] + IF turn[t].live /\ turn[t].registered + THEN /\ turn' = [turn EXCEPT ![t].interrupted = TRUE] + /\ UNCHANGED <> + ELSE IF t \in ended + THEN UNCHANGED <> + ELSE /\ early' = early \cup {t} + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* The environment. *) Tick == now < MaxTime /\ now' = now + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* The owner approves a task that waits for approval. Approve(t) == /\ state[t] = "pending_approval" /\ state' = [state EXCEPT ![t] = "queued"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* The owner revokes the grant or removes the caller from its group. Revoke(t) == /\ grant[t] /\ grant' = [grant EXCEPT ![t] = FALSE] - /\ UNCHANGED <> + /\ UNCHANGED <> + +\* The owner changes the running-task limit (`ProofNode::set_running_limit`, +\* `set_queue_limit`), or the agent's capacity changes (a connected agent +\* that attaches again). The value is read at the next dispatch. Nothing +\* that runs is touched. +SetCap(n) == + /\ n # cap + /\ cap' = n + /\ UNCHANGED <> \* `ProofNode::cancel` / `cancel_from`: under `dispatch_serial`, then \* `canceller.cancel` after the lock. The store call fails on a task that \* cannot become cancelled, and then no signal follows. -CancelHeld == w.phase \in {"confirm", "confirm_check"} - CancelStore(t) == - /\ ~CancelHeld + /\ Holders = {} /\ \/ state[t] = "cancelled" /\ UNCHANGED <> \/ /\ Allows(state[t], "cancelled") /\ Apply(Set(t, "cancelled", NoLease)) /\ signals' = signals \cup {t} - /\ UNCHANGED <> + /\ UNCHANGED <> \* `canceller.cancel(task_id)`, made after a cancel or a recovery. Signal(t) == /\ t \in signals /\ signals' = signals \ {t} /\ Interrupt(t) - /\ UNCHANGED <> + /\ UNCHANGED <> \* `maintain` -> `recover_expired_leases(now)`, then `canceller.cancel` -\* for the active task if recovery moved it to unknown_result. -RecoverAll == +\* for each active task that recovery moved to unknown_result. Another +\* running task keeps its lease and runs on. +Recover == LET expired == {t \in Tasks : lease[t] # NoLease /\ lease[t].exp <= now} toUnknown == {t \in expired : state[t] = "running"} IN /\ expired # {} @@ -208,29 +244,29 @@ RecoverAll == ELSE IF t \in toUnknown THEN "unknown_result" ELSE state[t]] /\ lease' = [t \in Tasks |-> IF t \in expired THEN NoLease ELSE lease[t]] - /\ signals' = signals \cup - {t \in toUnknown : w.phase # "idle" /\ w.task = t} - -Recover == - /\ RecoverAll - /\ UNCHANGED <> + /\ signals' = signals \cup {t \in toUnknown : \E e \in Execs : RunsTask(e, t)} + /\ UNCHANGED <> -\* `ProofNode::shutdown`: set the flag. Its cancel of the active task is +\* `ProofNode::shutdown`: set the flag. Its cancel of each active task is \* one more `CancelStore`, which the model allows at any time. Shutdown == /\ ~shutdown /\ shutdown' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* The process stops (an exit after shutdown, or a crash at any time) and -\* starts again. The agent child process stops with it. On start, -\* `ProofNode::with_scopes` runs `recover_expired_leases(now)`. +\* starts again. The agent child processes stop with it. On start, +\* `ProofNode::with_scopes` runs `recover_expired_leases(now)`. The limit +\* is read from the stored policy again; any value can come back. Restart == /\ restarts < MaxRestarts /\ restarts' = restarts + 1 - /\ w' = IdleWorker - /\ turn' = NoTurn + /\ w' = [e \in Execs |-> IdleWorker] + /\ turn' = [t \in Tasks |-> NoTurn] + /\ early' = {} + /\ ended' = {} /\ shutdown' = FALSE /\ LET expired == {t \in Tasks : lease[t] # NoLease /\ lease[t].exp <= now} IN /\ state' = [t \in Tasks |-> @@ -240,188 +276,221 @@ Restart == ELSE state[t]] /\ lease' = [t \in Tasks |-> IF t \in expired THEN NoLease ELSE lease[t]] /\ signals' = {} - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* The execution thread. *) - -\* `dispatch_one` -> `prepare_execution` -> `lease_next`. +(* The scheduler and the execution threads. *) + +\* `dispatch_one`: `RunningTasks::reserve(effective_running_limit)`, then +\* `prepare_execution` -> `lease_next_except`. A slot is free while fewer +\* than `cap` executions are active. The scheduler does not lease a task +\* that an execution of its own still holds (`RunningTasks::tasks_in_flight`). +\* Without that rule, a task whose lease ran out before its renewal thread +\* started goes back to the queue (`Recover`), is leased again, and has two +\* executions: the first one's lost lease then cancels the second one's turn +\* (see NoSpuriousCancel). One slot made that impossible; `cap` > 1 does not. Lease(t) == - /\ w.phase = "idle" /\ ~shutdown /\ nextExec <= MaxExec + /\ Cardinality(Busy) < cap + /\ \A e \in Execs : ~RunsTask(e, t) /\ state[t] = "queued" /\ Apply(Set(t, "leased", [exec |-> nextExec, exp |-> now + TTL])) - /\ w' = [IdleWorker EXCEPT !.phase = "leased", !.task = t, !.exec = nextExec] + /\ SetW(nextExec, [IdleWorker EXCEPT !.phase = "leased", !.task = t]) /\ nextExec' = nextExec + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> \* `prepare_leased`. -Prepare == - /\ w.phase = "leased" - /\ LET t == w.task IN +Prepare(e) == + /\ w[e].phase = "leased" + /\ LET t == w[e].task IN CASE state[t] = "cancelled" -> - Apply(Requeue(t)) /\ w' = IdleWorker + Apply(Requeue(t)) /\ SetW(e, IdleWorker) [] state[t] # "leased" -> - UNCHANGED <> /\ w' = IdleWorker + UNCHANGED <> /\ SetW(e, IdleWorker) [] ~grant[t] -> - Apply(MarkRejected(t, w.exec)) /\ w' = IdleWorker + Apply(MarkRejected(t, e)) /\ SetW(e, IdleWorker) [] OTHER -> - UNCHANGED <> /\ w' = [w EXCEPT !.phase = "prepared"] - /\ UNCHANGED <> + UNCHANGED <> /\ SetW(e, [w[e] EXCEPT !.phase = "prepared"]) + /\ UNCHANGED <> \* `run_execution`, before the executor runs. The renewal thread starts. -RunStart == - /\ w.phase = "prepared" +RunStart(e) == + /\ w[e].phase = "prepared" /\ IF shutdown - THEN Apply(Requeue(w.task)) /\ w' = IdleWorker - ELSE UNCHANGED <> /\ w' = [w EXCEPT !.phase = "confirm"] - /\ UNCHANGED <> + THEN Apply(Requeue(w[e].task)) /\ SetW(e, IdleWorker) + ELSE UNCHANGED <> /\ SetW(e, [w[e] EXCEPT !.phase = "start"]) + /\ UNCHANGED <> + +\* `on_confirmed_start` takes `dispatch_serial`. One execution at a time +\* holds it, so one start is confirmed at a time. +Acquire(e) == + /\ w[e].phase = "start" + /\ Holders = {} + /\ SetW(e, [w[e] EXCEPT !.phase = "confirm"]) + /\ UNCHANGED <> \* `on_confirmed_start`, part 1, under `dispatch_serial`: the shutdown \* check, the policy recheck, and `mark_running`. -ConfirmRunning == - /\ w.phase = "confirm" - /\ LET t == w.task IN +ConfirmRunning(e) == + /\ w[e].phase = "confirm" + /\ LET t == w[e].task IN CASE shutdown -> \* `requeue_leased`, and `settled_at_start`. Apply(Requeue(t)) - /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "cancelled"] + /\ SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "cancelled"]) [] ~grant[t] -> - Apply(MarkRejected(t, w.exec)) - /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] - [] LeaseIs(t, w.exec) /\ state[t] = "leased" -> + Apply(MarkRejected(t, e)) + /\ SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "err"]) + [] LeaseIs(t, e) /\ state[t] = "leased" -> Apply(Set(t, "running", lease[t])) - /\ w' = [w EXCEPT !.phase = "confirm_check"] + /\ SetW(e, [w[e] EXCEPT !.phase = "confirm_check"]) [] OTHER -> UNCHANGED <> - /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] - /\ UNCHANGED <> + /\ SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "err"]) + /\ UNCHANGED <> \* `on_confirmed_start`, part 2: read the state again. On success the \* executor calls `start_turn`, and the agent turn begins. -ConfirmCheck == - /\ w.phase = "confirm_check" - /\ LET t == w.task IN +ConfirmCheck(e) == + /\ w[e].phase = "confirm_check" + /\ LET t == w[e].task IN CASE state[t] = "cancelled" -> - w' = [w EXCEPT !.phase = "finish", !.outcome = "cancelled"] + SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "cancelled"]) /\ UNCHANGED <> [] state[t] \in {"leased", "running"} -> - /\ w' = [w EXCEPT !.phase = "starting", !.confirmed = TRUE] - /\ turn' = [turn EXCEPT !.live = TRUE, !.registered = FALSE, - !.interrupted = FALSE, !.task = t] + /\ SetW(e, [w[e] EXCEPT !.phase = "starting", !.confirmed = TRUE]) + /\ turn' = [turn EXCEPT ![t] = [live |-> TRUE, registered |-> FALSE, + interrupted |-> FALSE]] /\ starts' = [starts EXCEPT ![t] = @ + 1] [] OTHER -> - w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] + SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "err"]) /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> \* The adapter registers the turn (Codex `turns.active` after `turn/start`; \* the connected agent's `pending` map). `EarlyCancels::take`: a cancel \* that came first ends the turn here as cancelled. Otherwise \* `Agent::cancel` interrupts the turn from now on. -Register == - /\ w.phase = "starting" - /\ LET t == w.task IN - IF t \in turn.early - THEN /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "cancelled"] - /\ turn' = TurnOver(turn.early \ {t}, turn.ended \cup {t}, - turn.spurious \/ (state[t] = "running" - /\ ~w.renewFailed /\ ~shutdown)) - ELSE /\ w' = [w EXCEPT !.phase = "turn"] - /\ turn' = [turn EXCEPT !.registered = TRUE] - /\ UNCHANGED <> + /\ UNCHANGED <> \* The turn fails before the adapter registers it. -StartFails == - /\ w.phase = "starting" - /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] - /\ turn' = TurnOver(turn.early, turn.ended \cup {w.task}, turn.spurious) - /\ UNCHANGED <> +StartFails(e) == + /\ w[e].phase = "starting" + /\ SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = "err"]) + /\ turn' = [turn EXCEPT ![w[e].task] = NoTurn] + /\ ended' = ended \cup {w[e].task} + /\ UNCHANGED <> \* The turn ends. An interrupted turn ends as cancelled. -TurnEnds == - /\ w.phase = "turn" - /\ \E o \in IF turn.interrupted THEN {"cancelled"} ELSE {"ok", "err"} : - w' = [w EXCEPT !.phase = "finish", !.outcome = o] - /\ turn' = TurnOver(turn.early \ {w.task}, turn.ended \cup {w.task}, - turn.spurious) - /\ UNCHANGED <> +TurnEnds(e) == + /\ w[e].phase = "turn" + /\ LET t == w[e].task IN + /\ \E o \in IF turn[t].interrupted THEN {"cancelled"} ELSE {"ok", "err"} : + SetW(e, [w[e] EXCEPT !.phase = "finish", !.outcome = o]) + /\ turn' = [turn EXCEPT ![t] = NoTurn] + /\ early' = early \ {t} + /\ ended' = ended \cup {t} + /\ UNCHANGED <> \* The renewal thread of `run_execution` -> `renew_lease`. On failure it \* calls `canceller.cancel` once and stops. A cancel deletes the lease, so \* it also makes the renewal fail: this is the cancel's second signal. -Renew == - /\ w.phase \in {"confirm", "confirm_check", "starting", "turn"} +Renew(e) == + /\ w[e].phase \in {"start", "confirm", "confirm_check", "starting", "turn"} /\ ~shutdown - /\ ~w.renewFailed - /\ LET t == w.task IN - IF LeaseIs(t, w.exec) /\ lease[t].exp > now + /\ ~w[e].renewFailed + /\ LET t == w[e].task IN + IF LeaseIs(t, e) /\ lease[t].exp > now THEN /\ lease' = [lease EXCEPT ![t].exp = now + TTL] - /\ UNCHANGED <> - ELSE /\ w' = [w EXCEPT !.renewFailed = TRUE] + /\ UNCHANGED <> + ELSE /\ SetW(e, [w[e] EXCEPT !.renewFailed = TRUE]) /\ Interrupt(t) /\ UNCHANGED lease - /\ UNCHANGED <> + /\ UNCHANGED <> \* `ProofNode::shutdown`: while an execution is active, it calls -\* `canceller.cancel` for it again every 20 ms. -ShutdownSignal == +\* `canceller.cancel` for each active task again every 20 ms. +ShutdownSignal(t) == /\ shutdown - /\ w.phase # "idle" - /\ Interrupt(w.task) - /\ UNCHANGED <> + /\ \E e \in Execs : RunsTask(e, t) + /\ Interrupt(t) + /\ UNCHANGED <> \* `Agent::forget`, which `run_execution` calls after the executor returns \* and the renewal thread stops: the adapter drops a kept cancel. -Forget(t) == turn' = [turn EXCEPT !.early = @ \ {t}] +Forget(t) == early' = early \ {t} \* `run_execution` after the executor returns and the renewal thread stops. -Finish == - /\ w.phase = "finish" - /\ LET t == w.task - e == w.exec - IN IF w.renewFailed - THEN /\ Apply(IF w.outcome = "ok" THEN MarkEnd(t, e, "succeeded") ELSE Same) - /\ w' = [w EXCEPT !.phase = "finish_renewal"] +Finish(e) == + /\ w[e].phase = "finish" + /\ LET t == w[e].task + IN IF w[e].renewFailed + THEN /\ Apply(IF w[e].outcome = "ok" THEN MarkEnd(t, e, "succeeded") ELSE Same) + /\ SetW(e, [w[e] EXCEPT !.phase = "finish_renewal"]) /\ Forget(t) - ELSE /\ Apply(CASE w.outcome = "ok" -> MarkEnd(t, e, "succeeded") - [] w.outcome = "cancelled" -> Same - [] OTHER -> IF w.confirmed THEN MarkEnd(t, e, "unknown_result") + ELSE /\ Apply(CASE w[e].outcome = "ok" -> MarkEnd(t, e, "succeeded") + [] w[e].outcome = "cancelled" -> Same + [] OTHER -> IF w[e].confirmed THEN MarkEnd(t, e, "unknown_result") ELSE MarkEnd(t, e, "failed")) - /\ w' = IdleWorker + /\ SetW(e, IdleWorker) /\ Forget(t) - /\ UNCHANGED <> + /\ UNCHANGED <> \* `run_execution`, the renewal-failed branch after the late result. -FinishRenewal == - /\ w.phase = "finish_renewal" - /\ LET t == w.task IN +FinishRenewal(e) == + /\ w[e].phase = "finish_renewal" + /\ LET t == w[e].task IN Apply(IF state[t] = "cancelled" THEN Same - ELSE IF w.confirmed THEN MarkEnd(t, w.exec, "unknown_result") - ELSE MarkEnd(t, w.exec, "failed")) - /\ w' = IdleWorker - /\ UNCHANGED <> + ELSE IF w[e].confirmed THEN MarkEnd(t, e, "unknown_result") + ELSE MarkEnd(t, e, "failed")) + /\ SetW(e, IdleWorker) + /\ UNCHANGED <> Next == \/ Tick \/ Recover \/ Shutdown \/ Restart + \/ \E n \in 1..MaxCap : SetCap(n) \/ \E t \in Tasks : Approve(t) \/ Revoke(t) \/ CancelStore(t) \/ Signal(t) - \/ Lease(t) - \/ Prepare \/ RunStart \/ ConfirmRunning \/ ConfirmCheck \/ Register - \/ StartFails \/ TurnEnds \/ Renew \/ ShutdownSignal \/ Finish - \/ FinishRenewal + \/ Lease(t) \/ ShutdownSignal(t) + \/ \E e \in Execs : Prepare(e) \/ RunStart(e) \/ Acquire(e) + \/ ConfirmRunning(e) \/ ConfirmCheck(e) \/ Register(e) + \/ StartFails(e) \/ TurnEnds(e) \/ Renew(e) \/ Finish(e) + \/ FinishRenewal(e) Spec == Init /\ [][Next]_vars -\* The renewal thread and the shutdown loop run while the execution runs, +\* Each renewal thread and the shutdown loop run while their execution runs, \* and each `canceller.cancel` that follows a store call is made. The turn \* itself gets no fairness: an agent may run until `max_seconds`. -FairSpec == Spec /\ WF_vars(Renew) /\ WF_vars(ShutdownSignal) - /\ \A t \in Tasks : WF_vars(Signal(t)) +FairSpec == Spec /\ (\A e \in Execs : WF_vars(Renew(e))) + /\ (\A t \in Tasks : WF_vars(ShutdownSignal(t))) + /\ (\A t \in Tasks : WF_vars(Signal(t))) ----------------------------------------------------------------------------- (* Properties. *) @@ -431,17 +500,19 @@ LeaseIffActive == \A t \in Tasks : (lease[t] # NoLease) <=> (state[t] \in {"leased", "running"}) \* An agent turn starts at most once for a task: no lease expiry, cancel, -\* restart, or requeue makes the node run a task again. +\* restart, requeue, or second execution makes the node run a task again. AtMostOneStart == \A t \in Tasks : starts[t] <= 1 \* While a turn is live, its task is running, or it ended in a state that \* a person must look at (cancelled, unknown_result). It never shows as \* queued, leased, or a result that the turn did not give. TurnMatchesState == - turn.live => state[turn.task] \in {"running", "cancelled", "unknown_result"} + \A t \in Tasks : + turn[t].live => state[t] \in {"running", "cancelled", "unknown_result"} \* Every cancel reaches the turn: a registered turn whose task is cancelled -\* or unknown_result is interrupted, or it ends. +\* or unknown_result is interrupted, or it ends. This holds for each task +\* of several that run at once. \* \* An `Agent::cancel` can come before the adapter registers the turn \* (Codex inserts it into `turns.active` only after `turn/start` answers; @@ -449,9 +520,10 @@ TurnMatchesState == \* keeps it, and the turn ends as cancelled when it registers. No signal \* is repeated: the cancel itself and one renewal failure are all. CancelReachesTurn == - [](turn.live /\ turn.registered - /\ state[turn.task] \in {"cancelled", "unknown_result"} - => <>(turn.interrupted \/ ~turn.live)) + \A t \in Tasks : + [](turn[t].live /\ turn[t].registered + /\ state[t] \in {"cancelled", "unknown_result"} + => <>(turn[t].interrupted \/ ~turn[t].live)) \* The adapter cancels a turn at its start only for a cancel, a lost lease \* or a shutdown of this execution. Before `run_execution` called @@ -460,6 +532,24 @@ CancelReachesTurn == \* the queue, and the kept cancel ended the turn of the next execution. \* `settlement` writes nothing for `ExecutionError::Cancelled`, so the task \* stayed `running` with no turn and ended as `unknown_result`. -NoSpuriousCancel == ~turn.spurious +NoSpuriousCancel == ~spurious + +\* One execution at a time holds `dispatch_serial`, so no two starts are +\* confirmed together, and a cancel (which takes the same lock) never lands +\* between the policy recheck and `mark_running` of any of them. +OneStartAtATime == Cardinality(Holders) <= 1 + +\* The scheduler never has more executions than the model hands out, and +\* never takes a slot beyond `cap` at the time it takes it. A lower `cap` +\* does not shrink the number of executions: the count only falls when an +\* execution ends. +RunningWithinCap == + [][Cardinality(Busy') > Cardinality(Busy) => Cardinality(Busy') <= cap]_vars + +\* A change of the limit changes no state, lease, worker or turn: it never +\* stops a task that runs. +CapChangeTouchesNothing == + [][cap' # cap => (state' = state /\ lease' = lease /\ w' = w + /\ turn' = turn)]_vars ============================================================================= diff --git a/specs/ExecutionLeaseSerial.cfg b/specs/ExecutionLeaseSerial.cfg new file mode 100644 index 0000000..924ad22 --- /dev/null +++ b/specs/ExecutionLeaseSerial.cfg @@ -0,0 +1,22 @@ +\* ExecutionLeaseSerial: ExecutionLease with the default limit of one running +\* task. See ExecutionLeaseSerial.tla. +SPECIFICATION FairSpec +CONSTANTS + Tasks = {t1, t2} + MaxExec = 3 + TTL = 2 + MaxTime = 5 + MaxRestarts = 1 + MaxCap = 1 +INVARIANTS + TypeOK + LeaseIffActive + AtMostOneStart + TurnMatchesState + NoSpuriousCancel + OneStartAtATime + OneExecution +PROPERTIES + CancelReachesTurn + RunningWithinCap + CapChangeTouchesNothing diff --git a/specs/ExecutionLeaseSerial.tla b/specs/ExecutionLeaseSerial.tla new file mode 100644 index 0000000..c51d20d --- /dev/null +++ b/specs/ExecutionLeaseSerial.tla @@ -0,0 +1,17 @@ +------------------------- MODULE ExecutionLeaseSerial ------------------------- +(***************************************************************************) +(* ExecutionLease with the running-task limit at its default of one: the *) +(* node as it was before it could run more than one task. `MaxCap` is 1, *) +(* so `cap` never leaves 1 (see ExecutionLeaseSerial.cfg), and at most one *) +(* execution is active, whatever the scheduler, a cancel, a lost lease or *) +(* a restart does. Every property of ExecutionLease holds here too, with *) +(* more runs of the clock and more restarts than the concurrent model can *) +(* afford. *) +(***************************************************************************) +EXTENDS ExecutionLease + +\* One execution thread at a time: the scheduler of a node with the +\* default limit. +OneExecution == Cardinality(Busy) <= 1 + +============================================================================= diff --git a/specs/ManagedRoster.tla b/specs/ManagedRoster.tla index bafad15..67c61fd 100644 --- a/specs/ManagedRoster.tla +++ b/specs/ManagedRoster.tla @@ -274,6 +274,12 @@ Rekey(p, k) == \* that endpoint, not revoked. \* It reads the roster and changes nothing, so it is a predicate here, not \* an action: the claim admits work in each state where it holds. +\* `RosterClaims` reads through a `KeptStore`, which stays open between +\* calls. Each read starts a new read transaction, so it sees the roster as +\* committed at that moment, as a new open did; the store opens again when +\* the file is replaced or its `user_version` differs, and a store that +\* cannot open gives `ProviderError::Unavailable`, which admits nothing. +\* That is the same predicate: a stutter step, not a change to the model. Admits(a, e) == roster[a].st = "active" /\ roster[a].ep = e diff --git a/specs/Outbox.tla b/specs/Outbox.tla index 63b43b3..e1f464c 100644 --- a/specs/Outbox.tla +++ b/specs/Outbox.tla @@ -120,6 +120,13 @@ Init == ----------------------------------------------------------------------------- (* The sender's store. Each action is one SQLite transaction. *) +\* The loop of `run` reaches the store through a `KeptStore`, which opens +\* the file again when the path names another file (a restored backup) or +\* its `user_version` is not that of this binary (it fails closed for a +\* newer one). So the store of the processes here is always the file that +\* `enqueue` writes to, which is what the model assumes. This is below the +\* abstraction, not a change to an action. + \* `state IN ('waiting','working') AND (lease_until IS NULL OR \* lease_until <= now)`. Claimable(t) == @@ -271,6 +278,15 @@ TimeOut(p, t) == ----------------------------------------------------------------------------- (* The host. *) +\* The per-peer rate limit of the host sheds a frame before this action: +\* it answers "node overloaded" with `retryAfterMs`, and the host does not +\* change `seen` or `hostTasks`. `follow` sends a new frame for up to +\* `OVERLOAD_RETRY_WINDOW` (and not past the attempt window), which is a +\* `Send` whose frame arrives later: a stutter step here. When the window +\* ends, `outcome` maps the error to Waiting with `Delay::RateLimited`, as +\* it maps "busy" to Waiting with `Delay::Busy`; the model does not track +\* the delays. A full queue is the "busy" reply below and is not sent again. + \* `NodeService::handle` -> `ProofNode::admit` -> `admit_with_replay`. The \* policy check comes first; the replay key `exchange_id:nonce` is checked \* before the idempotency key; an overloaded queue rolls back the whole diff --git a/specs/PactConsent.tla b/specs/PactConsent.tla index a60618b..814ca2f 100644 --- a/specs/PactConsent.tla +++ b/specs/PactConsent.tla @@ -31,8 +31,8 @@ (* foreign token is the same as an invalid one), other callers (a poll by *) (* another PA gets `Unknown` and changes nothing), contexts and message *) (* reservation and retries, receipts, slow_down, queue limits, the access *) -(* groups (they do not apply to the pact scope), the single-execution *) -(* scheduler slot, lease expiry (see ExecutionLease), cancellation, and a *) +(* groups (they do not apply to the pact scope), the execution slots of *) +(* the scheduler, lease expiry (see ExecutionLease), cancellation, and a *) (* crash between the two steps of `approve`. An access token has no *) (* expiry of its own here: an expired token gets 401 like a token for a *) (* revoked or expired grant, which the model covers. Only the first code *) diff --git a/specs/PendingChange.tla b/specs/PendingChange.tla index dadbc77..7c31d20 100644 --- a/specs/PendingChange.tla +++ b/specs/PendingChange.tla @@ -22,11 +22,19 @@ (* crates/aether/src/admin_ui/advanced.rs the confirm and the policy *) (* form of the UI (AuditActor::Ui) *) (* crates/aether/src/policy.rs save_policy_settings_in_store, *) -(* stored_queue_limits *) +(* stored_queue_limits, stored_running_limit *) (* crates/aether/src/node_builder.rs the replay at node start: grants *) (* of the policy file without the revoked ones, then the stored *) -(* grants, the stored limit, admin.current.workspace *) +(* grants, the stored limits, admin.current.workspace *) (* crates/aether/src/node_service.rs impl LiveNode for RunningNode *) +(* crates/aether/src/proof/mod.rs ProofNode::set_queue_limit, *) +(* set_running_limit *) +(* *) +(* There are two limits (`QueueLimitId`): "queue", which stands for the *) +(* two limits of the waiting tasks (they take the same path and behave *) +(* alike), and "running", the number of tasks that run at once. Each has *) +(* its own stored value, live value and value in the stored policy. A *) +(* limit change names its limit; the policy settings carry both. *) (* *) (* One process holds the Administration behind a mutex, so one request *) (* runs at a time; `op` is that request between its store and node calls. *) @@ -48,8 +56,8 @@ (* clock (a pending change expires at any moment), the audit records *) (* other than `applied` (an audit record has no value column, so it holds *) (* no secret by its type), grant expiry and a stored grant that no longer *) -(* verifies at start, the two limit ids and the two task limits of the *) -(* policy (one limit here), the `admin..` values of workspace, *) +(* verifies at start, the range of a limit (the running limit is 1 to 32; *) +(* here every limit is 1 to 3), the `admin..` values of workspace, *) (* capability, directory and policy changes (nothing reads them at *) (* start), set_relay, cancel_task, access groups, and the store writes of *) (* save_policy_settings_in_store, which are one step here. A live revoke *) @@ -73,19 +81,24 @@ Kinds == {"grant", "workspace", "limit", "capability", "directory", "policy"} \* every other grant. GVals == {"lo", "hi"} WVals == {"w1", "w2"} +LimIds == {"queue", "running"} Limits == 1..3 -InitLimit == 2 +\* The limits of a new node: two waiting tasks, one running task (the +\* default of `running_tasks`). +InitLimit == [l \in LimIds |-> IF l = "queue" THEN 2 ELSE 1] +NoLimits == [l \in LimIds |-> 0] InitWs == "w1" -\* The value of a change: `val` for a grant or a workspace, `num` for a -\* limit, both for the policy settings. Capability and directory changes -\* have one value. +\* The value of a change: `val` for a grant or a workspace, `num` for the +\* limit that `lim` names, `lims` (both limits) for the policy settings. +\* Capability and directory changes have one value. ValsOf(kind) == - CASE kind = "grant" -> [val : GVals, num : {0}] - [] kind = "workspace" -> [val : WVals, num : {0}] - [] kind = "limit" -> [val : {None}, num : Limits] - [] kind = "policy" -> [val : WVals, num : Limits] - [] OTHER -> [val : {None}, num : {0}] + CASE kind = "grant" -> [val : GVals, num : {0}, lim : {None}, lims : {NoLimits}] + [] kind = "workspace" -> [val : WVals, num : {0}, lim : {None}, lims : {NoLimits}] + [] kind = "limit" -> [val : {None}, num : Limits, lim : LimIds, lims : {NoLimits}] + [] kind = "policy" -> [val : WVals, num : {0}, lim : {None}, + lims : [LimIds -> Limits]] + [] OTHER -> [val : {None}, num : {0}, lim : {None}, lims : {NoLimits}] \* Change::is_high_risk. HighRisk(kind, v) == @@ -98,15 +111,15 @@ VARIABLES mode, \* "serve": a node runs in the process; "admin": none op, \* the request that holds the Administration mutex durGrant, \* store: admin.grant. - durLimit, \* store: admin.limit., 0 when not set + durLimit, \* store: admin.limit. of each limit, 0 when not set curWs, \* store: admin.current.workspace - pol, \* store: workspace and queue limit of the stored policy + pol, \* store: workspace and limits of the stored policy revoked, \* store: admin.revoked. pending, \* store: pending_changes and admin.pending_revision. drev, \* store: admin.revision mrev, \* Administration::revision, in memory liveGrant, \* node: the grants of the live policy - liveLimit, \* node: the queue limit + liveLimit, \* node: each limit liveWs, \* node: the workspace liveCap, \* node: a capability was published audits, \* store: the `applied` audit records @@ -114,7 +127,7 @@ VARIABLES \* Ghosts. grOk, \* grants that a UI action asked for or confirmed wsOk, \* workspaces that a UI action asked for or confirmed - limOk, \* the highest limit that a UI action asked for + limOk, \* the highest value of each limit that a UI action asked for capOk, \* a UI action confirmed a capability dead, \* grants revoked, with no new apply of the id since applies, \* changes, revokes and policy saves that took effect @@ -130,10 +143,11 @@ flags == <> vars == <> -NoPending == [kind |-> None, val |-> None, num |-> 0, base |-> 0, - expired |-> FALSE, landed |-> "no"] +NoPending == [kind |-> None, val |-> None, num |-> 0, lim |-> None, + lims |-> NoLimits, base |-> 0, expired |-> FALSE, landed |-> "no"] Idle == [pc |-> "idle", actor |-> "ui", kind |-> "grant", id |-> CHOOSE i \in Ids : TRUE, val |-> None, num |-> 0, + lim |-> None, lims |-> NoLimits, prevVal |-> None, prevNum |-> 0, prevCur |-> None] Max(a, b) == IF a >= b THEN a ELSE b @@ -142,27 +156,29 @@ TypeOK == /\ mode \in {"serve", "admin"} /\ op \in [pc : Pcs, actor : Actors, kind : Kinds, id : Ids, val : GVals \cup WVals \cup {None}, num : 0..3, + lim : LimIds \cup {None}, lims : [LimIds -> 0..3], prevVal : GVals \cup {None}, prevNum : 0..3, prevCur : WVals \cup {None}] /\ durGrant \in [Ids -> GVals \cup {None}] - /\ durLimit \in 0..3 + /\ durLimit \in [LimIds -> 0..3] /\ curWs \in WVals \cup {None} - /\ pol \in [ws : WVals, limit : Limits] + /\ pol \in [ws : WVals, limit : [LimIds -> Limits]] /\ revoked \subseteq Ids /\ pending \in [Ids -> [kind : Kinds \cup {None}, val : GVals \cup WVals \cup {None}, num : 0..3, + lim : LimIds \cup {None}, lims : [LimIds -> 0..3], base : 0..MaxOps, expired : BOOLEAN, landed : {"no", "other", "change"}]] /\ drev \in 0..MaxOps /\ mrev \in 0..MaxOps /\ liveGrant \in [Ids -> GVals \cup {None}] - /\ liveLimit \in Limits + /\ liveLimit \in [LimIds -> Limits] /\ liveWs \in WVals /\ liveCap \in BOOLEAN /\ audits \in 0..MaxOps /\ applies \in 0..MaxOps /\ nOps \in 0..MaxOps /\ restarts \in 0..MaxRestarts /\ grOk \subseteq Ids \X GVals /\ wsOk \subseteq WVals - /\ limOk \in Limits + /\ limOk \in [LimIds -> Limits] /\ capOk \in BOOLEAN /\ dead \subseteq Ids /\ mcpRevived \in BOOLEAN /\ staleConfirmed \in BOOLEAN @@ -180,7 +196,7 @@ Init == /\ mode = "serve" /\ op = Idle /\ durGrant = [id \in Ids |-> None] - /\ durLimit = 0 + /\ durLimit = NoLimits /\ curWs = None /\ pol = [ws |-> InitWs, limit |-> InitLimit] /\ revoked = {} @@ -212,8 +228,9 @@ Approve(kind, id, v) == /\ grOk' = IF kind = "grant" THEN grOk \cup {<>} ELSE grOk /\ wsOk' = IF kind \in {"workspace", "policy"} THEN wsOk \cup {v.val} ELSE wsOk - /\ limOk' = IF kind \in {"limit", "policy"} THEN Max(limOk, v.num) - ELSE limOk + /\ limOk' = CASE kind = "limit" -> [limOk EXCEPT ![v.lim] = Max(@, v.num)] + [] kind = "policy" -> [l \in LimIds |-> Max(limOk[l], v.lims[l])] + [] OTHER -> limOk /\ capOk' = (capOk \/ kind = "capability") ----------------------------------------------------------------------------- @@ -222,13 +239,15 @@ Approve(kind, id, v) == (* the hub workers, the policy form). *) \* change_requires_confirmation. A limit from MCP is free only when the -\* live node reads a limit that is not lower. Policy settings from MCP are -\* free only when they keep the workspace and raise no limit -\* (policy_is_wider). +\* live node reads a value of that limit that is not lower. Policy settings +\* from MCP are free only when they keep the workspace and raise no limit +\* (policy_is_wider: each limit of `QueueLimitId::ALL`, the running limit +\* too). NeedsConfirmation(actor, kind, v) == /\ actor = "mcp" - /\ CASE kind = "limit" -> ~(mode = "serve" /\ v.num <= liveLimit) - [] kind = "policy" -> v.val # pol.ws \/ v.num > pol.limit + /\ CASE kind = "limit" -> ~(mode = "serve" /\ v.num <= liveLimit[v.lim]) + [] kind = "policy" -> \/ v.val # pol.ws + \/ \E l \in LimIds : v.lims[l] > pol.limit[l] [] OTHER -> HighRisk(kind, v) \* Administration::apply or save_policy_settings -> queue_pending -> @@ -241,6 +260,7 @@ Queue(actor, kind, id, v) == /\ IF pending[id].kind = None \/ pending[id].expired THEN \/ pending' = [pending EXCEPT ![id] = [kind |-> kind, val |-> v.val, num |-> v.num, + lim |-> v.lim, lims |-> v.lims, base |-> mrev, expired |-> FALSE, landed |-> "no"]] \/ Fault /\ UNCHANGED pending ELSE UNCHANGED pending @@ -253,13 +273,14 @@ Queue(actor, kind, id, v) == \* `p` is the pending table without the row that a confirm removes. Keep(actor, kind, id, v, p) == /\ op' = [pc |-> "live", actor |-> actor, kind |-> kind, id |-> id, - val |-> v.val, num |-> v.num, + val |-> v.val, num |-> v.num, lim |-> v.lim, lims |-> v.lims, prevVal |-> IF kind = "grant" THEN durGrant[id] ELSE None, - prevNum |-> IF kind = "limit" THEN durLimit ELSE 0, + prevNum |-> IF kind = "limit" THEN durLimit[v.lim] ELSE 0, prevCur |-> curWs] /\ durGrant' = IF kind = "grant" THEN [durGrant EXCEPT ![id] = v.val] ELSE durGrant - /\ durLimit' = IF kind = "limit" THEN v.num ELSE durLimit + /\ durLimit' = IF kind = "limit" THEN [durLimit EXCEPT ![v.lim] = v.num] + ELSE durLimit /\ curWs' = IF kind = "workspace" THEN v.val ELSE curWs /\ drev' = mrev + 1 /\ mrev' = mrev + 1 /\ audits' = audits + 1 @@ -296,7 +317,7 @@ Confirm(id) == /\ pending[id].kind # None /\ nOps' = nOps + 1 /\ LET p == pending[id] - v == [val |-> p.val, num |-> p.num] + v == [val |-> p.val, num |-> p.num, lim |-> p.lim, lims |-> p.lims] nothing == UNCHANGED < /\ LiveDone - /\ liveLimit' = IF mode = "serve" THEN op.num ELSE liveLimit + /\ liveLimit' = IF mode = "serve" + THEN [liveLimit EXCEPT ![op.lim] = op.num] + ELSE liveLimit /\ UNCHANGED <> [] op.kind = "workspace" -> \/ /\ LiveDone @@ -359,8 +382,8 @@ ApplyLive == \/ refuse [] op.kind = "policy" -> \/ /\ LiveDone - /\ pol' = [ws |-> op.val, limit |-> op.num] - /\ durLimit' = 0 + /\ pol' = [ws |-> op.val, limit |-> op.lims] + /\ durLimit' = NoLimits /\ UNCHANGED node \/ Fault /\ refuse [] OTHER -> @@ -376,7 +399,9 @@ PutBack == /\ durGrant' = IF op.kind = "grant" THEN [durGrant EXCEPT ![op.id] = op.prevVal] ELSE durGrant - /\ durLimit' = IF op.kind = "limit" THEN op.prevNum ELSE durLimit + /\ durLimit' = IF op.kind = "limit" + THEN [durLimit EXCEPT ![op.lim] = op.prevNum] + ELSE durLimit /\ curWs' = IF op.kind = "workspace" THEN op.prevCur ELSE curWs /\ audits' = audits - 1 /\ op' = Idle @@ -440,15 +465,15 @@ RevokeLive == \* Administration::save_policy_settings -> save_policy_settings_in_store. \* The audit record is written first (record_change); when the save fails, \* fail_change marks it, and when that fails too the record stays. The -\* save keeps the workspace and the limit in the stored policy and removes -\* the stored limit of `aether.change`. The running node keeps its -\* settings until it starts again. +\* save keeps the workspace and the limits in the stored policy and removes +\* the stored limit of `aether.change` of every limit. The running node +\* keeps its settings until it starts again. SavePolicy(actor, v) == /\ op.pc = "idle" /\ nOps < MaxOps /\ ~NeedsConfirmation(actor, "policy", v) /\ nOps' = nOps + 1 - /\ \/ /\ pol' = [ws |-> v.val, limit |-> v.num] - /\ durLimit' = 0 + /\ \/ /\ pol' = [ws |-> v.val, limit |-> v.lims] + /\ durLimit' = NoLimits /\ audits' = audits + 1 /\ applies' = applies + 1 /\ pending' = Landed(pending, "other") @@ -482,7 +507,8 @@ Restart(m) == /\ op' = Idle /\ mrev' = drev /\ liveGrant' = [id \in Ids |-> IF m = "serve" THEN StartGrant(id) ELSE None] - /\ liveLimit' = IF durLimit # 0 THEN durLimit ELSE pol.limit + /\ liveLimit' = [l \in LimIds |-> + IF durLimit[l] # 0 THEN durLimit[l] ELSE pol.limit[l]] /\ liveWs' = IF curWs # None THEN curWs ELSE pol.ws /\ liveCap' = FALSE /\ UNCHANGED <> @@ -522,22 +548,22 @@ CapabilityNeedsUi == liveCap => capOk \* than a limit that a UI action asked for. StoredFromUi == /\ curWs # None => curWs \in wsOk - /\ durLimit <= limOk - /\ pol.ws \in wsOk /\ pol.limit <= limOk + /\ \A l \in LimIds : durLimit[l] <= limOk[l] + /\ pol.ws \in wsOk /\ \A l \in LimIds : pol.limit[l] <= limOk[l] -\* The live workspace and limit come from a UI action only. An MCP client -\* moves the workspace or raises the limit neither with a change nor with -\* UpdatePolicy and a node start. +\* The live workspace and limits come from a UI action only. An MCP client +\* moves the workspace or raises a limit (the running-task limit too) +\* neither with a change nor with UpdatePolicy and a node start. LiveFromUi == /\ liveWs \in wsOk - /\ liveLimit <= limOk + /\ \A l \in LimIds : liveLimit[l] <= limOk[l] \* When no request runs and no undo waits, the node and the store agree, \* also after a store write failed. Agree == /\ \A id \in Ids : liveGrant[id] = StartGrant(id) /\ curWs # None => liveWs = curWs - /\ durLimit # 0 => liveLimit = durLimit + /\ \A l \in LimIds : durLimit[l] # 0 => liveLimit[l] = durLimit[l] LiveMatchesStore == (mode = "serve" /\ op.pc = "idle") => Agree \* A revoked grant is not live and not in the store, and a node start does diff --git a/specs/README.md b/specs/README.md index dcefbd6..31af4c6 100644 --- a/specs/README.md +++ b/specs/README.md @@ -10,13 +10,15 @@ change the model in the same commit. |---|---|---| | `DirectInvite` | `invites.rs`, `join_and_apply` in `access_groups.rs`, `import_bundle` and the contact functions in `direct.rs`, `PolicyEngine::admit`, `check_group` | A call that failed leaves no grant; one `sign_direct_invite` call runs at a time, so failed calls leave nobody in the group; a returned line whose grant is live admits its person unless the owner took them out of the group; the host admits a request only from an endpoint that the owner invited, with a claim signed for that endpoint, so a copied line gives nothing; the caller keeps only an authorization for its own endpoint; one contact name for one endpoint; a valid contact's name stays with its endpoint; each invite call ends (liveness) | | `Admission` | `a2a_transport.rs`, `proof/admission.rs`, `PolicyEngine::admit`, `admit_with_replay`, `own_ids` and `cancel_if_owned` in `aether-store/src/tasks.rs` | A task's owner is the authenticated endpoint, which had a live grant and a group membership; one task for each endpoint and idempotency key; a refused, replayed or changed frame changes nothing; a nonce stays in the replay table until it expires; the queue stays within its limits, with one per-peer limit for each endpoint, so two endpoints under one name share nothing; a task ID that another endpoint used does not refuse a caller, and one endpoint has one task for a task ID that it sent; no answer shows another endpoint's task; only the owner cancels; an honest caller with access gets its task in (liveness) | -| `ExecutionLease` | `NodeStore` lease functions, `SchedulerContext` in `proof/scheduler.rs`, `Agent::cancel` and `EarlyCancels` in `agent.rs` | A lease row exists only while a task is leased or running; a turn starts at most once for a task; a live turn's task is running, cancelled, or `unknown_result`; a cancel that an earlier run left does not stop a turn; every cancel reaches the turn (liveness) | -| `ConnectedAgent` | `agent/connected.rs`, `EarlyCancels` in `agent.rs`, `protocol/agent-socket` | An open task ID belongs to a running turn on that connection; a task goes only to the attached connection, and only its agent's answer is taken; an answer comes only after the task was sent; a turn ends once; no agent, no task sent; a cancel never reaches the agent before its task; a cancel before the start cancels the turn, and no cancel is kept after its turn ended; no turn waits on a connection that is over; every turn ends with its time limit, and a turn with a cancelled honest agent stops (liveness) | +| `ExecutionLease` | `NodeStore` lease functions (`lease_next_except`), `SchedulerContext` and `RunningTasks` in `proof/scheduler.rs`, `ProofNode::set_running_limit`, `Agent::cancel`, `Agent::capacity` and `EarlyCancels` in `agent.rs` | The scheduler runs up to `cap` executions at once (the owner's running-task limit, or the agent's capacity when that is lower), each on its own thread: a lease row exists only while a task is leased or running; a turn starts at most once for a task, also with several executions; the scheduler takes a slot only below `cap`, and a change of `cap` stops nothing that runs; one execution at a time holds `dispatch_serial` to confirm its start; a live turn's task is running, cancelled, or `unknown_result`; a cancel that an earlier run left, or that another execution of the task left, does not stop a turn; every cancel reaches its own turn, whatever else runs (liveness) | +| `ExecutionLeaseSerial` | The same as `ExecutionLease`, with the default running-task limit of one | The same properties, with restarts and a longer clock, and at most one execution at a time | +| `ConnectedAgent` | `agent/connected.rs`, `EarlyCancels` in `agent.rs`, `protocol/agent-socket` | An open task ID belongs to a running turn on that connection, also with two tasks open at once, and an answer or a cancel of one never touches the other; `max_tasks` of `ready` is read by `ConnectedAgent::capacity`; a task goes only to the attached connection, and only its agent's answer is taken; an answer comes only after the task was sent; a turn ends once; no agent, no task sent; a cancel never reaches the agent before its task; a cancel before the start cancels the turn, and no cancel is kept after its turn ended; no turn waits on a connection that is over; every turn ends with its time limit, and a turn with a cancelled honest agent stops (liveness) | +| `ConnectedAgentRerun` | The same as `ConnectedAgent` | The same properties, with one task ID that gets two turns and two connections | | `EventPaging` | `events_page`, `task_progress` and the event writers in `aether-store/src/tasks.rs`, `A2aTransport::handle`, `request_with_polling_on`, `follow` in `outbox.rs` | Event sequences have no gap and never change; a page is the ordered run after the caller's cursor; a page says "no more events" only at the end of the journal; the state and the page are from one instant; the cursor never moves back; a `node request` or an outbox attempt that stops with an answer has every event up to the one that ended the task; an ended task lets the caller stop (liveness) | | `Outbox` | `outbox.rs`, `sent_tasks` store functions, host admission | The host keeps one task for each sent task; an answer comes only from the host; a task that the host runs never shows as failed after a replay; an attempt whose lease another process claimed records nothing; an ended task does not change; each task ends (liveness) | | `HubInvite` | `hub_sync.rs`, `hub_membership.rs`, `admin_ui/hub.rs` workers, `server/lib/aether_hub` | A grant only for an approved row and its first endpoint; no grant for a blocked endpoint; one live grant for each approval, also when the store fails; a kept line belongs to the approval it was signed for; the caller keeps only lines that it accepted; an honest hub delivers an accepted invite (liveness) | | `ManagedRoster` | `managed_client.rs`, `directory_client.rs`, `control_service.rs`, `aether-store/src/{managed,directory,control}.rs`, `RosterClaims::verify` in `identity.rs` | A token makes one member; a roster row comes from a join event; a claim admits work only for a member that joined; with one control URL the roster is exactly the events up to the cursor; a revoke that the node applied stays, whatever spellings of the control URL it used; a cursor never moves back or skips; the caller uses only an unexpired record of the trusted key, its scope and the agent it asked for, also with an attacker directory; a record that was public before a revoke cannot be published again; a revoke reaches a node that keeps syncing, each cursor catches up, and directory events reach the node also past an expired or other-key record (liveness) | -| `PendingChange` | `admin.rs` (`Administration`, `check_live`, `settle`), `aether-store/src/admin.rs`, `admin_socket.rs`, the start replay in `node_builder.rs` | A high-risk grant or a capability is live or stored only after a UI action for that id and value; a workspace, a limit and the stored policy come only from a UI action, also through `UpdatePolicy` and a node start; when no request runs and no undo waits, the node and the store agree, also after a store write failed; a revoked grant stays out, also after a restart; a stale confirmation is refused, also when the process stopped before the node had the other change; each change that took effect has an `applied` audit record written no later than the change; an expired pending change never applies; each request ends (liveness) | +| `PendingChange` | `admin.rs` (`Administration`, `check_live`, `settle`), `aether-store/src/admin.rs`, `admin_socket.rs`, the start replay in `node_builder.rs` | A high-risk grant or a capability is live or stored only after a UI action for that id and value; a workspace, a limit and the stored policy come only from a UI action (each limit: the two queue limits and the running-task limit), also through `UpdatePolicy` and a node start; when no request runs and no undo waits, the node and the store agree, also after a store write failed; a revoked grant stays out, also after a restart; a stale confirmation is refused, also when the process stopped before the node had the other change; each change that took effect has an `applied` audit record written no later than the change; an expired pending change never applies; each request ends (liveness) | | `PactConsent` | `pact/`, `aether-store/src/pact.rs`, the dispatch recheck in `proof.rs` | One token for each device code; no token from a denied code; no task without a token; a failed approval leaves no grant; no task starts after its grant is revoked; an approved flow gets a token, and an admitted task ends (liveness) | ## Properties that are not checked