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.

Read-then-write paths wait for the write lock (follow-up to #221)

Lin (kwant bot)318541fe4be5
diff --git a/src/db/autofix.rs b/src/db/autofix.rs
index c0211ff7..dbee4028 100644
--- a/src/db/autofix.rs
+++ b/src/db/autofix.rs
@@ -322,7 +322,7 @@ impl Database {
/// Finishes the task's running attempt (if any) as `status`.
pub async fn finish_running_attempt(&self, task_id: &str, status: &str) -> Result<(), DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
finish_running(&mut tx, task_id, status, Utc::now()).await?;
tx.commit().await?;
Ok(())
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 60ff74b7..5b88214d 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -389,9 +389,10 @@ impl Database {
/// Removes a channel nobody has written in yet; `false` when it has messages or is #general.
pub async fn delete_empty_channel(&self, id: &str) -> Result<bool, DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages WHERE channel_id = ?").bind(id).fetch_one(&mut *tx).await?;
if n > 0 {
+ tx.rollback().await?;
return Ok(false);
}
let done = sqlx::query("DELETE FROM channels WHERE id = ? AND name != 'general'").bind(id).execute(&mut *tx).await?;
diff --git a/src/db/checkpoints.rs b/src/db/checkpoints.rs
index 6036dfd1..11d32810 100644
--- a/src/db/checkpoints.rs
+++ b/src/db/checkpoints.rs
@@ -319,7 +319,7 @@ impl Database {
/// A task event outside a state change (`restored`).
pub async fn task_event(&self, task_id: &str, mission_id: Option<&str>, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
insert_event(&mut tx, task_id, mission_id, kind, actor, None, None, detail).await?;
tx.commit().await?;
Ok(())
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index a324387e..0d966364 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -978,7 +978,7 @@ impl Database {
/// Takes every turn a previous run of kwnt left running (it stopped mid-reply).
pub async fn take_running_turns(&self) -> Result<Vec<RunningTurn>, DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let turns = sqlx::query_as::<_, RunningTurn>("SELECT * FROM running_turns ORDER BY started_at")
.fetch_all(&mut *tx)
.await?;
diff --git a/src/db/flight_school.rs b/src/db/flight_school.rs
index 65fcc5c8..c6cf3d9d 100644
--- a/src/db/flight_school.rs
+++ b/src/db/flight_school.rs
@@ -221,11 +221,15 @@ impl Database {
/// Sets a task's class and records a `class_changed` task event. Callers validate the slug and
/// who may set it (the lead or the person, never the task's own bot).
pub async fn set_task_class(&self, task_id: &str, class: &str, actor: &str) -> Result<bool, DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let row: Option<(String, Option<String>)> =
sqlx::query_as("SELECT task_class, mission_id FROM tasks WHERE id = ?").bind(task_id).fetch_optional(&mut *tx).await?;
- let Some((old, mission)) = row else { return Ok(false) };
+ let Some((old, mission)) = row else {
+ tx.rollback().await?;
+ return Ok(false);
+ };
if old == class {
+ tx.rollback().await?;
return Ok(true);
}
sqlx::query("UPDATE tasks SET task_class = ?, updated_at = ? WHERE id = ?").bind(class).bind(Utc::now()).bind(task_id).execute(&mut *tx).await?;
diff --git a/src/db/foundry.rs b/src/db/foundry.rs
index 0bcbc138..a2c1f50a 100644
--- a/src/db/foundry.rs
+++ b/src/db/foundry.rs
@@ -453,12 +453,13 @@ impl Database {
/// version: same lineage, and approving it supersedes the live one.
pub async fn insert_foundry_draft(&self, space_id: &str, d: &NewDraft, run_id: &str) -> Result<(Skill, SkillMeta), SkillError> {
let now = Utc::now();
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let (pending,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM skills WHERE status = 'pending' AND kwant_id = ?")
.bind(&d.kwant_id)
.fetch_one(&mut *tx)
.await?;
if pending >= MAX_PENDING_PER_KWANT {
+ tx.rollback().await?;
return Err(SkillError::TooManyPending);
}
let waiting: Option<(String,)> = sqlx::query_as(
@@ -469,6 +470,7 @@ impl Database {
.fetch_optional(&mut *tx)
.await?;
if waiting.is_some() {
+ tx.rollback().await?;
return Err(SkillError::Conflict("a Foundry draft for this class is already waiting for review".into()));
}
let live: Option<(String, String)> = sqlx::query_as(
@@ -543,13 +545,18 @@ impl Database {
/// name blocks it.
pub async fn rollback_skill(&self, target_id: &str, actor: &str) -> Result<Skill, SkillError> {
let now = Utc::now();
- let mut tx = self.pool.begin().await?;
- let target = sqlx::query_as::<_, Skill>("SELECT * FROM skills WHERE id = ?").bind(target_id).fetch_optional(&mut *tx).await?.ok_or(SkillError::NotFound)?;
+ let mut tx = self.begin_write().await?;
+ let Some(target) = sqlx::query_as::<_, Skill>("SELECT * FROM skills WHERE id = ?").bind(target_id).fetch_optional(&mut *tx).await? else {
+ tx.rollback().await?;
+ return Err(SkillError::NotFound);
+ };
let meta: Option<(String,)> = sqlx::query_as("SELECT lineage_id FROM skill_meta WHERE skill_id = ?").bind(target_id).fetch_optional(&mut *tx).await?;
let Some((lineage,)) = meta else {
+ tx.rollback().await?;
return Err(SkillError::Conflict("only a Foundry skill version can be rolled back to".into()));
};
if target.status != "superseded" {
+ tx.rollback().await?;
return Err(SkillError::Conflict(format!("only an earlier (superseded) version can be rolled back to; this one is {}", target.status)));
}
let current: Vec<(String,)> = sqlx::query_as(
@@ -571,6 +578,7 @@ impl Database {
.fetch_optional(&mut *tx)
.await?;
if clash.is_some() {
+ tx.rollback().await?;
return Err(SkillError::Conflict(format!("another skill called {} is live; rename or disable it first", target.name)));
}
sqlx::query("UPDATE skills SET status = 'enabled', updated_at = ?, reviewed_at = ? WHERE id = ?")
diff --git a/src/db/imports.rs b/src/db/imports.rs
index f5231540..3a4d0cac 100644
--- a/src/db/imports.rs
+++ b/src/db/imports.rs
@@ -177,7 +177,7 @@ impl Database {
pub async fn apply_import(&self, space: &SpaceId, bundle: &Bundle) -> Result<ImportRecord, DbError> {
let mut created = Created::default();
let now = Utc::now();
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let mut ids: HashMap<&str, String> = HashMap::new();
// Known up front so the ledger can say which import each memory came from
let import_id = Uuid::new_v4().to_string();
@@ -189,6 +189,7 @@ impl Database {
.fetch_one(&mut *tx)
.await?;
if taken > 0 {
+ tx.rollback().await?;
return Err(DbError::Conflict(format!("a bot called {} already exists in this space; preview again", bot.name)));
}
let id = Uuid::new_v4().to_string();
diff --git a/src/db/parked.rs b/src/db/parked.rs
index f7e5b9cc..a6039a28 100644
--- a/src/db/parked.rs
+++ b/src/db/parked.rs
@@ -67,7 +67,7 @@ impl Database {
/// Parks a turn; `None` when one is already waiting for that bot in that chat (it keeps its
/// time, so a chat gets at most one retry however many messages hit the limit).
pub async fn park_turn(&self, t: &NewParkedTurn) -> Result<Option<ParkedTurn>, DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let waiting: Option<(String,)> = sqlx::query_as(&format!("SELECT id FROM parked_turns WHERE status = 'pending' AND {SAME_CHAT}"))
.bind(&t.kwant_id)
.bind(t.channel_id.as_deref().unwrap_or(""))
@@ -76,6 +76,7 @@ impl Database {
.fetch_optional(&mut *tx)
.await?;
if waiting.is_some() {
+ tx.rollback().await?;
return Ok(None);
}
let row = sqlx::query_as::<_, ParkedTurn>(
diff --git a/src/db/truth_ledger.rs b/src/db/truth_ledger.rs
index 6110c2b7..b8b7b644 100644
--- a/src/db/truth_ledger.rs
+++ b/src/db/truth_ledger.rs
@@ -736,7 +736,7 @@ impl Database {
return Ok(None);
}
let (a, b) = if a < b { (a, b) } else { (b, a) };
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let (live,): (i64,) = sqlx::query_as(&format!(
"SELECT COUNT(DISTINCT f.space_id) * 10 + COUNT(*) FROM knowledge_facts f WHERE f.id IN (?, ?) AND {IN_FORCE}"
))
@@ -746,6 +746,7 @@ impl Database {
.await?;
// Both in force (2) and in one space (10)
if live != 12 {
+ tx.rollback().await?;
return Ok(None);
}
let id = format!("fd_{}", uuid::Uuid::new_v4().simple());
@@ -761,6 +762,7 @@ impl Database {
.execute(&mut *tx)
.await?;
if res.rows_affected() == 0 {
+ tx.rollback().await?;
return Ok(None);
}
for side in [a, b] {
diff --git a/src/db/waiting.rs b/src/db/waiting.rs
index e4e7a9b4..a963023b 100644
--- a/src/db/waiting.rs
+++ b/src/db/waiting.rs
@@ -73,7 +73,7 @@ impl Database {
/// for a plain ask, an earlier one of this bot in this chat still waiting (it keeps its time,
/// so asking again doesn't bring a second reminder).
pub async fn add_waiting(&self, w: &NewWaitingItem) -> Result<Option<WaitingItem>, DbError> {
- let mut tx = self.pool.begin().await?;
+ let mut tx = self.begin_write().await?;
let existing: Option<(String,)> = match &w.question_id {
Some(q) => sqlx::query_as("SELECT id FROM waiting_on_person WHERE question_id = ?").bind(q).fetch_optional(&mut *tx).await?,
None => {
@@ -89,6 +89,7 @@ impl Database {
}
};
if existing.is_some() {
+ tx.rollback().await?;
return Ok(None);
}
let row = sqlx::query_as::<_, WaitingItem>(
diff --git a/tests/foundry_test.rs b/tests/foundry_test.rs
index 5ae9257d..852f4066 100644
--- a/tests/foundry_test.rs
+++ b/tests/foundry_test.rs
@@ -614,6 +614,37 @@ async fn rollback_moves_one_lineage_back_in_one_step() {
assert_eq!(status, StatusCode::NOT_FOUND);
}
+#[tokio::test]
+async fn rolling_back_waits_for_another_write_instead_of_failing() {
+ use std::time::Instant;
+ let e = setup().await;
+ let a = bot(&e, "A").await;
+ let ex = verified(&e, &a, "release", 3).await;
+ let (v1, _) = stored_draft(&e, &a, "release", "Version one.", &ex[..2]).await;
+ person(&e, "POST", &format!("/api/skills/{}/approve", v1.id), Some(json!({}))).await;
+ let (v2, _) = stored_draft(&e, &a, "release", "Version two.", &ex[..2]).await;
+ person(&e, "POST", &format!("/api/skills/{}/approve", v2.id), Some(json!({}))).await;
+
+ // Another connection holds the write lock for 300 ms
+ let other = sqlx::sqlite::SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", e.state.config.data_dir.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 (status, v) = call(&e.app, "POST", &format!("/api/skills/{}/rollback", v1.id), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["status"], "enabled", "{v}");
+ assert!(started.elapsed() >= Duration::from_millis(250), "the lock was held during the rollback");
+ writer.await.unwrap();
+}
+
#[tokio::test]
async fn reads_of_the_review_queue_are_person_only() {
let e = setup().await;
diff --git a/tests/import_test.rs b/tests/import_test.rs
index 1f703d80..7b63ca0c 100644
--- a/tests/import_test.rs
+++ b/tests/import_test.rs
@@ -221,6 +221,31 @@ async fn apply_creates_bots_without_tools_pending_skills_and_paused_routines_the
assert_eq!((status, again["code"].as_str()), (StatusCode::CONFLICT, Some("already_undone")));
}
+#[tokio::test]
+async fn applying_waits_for_another_write_instead_of_failing() {
+ use std::time::{Duration, Instant};
+ let e = setup().await;
+ let (_, preview) = preview_file(&e.app, "kwant-bundle.json", &dflt()).await;
+
+ // Another connection holds the write lock for 300 ms
+ let other = sqlx::sqlite::SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", e.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 (status, applied) = apply(&e.app, &dflt(), &preview["bundle"], &[]).await;
+ assert_eq!(status, StatusCode::CREATED, "{applied}");
+ assert!(started.elapsed() >= Duration::from_millis(250), "the lock was held during the import");
+ writer.await.unwrap();
+}
+
#[tokio::test]
async fn name_clash_renames_and_never_overwrites() {
let e = setup().await;