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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
approve_skill waits for the write lock (skills_test flake)
Lin (kwant bot)19e357fc11f7
diff --git a/src/db/continuity.rs b/src/db/continuity.rsindex 35959aa2..a324387e 100644--- a/src/db/continuity.rs+++ b/src/db/continuity.rs@@ -664,7 +664,7 @@ impl Database {id: &str,change: PinChange,) -> Result<Memory, MemoryError> {- let mut tx = self.pool.begin().await?;+ let mut tx = self.begin_write().await?;let row: Option<(String, Option<String>)> =sqlx::query_as("SELECT source, pinned_by FROM kwant_memories WHERE id = ? AND kwant_id = ?").bind(id)@@ -672,21 +672,25 @@ impl Database {.fetch_optional(&mut *tx).await?;let Some((source, pinned_by)) = row else {+ tx.rollback().await?;return Err(MemoryError::NotFound);};if !change.by_person {if source == "user" {+ tx.rollback().await?;return Err(MemoryError::PersonWritten);}if pinned_by.as_deref() == Some("user") && !change.pinned {+ tx.rollback().await?;return Err(MemoryError::PersonPinned);}}if change.pinned == pinned_by.is_some() {- drop(tx);+ tx.rollback().await?;return self.get_memory(id).await;}if change.pinned && pinned_count(&mut tx, kwant_id).await? >= MAX_PINNED_PER_KWANT {+ tx.rollback().await?;return Err(MemoryError::TooManyPinned);}let by = change.pinned.then_some(if change.by_person { "user" } else { "agent" });diff --git a/src/db/documents.rs b/src/db/documents.rsindex 87722265..1eaf72f4 100644--- a/src/db/documents.rs+++ b/src/db/documents.rs@@ -158,7 +158,7 @@ impl Database {/// so the caller can delete the blobs nothing else uses.pub async fn document_delete(&self, case_id: &str) -> Result<Vec<super::attachments::Attachment>, DbError> {let context = format!("document:{case_id}");- let mut tx = self.pool.begin().await?;+ let mut tx = self.begin_write().await?;let attachments: Vec<super::attachments::Attachment> =sqlx::query_as("SELECT * FROM attachments WHERE context_id = ?").bind(&context).fetch_all(&mut *tx).await?;sqlx::query("DELETE FROM attachments WHERE context_id = ?").bind(&context).execute(&mut *tx).await?;diff --git a/src/db/mod.rs b/src/db/mod.rsindex c7955131..7b361d5e 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -709,12 +709,13 @@ impl Database {};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 Some((old_name,)): Option<(String,)> = sqlx::query_as("SELECT name FROM teams WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?else {+ tx.rollback().await?;return Ok(None);};let new_channel = format!("team-{}", input.name);@@ -726,6 +727,7 @@ impl Database {.await?;let chat = match (chat, taken) {(Some(chat), Some((other,))) if chat != other => {+ tx.rollback().await?;return Err(DbError::Conflict(format!("a channel called #{new_channel} already exists; rename or delete it first")));@@ -774,12 +776,13 @@ impl Database {/// Deletes the team and keeps its chat, history and all, as an ordinary channel renamed to/// `archived-team-<name>` (see [`archive_team_chat`]), in the same transaction.pub async fn delete_team(&self, id: &str) -> Result<bool, DbError> {- let mut tx = self.pool.begin().await?;+ let mut tx = self.begin_write().await?;let Some((space, name)): Option<(String, String)> = sqlx::query_as("SELECT space_id, name FROM teams WHERE id = ?").bind(id).fetch_optional(&mut *tx).await?else {+ tx.rollback().await?;return Ok(false);};let space = SpaceId::new(space);diff --git a/src/db/skills.rs b/src/db/skills.rsindex b755105c..5305ed27 100644--- a/src/db/skills.rs+++ b/src/db/skills.rs@@ -342,7 +342,7 @@ impl Database {let kwant_id = edit.kwant_id.clone().unwrap_or(skill.kwant_id.clone());self.check_skill_owner(&SpaceId::new(&skill.space_id), kwant_id.as_deref()).await?;let now = Utc::now();- let mut tx = self.pool.begin().await?;+ let mut tx = self.begin_write().await?;// The revised skill steps aside; any other live skill with the target name blocks approvalif let Some(old) = &skill.replaces_id {sqlx::query("UPDATE skills SET status = 'superseded', updated_at = ? WHERE id = ? AND status IN ('enabled', 'disabled')")@@ -361,6 +361,7 @@ impl Database {.fetch_optional(&mut *tx).await?;if clash.is_some() {+ tx.rollback().await?;return Err(SkillError::Conflict(format!("a skill called {} already exists; rename this one or disable that one first", text.name)));}sqlx::query(diff --git a/tests/skills_test.rs b/tests/skills_test.rsindex 678afebd..acff19dc 100644--- a/tests/skills_test.rs+++ b/tests/skills_test.rs@@ -293,3 +293,34 @@ async fn skills_migration_is_idempotent_and_additive() {let db = kwnt::db::Database::init(tmp.path()).await.unwrap();assert_eq!(db.list_skills(&kwnt::db::spaces::SpaceId::default_space(), None, Some("enabled")).await.unwrap().len(), 1);}++/// Approving while another connection writes waits for it instead of a 500 "database error": the+/// approval checks the name for a clash 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 here, behind the+/// proposing turn's writes.+#[tokio::test]+async fn approving_waits_for_another_write_instead_of_failing() {+ use std::time::{Duration, Instant};+ let env = setup().await;+ let text = kwnt::db::skills::SkillText { name: "lock-wait".into(), description: "Wait for the lock".into(), body: "1. wait".into() };+ let pending = env.state.db.propose_skill(&env.a, text).await.unwrap();++ // Another connection holds the write lock for 300 ms+ let other = sqlx::sqlite::SqlitePoolOptions::new()+ .max_connections(1)+ .connect(&format!("sqlite://{}", env.tmp.path().join("data").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 (s, v) = call(&env.app, "POST", &format!("/api/skills/{}/approve", pending.id), None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["status"], "enabled");+ assert!(started.elapsed() >= Duration::from_millis(250), "the lock was held during the approval");+ writer.await.unwrap();+}