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.

Fix "database is locked" flakes: wait for the write lock when a transaction reads first

Lin (kwant bot)5831be4fa151
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index e00b9198..35959aa2 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -506,17 +506,19 @@ impl Database {
let text = clean_memory_text(text)?;
let id = Uuid::new_v4().to_string();
let now = Utc::now();
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let (count,): (i64,) =
sqlx::query_as("SELECT COUNT(*) FROM kwant_memories WHERE kwant_id = ?")
.bind(kwant_id)
.fetch_one(&mut *tx)
.await?;
if count >= MAX_MEMORIES_PER_KWANT {
+ tx.rollback().await?;
return Err(MemoryError::TooMany);
}
let pinned_by = pinned.then(|| source.to_string());
if pinned && pinned_count(&mut tx, kwant_id).await? >= MAX_PINNED_PER_KWANT {
+ tx.rollback().await?;
return Err(MemoryError::TooManyPinned);
}
if let Some(turn_id) = outside_turn {
@@ -605,8 +607,9 @@ impl Database {
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
- // Rolls the provenance row back with it
- drop(tx);
+ // Rolls the provenance row back with it. Awaited, not dropped: a dropped transaction
+ // rolls back in the background and can still hold the write lock after we return
+ tx.rollback().await?;
return Err(self.why_agent_cannot_touch(kwant_id, id).await);
}
// Unchanged text fires no mirror; the marker must not outlive this write
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 31d0bc57..c7955131 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -215,6 +215,16 @@ impl Database {
Ok(Self { pool })
}
+ /// A transaction that holds SQLite's write lock from the start, for one that reads before it
+ /// writes. A plain `pool.begin()` only asks for the lock at its first write, and SQLite fails
+ /// that write at once with "database is locked" when another connection is writing: the busy
+ /// timeout doesn't apply to a transaction that has already read. This one waits for the lock
+ /// (up to the busy timeout) at `BEGIN` instead. Roll it back rather than drop it when giving
+ /// up, so the lock is free before the caller returns.
+ async fn begin_write(&self) -> Result<sqlx::Transaction<'static, Sqlite>, sqlx::Error> {
+ self.pool.begin_with("BEGIN IMMEDIATE").await
+ }
+
async fn seed_defaults(&self) -> Result<(), DbError> {
// Starters seeded before souls existed get one, unless the user has rewritten them
for (name, _, persona_prompt, soul, _) in STARTERS {
@@ -606,13 +616,14 @@ impl Database {
let members_json = serde_json::to_string(&input.member_kwants)?;
self.check_members(space, &input.lead_kwant_id, &input.member_kwants).await?;
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let (clash,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM teams WHERE space_id = ? AND name = ? COLLATE NOCASE")
.bind(space.as_str())
.bind(&input.name)
.fetch_one(&mut *tx)
.await?;
if clash > 0 {
+ tx.rollback().await?;
return Err(DbError::Conflict(format!("a team called {} already exists in this space", input.name)));
}
sqlx::query(
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 7d9591b3..da8c7095 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1182,6 +1182,34 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {
assert_eq!(status, StatusCode::UNAUTHORIZED, "token dies with the turn");
}
+/// A memory added while another connection is writing waits for it instead of failing with
+/// "database is locked": the add counts the bot's memories before it writes, and SQLite fails a
+/// transaction's first write at once when the lock is taken after it has read. Seen as a flake in
+/// `self_tools_are_scoped_to_the_turn_and_kwant`, right after a refused `memory_update`.
+#[tokio::test]
+async fn adding_a_memory_waits_for_another_write_instead_of_failing() {
+ let (_app, state, tmp) = setup().await;
+ let kwants = state.db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
+
+ // Another connection holds the write lock for 300 ms
+ let other = SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", tmp.path().join("kwnt.db").display()))
+ .await
+ .unwrap();
+ let tx = other.begin_with("BEGIN IMMEDIATE").await.unwrap();
+ let writer = tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ tx.commit().await.unwrap();
+ });
+
+ let started = std::time::Instant::now();
+ let m = state.db.add_memory(&kwants[0].id, "Prefers short replies", "user").await.unwrap();
+ assert!(started.elapsed() >= std::time::Duration::from_millis(250), "the lock was held during the add");
+ writer.await.unwrap();
+ assert!(state.db.list_memories(&kwants[0].id).await.unwrap().iter().any(|x| x.id == m.id));
+}
+
#[tokio::test]
async fn self_server_name_is_reserved() {
let (app, _state, _tmp) = setup().await;
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index fe4a3b96..7d2b4a1c 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -727,10 +727,14 @@ async fn follow_ups_and_restarts_report_in_the_origin_chat() {
};
let (_, open) = env.state.db.create_delegation(&left_open("Cut short")).await.unwrap();
delegation::interrupt_open(&env.state).await;
- wait_for("the restarted delegation to complete", || async { delegation_status(&env, &open.id).await == "completed" }).await;
+ // Its result is posted just after it's marked completed
+ wait_for("the restarted delegation's result in the lead's chat", || async {
+ delegation_status(&env, &open.id).await == "completed"
+ && env.state.db.list_messages(&env.lead, 30).await.unwrap().iter().any(|m| m.text.contains("answer restarted"))
+ })
+ .await;
let lead_chat = env.state.db.list_messages(&env.lead, 30).await.unwrap();
assert!(lead_chat.iter().any(|m| m.text.contains("Cut short") && m.text.contains("retrying it once now")));
- assert!(lead_chat.iter().any(|m| m.text.contains("answer restarted")));
// Its prompt warns that the cut-short run may have done part of the work; a first run's doesn't
let rerun = prompts_with("Task: Cut short");
assert!(!rerun.is_empty() && rerun.iter().all(|p| p.contains(delegation::RESTARTED_NOTE)), "{rerun:?}");
diff --git a/tests/server_test.rs b/tests/server_test.rs
index 76151fcb..0f6e1122 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -11,6 +11,8 @@ use kwnt::{
tools::ToolRunner,
};
use serde_json::json;
+use sqlx::sqlite::SqlitePoolOptions;
+use std::time::{Duration, Instant};
use tempfile::tempdir;
use tower::ServiceExt;
@@ -153,6 +155,50 @@ async fn test_teams_api_endpoints() {
assert_eq!(resp.status(), StatusCode::OK);
}
+/// A team made while another connection is writing waits for it instead of a 500 "database
+/// error": the create checks the name before it writes, and SQLite fails a transaction's first
+/// write at once when the lock is taken after it has read. Seen as a `delegation_test` flake,
+/// behind a delegated turn's writes.
+#[tokio::test]
+async fn creating_a_team_waits_for_another_write_instead_of_failing() {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let laya = LayaRouter::new(config.laya_url.clone());
+ let state = AppState::new(config, db.clone(), ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), laya);
+ let app = create_router(state);
+ let kwants = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();
+
+ // Another connection holds the write lock for 300 ms
+ let other = SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", tmp.path().join("kwnt.db").display()))
+ .await
+ .unwrap();
+ let tx = other.begin_with("BEGIN IMMEDIATE").await.unwrap();
+ let writer = tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ tx.commit().await.unwrap();
+ });
+
+ let started = Instant::now();
+ let payload = json!({"name": "night-shift", "lead_kwant_id": kwants[0].id, "member_kwants": [kwants[0].id, kwants[1].id]});
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/teams")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&payload).unwrap()))
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
+ assert!(started.elapsed() >= Duration::from_millis(250), "the lock was held during the create");
+ writer.await.unwrap();
+ let team: Team = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(team.name, "night-shift");
+}
+
#[tokio::test]
async fn test_chat_routing_with_kwant_mention() {
let tmp = tempdir().unwrap();