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.

Bot delete: survive gone ids and an out-of-step search index, plain-words errors (#465)

Oleksandr Ivanchenkoff5b097adde4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e36af2ba..bb1b9f19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
- **A bot's Enter now submits forms.** When a bot pressed Enter in kwant's browser, the page saw the key but a search box or login form never sent. Enter, Tab, Backspace, Space, the arrows and single characters now go out as a real keyboard sends them. A key kwant can't press, such as `Control+a` or a whole word, is refused with a hint to type text instead. (#457)
- Every pull request now builds the web part of `docker compose up --build`, so a source build can't break unnoticed again as it did in 0.7.6. (#457)
+- **Deleting a bot no longer fails with "database error".** A team or channel the bot led could list a bot that no longer exists, or the chat search index could be out of step with the chat. Either one stopped the delete. kwant now skips the missing bot when it picks the new lead, and repairs the search index and tries again. If a delete still fails, the dialog says why in plain words. (#465)
## [Mac 0.7.7] - 2026-11-09
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 1aeb0c6f..c640c5e8 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -332,11 +332,37 @@ impl Database {
/// transaction. Channels and teams it led get another lead (`new_lead`, which must be in
/// the same space). What it wrote in shared channels stays, as the room's history; so does
/// the space's log of bot actions.
+ ///
+ /// When a chat search index is out of step with what it indexes (SQLite's
+ /// `SQLITE_CORRUPT_VTAB`, which the index's delete trigger raises), the delete is rolled
+ /// back, both search indexes are rebuilt from their tables and the delete runs once more.
pub async fn delete_kwant_and_history(&self, id: &str, new_lead: &str) -> Result<bool, DbError> {
- let mut tx = self.pool.begin().await?;
- let done = purge_kwant(&mut tx, id, new_lead).await?;
- tx.commit().await?;
- Ok(done)
+ match self.delete_kwant_once(id, new_lead).await {
+ Err(e) if sqlite_code(&e) == Some(SQLITE_CORRUPT_VTAB) => {
+ tracing::warn!(kwant_id = %id, error = %e, "a chat search index is out of step; rebuilding it and deleting the bot again");
+ if let Err(repair) = self.rebuild_search_indexes().await {
+ tracing::warn!(kwant_id = %id, error = %repair, "rebuilding the chat search indexes failed");
+ return Err(e);
+ }
+ self.delete_kwant_once(id, new_lead).await
+ }
+ done => done,
+ }
+ }
+
+ /// One attempt of [`Self::delete_kwant_and_history`], holding the write lock from the start.
+ async fn delete_kwant_once(&self, id: &str, new_lead: &str) -> Result<bool, DbError> {
+ let mut tx = self.begin_write().await?;
+ match purge_kwant(&mut tx, id, new_lead).await {
+ Ok(done) => {
+ tx.commit().await?;
+ Ok(done)
+ }
+ Err(e) => {
+ let _ = tx.rollback().await;
+ Err(e)
+ }
+ }
}
/// Removes a channel nobody has written in yet; `false` when it has messages or is #general.
@@ -393,9 +419,21 @@ pub(super) async fn purge_kwant(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, id
.fetch_all(&mut **tx)
.await?;
for (row_id, lead, members) in rows {
- let kept: Vec<String> =
+ // Ids of bots that no longer exist are dropped too: handing the lead to one would
+ // fail the delete on the lead's foreign key.
+ let listed: Vec<String> =
serde_json::from_str::<Vec<String>>(&members).unwrap_or_default().into_iter().filter(|m| m != id).collect();
- let lead = if lead == id { kept.first().cloned().unwrap_or_else(|| new_lead.to_string()) } else { lead };
+ let existing = existing_kwants(tx, &listed, &lead).await?;
+ let listed_len = listed.len();
+ let kept: Vec<String> = listed.into_iter().filter(|m| existing.contains(m)).collect();
+ if kept.len() != listed_len {
+ tracing::info!(table, row = %row_id, dropped = listed_len - kept.len(), "dropped ids of bots that no longer exist from a member list");
+ }
+ let lead = if lead == id || !existing.contains(&lead) {
+ kept.first().cloned().unwrap_or_else(|| new_lead.to_string())
+ } else {
+ lead
+ };
sqlx::query(&format!("UPDATE {table} SET member_kwants = ?, lead_kwant_id = ? WHERE id = ?"))
.bind(serde_json::to_string(&kept)?)
.bind(&lead)
@@ -407,3 +445,76 @@ pub(super) async fn purge_kwant(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, id
let done = sqlx::query("DELETE FROM kwants WHERE id = ?").bind(id).execute(&mut **tx).await?;
Ok(done.rows_affected() == 1)
}
+
+/// Which of `members` and `lead` are bots that exist.
+async fn existing_kwants(
+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
+ members: &[String],
+ lead: &str,
+) -> Result<std::collections::HashSet<String>, DbError> {
+ let wanted: Vec<&str> = members.iter().map(String::as_str).chain(std::iter::once(lead)).collect();
+ let rows: Vec<(String,)> = sqlx::query_as("SELECT id FROM kwants WHERE id IN (SELECT value FROM json_each(?))")
+ .bind(serde_json::to_string(&wanted)?)
+ .fetch_all(&mut **tx)
+ .await?;
+ Ok(rows.into_iter().map(|(id,)| id).collect())
+}
+
+/// SQLite's extended result code for "a virtual table is malformed": an external-content
+/// search index that is out of step with its table.
+pub(crate) const SQLITE_CORRUPT_VTAB: i32 = 267;
+
+/// The SQLite extended result code behind a database error, if there is one.
+pub(crate) fn sqlite_code(e: &DbError) -> Option<i32> {
+ match e {
+ DbError::Sqlx(sqlx::Error::Database(d)) => d.code().and_then(|c| c.parse().ok()),
+ _ => None,
+ }
+}
+
+/// What the Delete dialog says when deleting `name` failed: plain words, never SQL. The
+/// full error goes to the log.
+pub fn delete_failure_message(name: &str, e: &DbError) -> String {
+ delete_failure_for_code(name, sqlite_code(e))
+}
+
+fn delete_failure_for_code(name: &str, code: Option<i32>) -> String {
+ // The primary result code is the low byte of the extended one
+ let why = match code {
+ Some(SQLITE_CORRUPT_VTAB) => "its chat search index needed repair and kwant couldn't finish it. Restart kwant and try again",
+ Some(787) => "other saved data still points to it, or to a bot that no longer exists, so nothing was deleted. The details are in kwant's log",
+ Some(c) if c & 0xff == 11 || c & 0xff == 26 => "kwant's database file looks damaged. Quit kwant, back up the kwnt.db file and ask for help before trying again",
+ Some(c) if c & 0xff == 5 || c & 0xff == 6 => "kwant is busy saving something else. Try again in a moment",
+ Some(c) if c & 0xff == 13 => "the disk is full. Free some space and try again",
+ Some(c) if c & 0xff == 8 || c & 0xff == 10 || c & 0xff == 14 => "kwant can't write to its database file. Check the disk and its permissions, then try again",
+ _ => "kwant couldn't save the change, so nothing was deleted. The details are in kwant's log",
+ };
+ format!("Couldn't delete {name}: {why}.")
+}
+
+#[cfg(test)]
+mod delete_failure_tests {
+ use super::delete_failure_for_code;
+
+ #[test]
+ fn each_failure_has_plain_words() {
+ let say = |c| delete_failure_for_code("Architect", c);
+ assert!(say(Some(267)).contains("search index"));
+ assert!(say(Some(787)).contains("no longer exists"));
+ assert!(say(Some(787)).contains("nothing was deleted"));
+ assert!(say(Some(11)).contains("damaged"));
+ assert!(say(Some(5)).contains("busy"));
+ assert!(say(Some(517)).contains("busy"), "SQLITE_BUSY_SNAPSHOT");
+ assert!(say(Some(13)).contains("disk is full"));
+ assert!(say(Some(8)).contains("can't write"));
+ assert!(say(Some(1811)).contains("nothing was deleted"), "a trigger's RAISE");
+ assert!(say(None).contains("nothing was deleted"));
+ for c in [None, Some(1), Some(5), Some(8), Some(11), Some(13), Some(267), Some(787), Some(1811)] {
+ let m = say(c);
+ assert!(m.starts_with("Couldn't delete Architect: "), "{m}");
+ for word in ["database error", "SQL", "constraint", "malformed", "code"] {
+ assert!(!m.contains(word), "{m} has {word}");
+ }
+ }
+ }
+}
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index 0d966364..8d128a68 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -54,6 +54,9 @@ pub struct Memory {
pub updated_at: DateTime<Utc>,
}
+/// The external-content full-text indexes over chat messages and bot memories.
+const SEARCH_INDEXES: [&str; 2] = ["messages_fts", "kwant_memories_fts"];
+
impl Memory {
pub fn pinned(&self) -> bool {
self.pinned_by.is_some()
@@ -306,10 +309,45 @@ impl Database {
sqlx::query("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
.execute(&self.pool)
.await?;
+ } else {
+ self.repair_search_index_if_out_of_step("messages", "messages_fts").await?;
}
self.migrate_memory_pins().await
}
+ /// Rebuilds both chat search indexes from their tables, in one transaction. Reads every
+ /// message and memory, so it runs only when an index was found out of step.
+ pub(super) async fn rebuild_search_indexes(&self) -> Result<(), DbError> {
+ let mut tx = self.begin_write().await?;
+ for index in SEARCH_INDEXES {
+ if let Err(e) = sqlx::query(&format!("INSERT INTO {index}({index}) VALUES ('rebuild')")).execute(&mut *tx).await {
+ let _ = tx.rollback().await;
+ return Err(e.into());
+ }
+ }
+ tx.commit().await?;
+ tracing::info!("rebuilt the chat search indexes");
+ Ok(())
+ }
+
+ /// A start-up check that costs two counts: an external-content index keeps one size row
+ /// per indexed row, so a different count means rows were written or removed while its
+ /// triggers were missing, and the index is rebuilt. Text changed in place without the
+ /// index hearing about it isn't seen here; a delete that trips over it repairs it then
+ /// (see `delete_kwant_and_history`).
+ async fn repair_search_index_if_out_of_step(&self, table: &str, index: &str) -> Result<(), DbError> {
+ let (rows,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {table}")).fetch_one(&self.pool).await?;
+ let Ok((indexed,)) = sqlx::query_as::<_, (i64,)>(&format!("SELECT COUNT(*) FROM {index}_docsize")).fetch_one(&self.pool).await
+ else {
+ return Ok(());
+ };
+ if rows != indexed {
+ tracing::warn!(table, rows, indexed, "a chat search index is out of step with its table; rebuilding it");
+ sqlx::query(&format!("INSERT INTO {index}({index}) VALUES ('rebuild')")).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
/// Additive and reversible ([`MEMORY_PINS_DOWN`]): `pinned_by` and `imported` columns and a search index
/// over memories, filled from existing notes the first time. Older binaries ignore both, and
/// the triggers keep the index current for their writes too.
@@ -348,6 +386,8 @@ impl Database {
sqlx::query("INSERT INTO kwant_memories_fts(kwant_memories_fts) VALUES ('rebuild')")
.execute(&self.pool)
.await?;
+ } else {
+ self.repair_search_index_if_out_of_step("kwant_memories", "kwant_memories_fts").await?;
}
Ok(())
}
diff --git a/src/db/hires.rs b/src/db/hires.rs
index 5f59678f..a8dec6e6 100644
--- a/src/db/hires.rs
+++ b/src/db/hires.rs
@@ -399,31 +399,45 @@ impl Database {
Ok(space.map(|s| (s, role)))
}
- /// Adds a bot to a team and to the team's `team-<name>` channel.
+ /// Adds a bot to a team and to the team's `team-<name>` channel. The member lists are read
+ /// inside the write transaction: read before it, a bot deleted in between came back into
+ /// the list as an id of a bot that no longer exists. Ids of bots that no longer exist are
+ /// dropped, and a `kwant_id` that isn't a bot is not added.
pub async fn add_team_member(&self, team_id: &str, kwant_id: &str) -> Result<bool, DbError> {
- let Some(team) = self.get_team(team_id).await? else {
+ let mut tx = self.begin_write().await?;
+ let team: Option<(String, String, String)> = sqlx::query_as("SELECT name, space_id, member_kwants FROM teams WHERE id = ?")
+ .bind(team_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some((name, space_id, raw)) = team else {
+ tx.rollback().await?;
return Ok(false);
};
- let mut members: Vec<String> = serde_json::from_str(&team.member_kwants).unwrap_or_default();
- if !members.iter().any(|m| m == kwant_id) {
- members.push(kwant_id.to_string());
- }
- let json = serde_json::to_string(&members)?;
- let mut tx = self.pool.begin().await?;
- sqlx::query("UPDATE teams SET member_kwants = ? WHERE id = ?").bind(&json).bind(team_id).execute(&mut *tx).await?;
- let space = SpaceId::new(team.space_id.clone());
- let channel: Option<(String, String)> = match super::team_channel_id(&mut *tx, &space, &team.name).await? {
+ let space = SpaceId::new(space_id);
+ let channel: Option<(String, String)> = match super::team_channel_id(&mut *tx, &space, &name).await? {
Some(cid) => sqlx::query_as("SELECT id, member_kwants FROM channels WHERE id = ?").bind(cid).fetch_optional(&mut *tx).await?,
None => None,
};
- if let Some((cid, raw)) = channel {
- let mut cm: Vec<String> = serde_json::from_str(&raw).unwrap_or_default();
- if !cm.iter().any(|m| m == kwant_id) {
- cm.push(kwant_id.to_string());
+ let mut lists = vec![("teams", team_id.to_string(), raw)];
+ lists.extend(channel.map(|(cid, raw)| ("channels", cid, raw)));
+ for (table, row_id, raw) in lists {
+ let mut members: Vec<String> = serde_json::from_str(&raw).unwrap_or_default();
+ if !members.iter().any(|m| m == kwant_id) {
+ members.push(kwant_id.to_string());
}
- sqlx::query("UPDATE channels SET member_kwants = ? WHERE id = ?")
- .bind(serde_json::to_string(&cm)?)
- .bind(cid)
+ // Only bots that exist, in the order they were listed
+ let members: Vec<String> = sqlx::query_as::<_, (String,)>(
+ "SELECT value FROM json_each(?) WHERE value IN (SELECT id FROM kwants) ORDER BY key",
+ )
+ .bind(serde_json::to_string(&members)?)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .map(|(id,)| id)
+ .collect();
+ sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?"))
+ .bind(serde_json::to_string(&members)?)
+ .bind(&row_id)
.execute(&mut *tx)
.await?;
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index faf6248a..3bca93bc 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -883,6 +883,16 @@ impl Database {
}
match rows.as_slice() {
[(id, old)] => {
+ // Only the team's members that are still bots, so the chat never gets an
+ // id the next bot delete would hand the lead to
+ let (members,): (String,) = sqlx::query_as(
+ "SELECT COALESCE(json_group_array(value), '[]') FROM \
+ (SELECT value FROM json_each(CASE WHEN json_valid(?1) THEN ?1 ELSE '[]' END) \
+ WHERE value IN (SELECT id FROM kwants) ORDER BY key)",
+ )
+ .bind(&members)
+ .fetch_one(&self.pool)
+ .await?;
sqlx::query("UPDATE channels SET name = ?, lead_kwant_id = ?, member_kwants = ? WHERE id = ?")
.bind(&wanted)
.bind(&lead)
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 07e85168..fad85114 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -447,7 +447,12 @@ pub(super) async fn remove_bot(state: &AppState, id: &str) -> Response {
match state.db.delete_kwant_and_history(&id, &fallback.id).await {
Ok(true) => {}
Ok(false) => return api_error(StatusCode::NOT_FOUND, "bot not found"),
- Err(e) => return db_error(&e, ""),
+ Err(e) => {
+ // The dialog gets plain words; the SQLite message stays in the log
+ tracing::warn!(kwant_id = %id, name = %bot.name, error = %e, "deleting a bot failed");
+ let message = crate::db::bot_actions::delete_failure_message(&bot.name, &e);
+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "delete_failed", "message": message}))).into_response();
+ }
}
state.broker.forget_kwant(&id).await;
super::passwords::forget_deleted_owners(&state, &[&id]).await;
diff --git a/tests/bot_delete_repair_test.rs b/tests/bot_delete_repair_test.rs
new file mode 100644
index 00000000..e94a6bbd
--- /dev/null
+++ b/tests/bot_delete_repair_test.rs
@@ -0,0 +1,255 @@
+//! Deleting a bot from a database that is a little out of step (Oleks, 0.7.7 on Mac: the
+//! Delete dialog said only "database error").
+//! - h1: a channel or team the bot leads lists a bot that no longer exists. The lead used to go
+//! to that id and the delete failed on the lead's foreign key.
+//! - h3: the chat search index is out of step with the messages (or memories) it indexes. Its
+//! delete trigger failed with "database disk image is malformed" and the delete rolled back.
+//! - A delete that still fails says what happened in plain words, never SQL.
+//! - Where stale ids came from: a team member added while a bot was deleted, and a team chat
+//! relinked at start-up, no longer bring back ids of bots that don't exist.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::NewMessage, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use sqlx::SqlitePool;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+/// A second connection to the same file, for writing the broken states the app never writes.
+async fn raw(tmp: &TempDir) -> SqlitePool {
+ SqlitePool::connect(&format!("sqlite://{}", tmp.path().join("kwnt.db").display())).await.unwrap()
+}
+
+async fn call(app: &Router, state: &AppState, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {}", state.api_token.reveal()));
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+fn dm(kwant: &str, role: &str, text: &str) -> NewMessage {
+ NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(kwant.into()),
+ sender_role: role.into(),
+ sender_id: if role == "user" { "user".into() } else { kwant.into() },
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ }
+}
+
+/// Architect and the others in the default space, in the order the route picks a fallback lead.
+async fn architect_and_others(state: &AppState) -> (String, Vec<String>) {
+ let bots = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();
+ let architect = bots.iter().find(|k| k.name == "Architect").expect("the starter Architect").id.clone();
+ (architect.clone(), bots.into_iter().map(|k| k.id).filter(|id| *id != architect).collect())
+}
+
+async fn members(pool: &SqlitePool, table: &str, id: &str) -> (String, Vec<String>) {
+ let (lead, raw): (String, String) =
+ sqlx::query_as(&format!("SELECT lead_kwant_id, member_kwants FROM {table} WHERE id = ?")).bind(id).fetch_one(pool).await.unwrap();
+ (lead, serde_json::from_str(&raw).unwrap())
+}
+
+async fn assert_foreign_keys_hold(pool: &SqlitePool) {
+ let broken: Vec<(String, Option<i64>, String, i64)> = sqlx::query_as("PRAGMA foreign_key_check").fetch_all(pool).await.unwrap();
+ assert!(broken.is_empty(), "PRAGMA foreign_key_check: {broken:?}");
+}
+
+async fn assert_search_indexes_in_step(pool: &SqlitePool) {
+ for index in ["messages_fts", "kwant_memories_fts"] {
+ sqlx::query(&format!("INSERT INTO {index}({index}, rank) VALUES ('integrity-check', 1)"))
+ .execute(pool)
+ .await
+ .unwrap_or_else(|e| panic!("{index} is out of step: {e}"));
+ }
+}
+
+#[tokio::test]
+async fn h1_a_led_channel_and_team_listing_a_gone_bot_no_longer_block_the_delete() {
+ let (app, state, tmp) = setup().await;
+ let (architect, others) = architect_and_others(&state).await;
+ let next = others[0].clone();
+
+ // A channel Architect leads, and a team where it is the only bot left besides a gone one
+ let (s, v) = call(&app, &state, "POST", "/api/channels", Some(json!({"name": "plans", "description": null, "routing_mode": "auto", "lead_kwant_id": architect, "member_kwants": [architect, next]}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ let channel = v["id"].as_str().unwrap().to_string();
+ let (s, v) = call(&app, &state, "POST", "/api/teams", Some(json!({"name": "design", "lead_kwant_id": architect, "member_kwants": [architect]}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ let team = v["id"].as_str().unwrap().to_string();
+ state.db.insert_message(&dm(&architect, "user", "hello")).await.unwrap();
+
+ // The broken state: each lists a bot id that no longer exists right after Architect
+ let pool = raw(&tmp).await;
+ sqlx::query("UPDATE channels SET member_kwants = ? WHERE id = ?").bind(json!([architect, "gone-bot-id", next]).to_string()).bind(&channel).execute(&pool).await.unwrap();
+ sqlx::query("UPDATE teams SET member_kwants = ? WHERE id = ?").bind(json!([architect, "gone-bot-id"]).to_string()).bind(&team).execute(&pool).await.unwrap();
+
+ let (s, v) = call(&app, &state, "DELETE", &format!("/api/kwants/{architect}"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(state.db.get_kwant(&architect).await.unwrap().is_none());
+
+ // The lead went to the next bot that exists; the gone id is dropped from the list
+ assert_eq!(members(&pool, "channels", &channel).await, (next.clone(), vec![next.clone()]));
+ // Nobody left in the team: the space's fallback leads it
+ assert_eq!(members(&pool, "teams", &team).await, (others[0].clone(), vec![]));
+ assert_foreign_keys_hold(&pool).await;
+}
+
+#[tokio::test]
+async fn h3_a_search_index_out_of_step_is_rebuilt_and_the_delete_succeeds() {
+ let (app, state, tmp) = setup().await;
+ let (architect, others) = architect_and_others(&state).await;
+ for i in 0..17 {
+ state.db.insert_message(&dm(&architect, if i % 2 == 0 { "user" } else { "kwant" }, &format!("message {i} about the plan"))).await.unwrap();
+ }
+ state.db.insert_message(&dm(&others[0], "user", "a message that stays")).await.unwrap();
+ state.db.add_memory(&architect, "Oleks prefers short answers.", "user").await.unwrap();
+
+ // The text changes without the search indexes hearing about it (as if written while the
+ // update triggers were missing)
+ let pool = raw(&tmp).await;
+ for sql in [
+ "DROP TRIGGER messages_fts_au",
+ "DROP TRIGGER kwant_memories_fts_au",
+ ] {
+ sqlx::query(sql).execute(&pool).await.unwrap();
+ }
+ sqlx::query("UPDATE messages SET text = text || ' edited outside the index' WHERE direct_kwant_id = ?").bind(&architect).execute(&pool).await.unwrap();
+ sqlx::query("UPDATE kwant_memories SET text = text || ' edited outside the index' WHERE kwant_id = ?").bind(&architect).execute(&pool).await.unwrap();
+ assert!(
+ sqlx::query("INSERT INTO messages_fts(messages_fts, rank) VALUES ('integrity-check', 1)").execute(&pool).await.is_err(),
+ "the index is out of step before the delete"
+ );
+
+ let (s, v) = call(&app, &state, "DELETE", &format!("/api/kwants/{architect}"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(state.db.get_kwant(&architect).await.unwrap().is_none());
+ let (left,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages WHERE direct_kwant_id = ?").bind(&architect).fetch_one(&pool).await.unwrap();
+ assert_eq!(left, 0);
+ assert_eq!(state.db.list_messages(&others[0], 10).await.unwrap().len(), 1, "other chats stay");
+ assert_foreign_keys_hold(&pool).await;
+ assert_search_indexes_in_step(&pool).await;
+ let (hits,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages_fts WHERE messages_fts MATCH 'stays'").fetch_one(&pool).await.unwrap();
+ assert_eq!(hits, 1, "search still finds what is left");
+}
+
+#[tokio::test]
+async fn a_delete_that_still_fails_says_why_in_plain_words() {
+ let (app, state, tmp) = setup().await;
+ let (architect, _) = architect_and_others(&state).await;
+ state.db.insert_message(&dm(&architect, "user", "keep me")).await.unwrap();
+
+ // Something the delete can't get past, with SQL-ish text the dialog must not show
+ let pool = raw(&tmp).await;
+ sqlx::query("CREATE TRIGGER block_delete BEFORE DELETE ON kwants BEGIN SELECT RAISE(ABORT, 'secret sql text from kwants'); END")
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let (s, v) = call(&app, &state, "DELETE", &format!("/api/kwants/{architect}"), None).await;
+ assert_eq!(s, StatusCode::INTERNAL_SERVER_ERROR, "{v}");
+ assert_eq!(v["error"], "delete_failed");
+ let message = v["message"].as_str().unwrap();
+ assert!(message.starts_with("Couldn't delete Architect: "), "{message}");
+ assert!(message.contains("nothing was deleted"), "{message}");
+ for leak in ["database error", "secret", "sql", "SQL", "kwants", "RAISE", "code"] {
+ assert!(!message.contains(leak), "{message} shows {leak}");
+ }
+
+ // Rolled back whole: the bot and its chat are still there
+ assert!(state.db.get_kwant(&architect).await.unwrap().is_some());
+ assert_eq!(state.db.list_messages(&architect, 10).await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn adding_a_team_member_keeps_only_bots_that_exist() {
+ let (app, state, tmp) = setup().await;
+ let (architect, others) = architect_and_others(&state).await;
+ let (s, v) = call(&app, &state, "POST", "/api/teams", Some(json!({"name": "build", "lead_kwant_id": architect, "member_kwants": [architect]}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ let team = v["id"].as_str().unwrap().to_string();
+ let chat = state.db.team_channel(&SpaceId::default_space(), "build").await.unwrap().expect("the team's chat");
+
+ let pool = raw(&tmp).await;
+ for (table, id) in [("teams", &team), ("channels", &chat)] {
+ sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?")).bind(json!([architect, "gone-bot-id"]).to_string()).bind(id).execute(&pool).await.unwrap();
+ }
+
+ assert!(state.db.add_team_member(&team, &others[0]).await.unwrap());
+ assert!(state.db.add_team_member(&team, "not-a-bot").await.unwrap());
+ for (table, id) in [("teams", &team), ("channels", &chat)] {
+ assert_eq!(members(&pool, table, id).await.1, vec![architect.clone(), others[0].clone()], "{table}");
+ }
+ assert!(!state.db.add_team_member("no-such-team", &others[0]).await.unwrap());
+}
+
+#[tokio::test]
+async fn start_up_relinks_a_team_chat_without_ids_of_gone_bots_and_rebuilds_an_index_missing_rows() {
+ let (app, state, tmp) = setup().await;
+ let (architect, others) = architect_and_others(&state).await;
+ let (s, v) = call(&app, &state, "POST", "/api/teams", Some(json!({"name": "ops", "lead_kwant_id": architect, "member_kwants": [architect, others[0]]}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ let team = v["id"].as_str().unwrap().to_string();
+ let chat = state.db.team_channel(&SpaceId::default_space(), "ops").await.unwrap().expect("the team's chat");
+
+ let pool = raw(&tmp).await;
+ // A chat that lost its exact name, a team listing a gone bot, and a message written while
+ // the index's insert trigger was missing
+ sqlx::query("UPDATE channels SET name = 'TEAM-OPS' WHERE id = ?").bind(&chat).execute(&pool).await.unwrap();
+ sqlx::query("UPDATE teams SET member_kwants = ? WHERE id = ?").bind(json!([architect, "gone-bot-id", others[0]]).to_string()).bind(&team).execute(&pool).await.unwrap();
+ sqlx::query("DROP TRIGGER messages_fts_ai").execute(&pool).await.unwrap();
+ state.db.insert_message(&dm(&architect, "user", "written while the index was deaf")).await.unwrap();
+ let (rows,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages").fetch_one(&pool).await.unwrap();
+ let (indexed,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages_fts_docsize").fetch_one(&pool).await.unwrap();
+ assert_ne!(rows, indexed);
+ pool.close().await;
+ drop((app, state));
+
+ let db = Database::init(tmp.path()).await.unwrap();
+ let pool = raw(&tmp).await;
+ let (name, lead, raw_members): (String, String, String) =
+ sqlx::query_as("SELECT name, lead_kwant_id, member_kwants FROM channels WHERE id = ?").bind(&chat).fetch_one(&pool).await.unwrap();
+ assert_eq!(name, "team-ops");
+ assert_eq!(lead, architect);
+ assert_eq!(serde_json::from_str::<Vec<String>>(&raw_members).unwrap(), vec![architect.clone(), others[0].clone()]);
+ let (indexed,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages_fts_docsize").fetch_one(&pool).await.unwrap();
+ assert_eq!(indexed, rows, "the index was rebuilt");
+ assert_search_indexes_in_step(&pool).await;
+ let (hits,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages_fts WHERE messages_fts MATCH 'deaf'").fetch_one(&pool).await.unwrap();
+ assert_eq!(hits, 1);
+ drop(db);
+}