Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Goals: refuse latency under 0 ms; busy timeout for the proposals concurrency test (#243)

Oleksandr Ivanchenkof32c1a259f7c
diff --git a/src/db/goals.rs b/src/db/goals.rs
index b35572b6..0a962e83 100644
--- a/src/db/goals.rs
+++ b/src/db/goals.rs
@@ -973,7 +973,10 @@ mod tests {
#[tokio::test]
async fn concurrent_proposals_never_pass_the_cap() {
- let (db, _dir) = db().await;
+ // Eight writers queue on SQLite's lock; on a loaded machine the default 5 s wait can run
+ // out ("database is locked"), so this test's connections wait up to a minute
+ let dir = tempfile::tempdir().unwrap();
+ let db = Database::init_with_busy_timeout(dir.path(), std::time::Duration::from_secs(60)).await.unwrap();
let mut handles = Vec::new();
for _ in 0..8 {
let db = db.clone();
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 0ae725e1..18d9b80a 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -44,13 +44,19 @@ pub mod smart_results;
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
/// Default's #general description before the "kwant bots" wording; replaced only if unchanged.
const OLD_GENERAL_DESCRIPTION: &str = "Main collaboration hub for all agents";
+/// How long a connection waits for SQLite's write lock (sqlx's default, kept explicit).
+const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
+
/// Set once [`Database::migrate_chain_budget_default`] has run.
const CHAIN_BUDGET_OPT_IN_DONE: &str = "chain_token_budget_opt_in_v1";
use models::*;
use spaces::SpaceId;
-use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
-use std::path::Path;
+use sqlx::{
+ sqlite::{SqliteConnectOptions, SqlitePoolOptions},
+ Pool, Sqlite,
+};
+use std::{path::Path, str::FromStr, time::Duration};
use thiserror::Error;
use uuid::Uuid;
@@ -110,16 +116,23 @@ const STARTERS: [(&str, &str, &str, &str, &str); 3] = [
impl Database {
pub async fn init(data_dir: &Path) -> Result<Self, DbError> {
- Self::open(data_dir, true).await
+ Self::open(data_dir, true, BUSY_TIMEOUT).await
+ }
+
+ /// `init` with a longer wait for SQLite's write lock, for tests that make many connections
+ /// write at once on a loaded machine (a writer waits this long at `BEGIN IMMEDIATE`).
+ #[doc(hidden)]
+ pub async fn init_with_busy_timeout(data_dir: &Path, busy_timeout: Duration) -> Result<Self, DbError> {
+ Self::open(data_dir, true, busy_timeout).await
}
/// The database as a release from before spaces leaves it, for migration tests.
#[doc(hidden)]
pub async fn init_without_spaces(data_dir: &Path) -> Result<Self, DbError> {
- Self::open(data_dir, false).await
+ Self::open(data_dir, false, BUSY_TIMEOUT).await
}
- async fn open(data_dir: &Path, spaces: bool) -> Result<Self, DbError> {
+ async fn open(data_dir: &Path, spaces: bool, busy_timeout: Duration) -> Result<Self, DbError> {
std::fs::create_dir_all(data_dir)?;
let db_path = data_dir.join("kwnt.db");
let fresh = !db_path.exists();
@@ -217,9 +230,12 @@ impl Database {
db.migrate_truth_ledger().await?;
db.pool.close().await;
+ // Said out loud rather than left to sqlx's default: every writer, a goal proposal
+ // included, waits this long for the lock before "database is locked"
+ let options = SqliteConnectOptions::from_str(&conn_str)?.busy_timeout(busy_timeout);
let pool = SqlitePoolOptions::new()
.max_connections(10)
- .connect(&conn_str)
+ .connect_with(options)
.await?;
sqlx::query("PRAGMA synchronous = NORMAL;").execute(&pool).await?;
Ok(Self { pool, data_dir: data_dir.to_path_buf() })
diff --git a/src/server/goals/predicate.rs b/src/server/goals/predicate.rs
index 28543d44..871fad4e 100644
--- a/src/server/goals/predicate.rs
+++ b/src/server/goals/predicate.rs
@@ -142,6 +142,10 @@ pub fn normalize(kind: &str, spec: &Value, metric: Option<&str>, operator: Optio
"exit_code" => whole(target, 0, 255).ok_or("an exit code target is a whole number from 0 to 255")?.to_string(),
"latency_ms" => {
let n = number(target).filter(|n| (0.0..=MAX_LATENCY_MS).contains(n)).ok_or("a latency target is a number of milliseconds from 0 to 600000")?;
+ // A latency is never below 0, so "under 0 ms" can never be met
+ if n == 0.0 && operator == Some("lt") {
+ return Err("a latency can't be under 0 ms, so that goal could never be met: use 1 or more with lt, or lte 0".into());
+ }
plain(n)
}
"stdout_number" => plain(number(target).ok_or("stdout_number needs a number target, at most 1e15 either way")?),
@@ -574,6 +578,11 @@ mod tests {
assert!(n("http", json!({}), Some("latency_ms"), Some("eq"), Some("500")).is_err());
assert!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("fast")).is_err());
assert!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("-1")).is_err());
+ // M1: nothing is under 0 ms; 1 is the lowest target that can be met
+ assert!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("0")).unwrap_err().contains("never be met"));
+ assert!(n("http", json!({}), Some("latency_ms"), None, Some("0.0")).is_err());
+ assert_eq!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("1")), Ok(Some(p("latency_ms", Some("lt"), "1"))));
+ assert_eq!(n("http", json!({}), Some("latency_ms"), Some("lte"), Some("0")), Ok(Some(p("latency_ms", Some("lte"), "0"))));
assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("NaN")).is_err());
assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("Infinity")).is_err());
assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("1e308")).is_err());
diff --git a/tests/goals_test.rs b/tests/goals_test.rs
index 8a8bafe3..a0d80bf8 100644
--- a/tests/goals_test.rs
+++ b/tests/goals_test.rs
@@ -318,11 +318,22 @@ async fn the_api_creates_edits_pauses_and_deletes_goals() {
assert_eq!((v["goal"]["status"].as_str(), v["goal"]["mode"].as_str(), v["goal"]["confirm_failures"].as_i64()), (Some("checking"), Some("suggest"), Some(2)));
assert_eq!(v["goal"]["checks"][0]["says"], format!("{url} answers with status 200"));
assert_eq!(v["goal"]["checks"][1]["required"], false);
+ // M1: the lowest latency target that can be met (lt 1) is accepted, lt 0 is refused in plain words
+ let edge = json!({"title": "Fast", "checks": [{"kind": "http", "spec": {"url": url}, "metric": "latency_ms", "operator": "lt", "target": 1}]});
+ let (status, v2) = call(&e.app, "POST", "/api/goals", None, Some(edge)).await;
+ assert_eq!(status, StatusCode::OK, "{v2}");
+ assert_eq!(v2["goal"]["checks"][0]["target"], "1");
+ let none = json!({"title": "Fast", "checks": [{"kind": "http", "spec": {"url": url}, "metric": "latency_ms", "operator": "lt", "target": 0}]});
+ let (status, v3) = call(&e.app, "POST", "/api/goals", None, Some(none)).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(v3["error"].as_str().unwrap_or("").contains("never be met"), "{v3}");
// Refusals
for (bad, code) in [
(json!({"title": "", "checks": [{"kind": "http", "spec": {"url": url}}]}), StatusCode::BAD_REQUEST),
(json!({"title": "x", "checks": [{"kind": "http", "spec": {"url": url}, "severity": "advisory"}]}), StatusCode::BAD_REQUEST),
(json!({"title": "x", "interval_minutes": 5, "checks": [{"kind": "http", "spec": {"url": url}}]}), StatusCode::BAD_REQUEST),
+ // M1: a latency under 0 ms could never be met
+ (json!({"title": "x", "checks": [{"kind": "http", "spec": {"url": url}, "metric": "latency_ms", "operator": "lt", "target": 0}]}), StatusCode::BAD_REQUEST),
(json!({"from_task": "t1"}), StatusCode::NOT_FOUND), // wired by goals-remediation: an unknown task is a 404
] {
let (status, v) = call(&e.app, "POST", "/api/goals", None, Some(bad.clone())).await;
@@ -384,6 +395,11 @@ async fn propose(e: &Env, token: &str, args: Value) -> (bool, String) {
async fn a_bot_proposes_drafts_and_only_the_person_approves() {
let e = setup().await;
let token = turn(&e, "t-goal").await;
+ // M1: an impossible target is refused with a plain reason and takes no draft slot
+ let impossible = json!({"title": "Fast", "checks": [{"kind": "http", "spec": {"url": "https://example.com"}, "metric": "latency_ms", "operator": "lt", "target": 0}]});
+ let (err, text) = propose(&e, &token, impossible).await;
+ assert!(err && text.contains("never be met"), "{text}");
+ assert_eq!(e.state.db.count_draft_goals(&e.space).await.unwrap(), 0);
let args = json!({"title": "Report exists", "mode": "fix", "checks": [{"kind": "file_exists", "spec": {"path": "report.md"}}]});
let (err, text) = propose(&e, &token, args.clone()).await;
assert!(!err, "{text}");