| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use crate::constant::MAX_ERROR_CODE_LEN; |
| 13 | use crate::database::Database; |
| 14 | use crate::db::page::PagedList; |
| 15 | use crate::domain::rag_message::{ |
| 16 | RagContent, RagMessage, RagMessageId, RagMessageRole, RagMessageStatus, RagReply, |
| 17 | }; |
| 18 | use crate::domain::rag_thread::RagThreadId; |
| 19 | use crate::domain::timestamp::Timestamp; |
| 20 | use crate::domain::user::UserId; |
| 21 | use crate::error::AppError; |
| 22 | use sqlx::query_as; |
| 23 | use sqlx::types::Json; |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | async fn insert(db: &Database, message: RagMessage) -> Result<RagMessage, AppError> { |
| 40 | let inserted = query_as!( |
| 41 | RagMessage, |
| 42 | "WITH touch AS ( |
| 43 | UPDATE rag_thread SET updated_at = GREATEST($2, updated_at + 1) |
| 44 | WHERE id = $1 |
| 45 | RETURNING 1) |
| 46 | INSERT INTO rag_message (id, thread, user_id, role, content, status, \ |
| 47 | reply, error_code, created_at, completed_at) |
| 48 | SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11 |
| 49 | WHERE EXISTS (SELECT 1 FROM touch) |
| 50 | RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 51 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 52 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 53 | error_code AS \"error_code: String\", \ |
| 54 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"", |
| 55 | message.get_thread_id().uuid(), |
| 56 | Timestamp::now().as_millis(), |
| 57 | message.get_id().uuid(), |
| 58 | message.user_id.uuid(), |
| 59 | message.role.as_str(), |
| 60 | message.content.as_str(), |
| 61 | message.status.as_str(), |
| 62 | message.reply as _, |
| 63 | message.error_code, |
| 64 | message.created_at.as_millis(), |
| 65 | message.completed_at.map(|t| t.as_millis()), |
| 66 | ) |
| 67 | .fetch_optional(db) |
| 68 | .await?; |
| 69 | |
| 70 | |
| 71 | inserted.ok_or(AppError::NotFound) |
| 72 | } |
| 73 | |
| 74 | |
| 75 | |
| 76 | pub async fn append_user( |
| 77 | db: &Database, |
| 78 | thread: &RagThreadId, |
| 79 | user: &UserId, |
| 80 | content: RagContent, |
| 81 | ) -> Result<RagMessage, AppError> { |
| 82 | let now = Timestamp::now(); |
| 83 | insert( |
| 84 | db, |
| 85 | RagMessage { |
| 86 | id: RagMessageId::generate(), |
| 87 | thread: thread.clone(), |
| 88 | user_id: *user, |
| 89 | role: RagMessageRole::User, |
| 90 | content, |
| 91 | status: RagMessageStatus::Complete, |
| 92 | reply: None, |
| 93 | error_code: None, |
| 94 | created_at: now, |
| 95 | completed_at: Some(now), |
| 96 | }, |
| 97 | ) |
| 98 | .await |
| 99 | } |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | pub async fn append_pending_assistant( |
| 106 | db: &Database, |
| 107 | thread: &RagThreadId, |
| 108 | user: &UserId, |
| 109 | ) -> Result<RagMessage, AppError> { |
| 110 | insert( |
| 111 | db, |
| 112 | RagMessage { |
| 113 | id: RagMessageId::generate(), |
| 114 | thread: thread.clone(), |
| 115 | user_id: *user, |
| 116 | role: RagMessageRole::Assistant, |
| 117 | content: RagContent::empty(), |
| 118 | status: RagMessageStatus::Pending, |
| 119 | reply: None, |
| 120 | error_code: None, |
| 121 | created_at: Timestamp::now(), |
| 122 | completed_at: None, |
| 123 | }, |
| 124 | ) |
| 125 | .await |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | pub async fn list_for_thread( |
| 131 | db: &Database, |
| 132 | thread: &RagThreadId, |
| 133 | limit: Option<i64>, |
| 134 | offset: i64, |
| 135 | ) -> Result<(Vec<RagMessage>, i64), AppError> { |
| 136 | let (rows, total) = PagedList::new( |
| 137 | "rag_message WHERE thread = $1", |
| 138 | "ORDER BY created_at ASC, id ASC", |
| 139 | ) |
| 140 | .bind(thread.uuid()) |
| 141 | .run::<RagMessage>(limit, offset, db) |
| 142 | .await?; |
| 143 | Ok((rows.into_iter().map(RagMessage::projected).collect(), total)) |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | pub async fn list_tail( |
| 150 | db: &Database, |
| 151 | thread: &RagThreadId, |
| 152 | limit: usize, |
| 153 | ) -> Result<Vec<RagMessage>, AppError> { |
| 154 | let mut messages: Vec<RagMessage> = query_as!( |
| 155 | RagMessage, |
| 156 | "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 157 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 158 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 159 | error_code AS \"error_code: String\", \ |
| 160 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ |
| 161 | FROM rag_message WHERE thread = $1 \ |
| 162 | ORDER BY created_at DESC, id DESC LIMIT $2", |
| 163 | thread.uuid(), |
| 164 | limit as i64 |
| 165 | ) |
| 166 | .fetch_all(db) |
| 167 | .await?; |
| 168 | messages.reverse(); |
| 169 | Ok(messages) |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | pub async fn list_settled_tail( |
| 179 | db: &Database, |
| 180 | thread: &RagThreadId, |
| 181 | limit: usize, |
| 182 | ) -> Result<Vec<RagMessage>, AppError> { |
| 183 | let mut messages: Vec<RagMessage> = query_as!( |
| 184 | RagMessage, |
| 185 | "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 186 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 187 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 188 | error_code AS \"error_code: String\", \ |
| 189 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ |
| 190 | FROM rag_message WHERE thread = $1 \ |
| 191 | AND status = 'complete' AND content <> '' \ |
| 192 | ORDER BY created_at DESC, id DESC LIMIT $2", |
| 193 | thread.uuid(), |
| 194 | limit as i64 |
| 195 | ) |
| 196 | .fetch_all(db) |
| 197 | .await?; |
| 198 | messages.reverse(); |
| 199 | Ok(messages) |
| 200 | } |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | pub async fn prompt_of( |
| 211 | db: &Database, |
| 212 | id: &RagMessageId, |
| 213 | ) -> Result<Option<RagMessage>, AppError> { |
| 214 | let message = query_as!( |
| 215 | RagMessage, |
| 216 | "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 217 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 218 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 219 | error_code AS \"error_code: String\", \ |
| 220 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ |
| 221 | FROM rag_message WHERE id = $1", |
| 222 | id.uuid() |
| 223 | ) |
| 224 | .fetch_optional(db) |
| 225 | .await?; |
| 226 | Ok(message) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | pub async fn read_for( |
| 231 | db: &Database, |
| 232 | id: &RagMessageId, |
| 233 | user: &UserId, |
| 234 | ) -> Result<Option<RagMessage>, AppError> { |
| 235 | let message = query_as!( |
| 236 | RagMessage, |
| 237 | "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 238 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 239 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 240 | error_code AS \"error_code: String\", \ |
| 241 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ |
| 242 | FROM rag_message WHERE id = $1", |
| 243 | id.uuid() |
| 244 | ) |
| 245 | .fetch_optional(db) |
| 246 | .await?; |
| 247 | Ok(message |
| 248 | .filter(|message| &message.user_id == user) |
| 249 | .map(RagMessage::projected)) |
| 250 | } |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | pub async fn complete( |
| 258 | db: &Database, |
| 259 | id: &RagMessageId, |
| 260 | text: RagContent, |
| 261 | reply: Json<RagReply>, |
| 262 | ) -> Result<RagMessage, AppError> { |
| 263 | settle(db, id, Some(text), Some(reply), None).await |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | pub async fn fail( |
| 270 | db: &Database, |
| 271 | id: &RagMessageId, |
| 272 | error_code: &str, |
| 273 | ) -> Result<RagMessage, AppError> { |
| 274 | settle(db, id, None, None, Some(error_code)).await |
| 275 | } |
| 276 | |
| 277 | async fn settle( |
| 278 | db: &Database, |
| 279 | id: &RagMessageId, |
| 280 | text: Option<RagContent>, |
| 281 | reply: Option<Json<RagReply>>, |
| 282 | error_code: Option<&str>, |
| 283 | ) -> Result<RagMessage, AppError> { |
| 284 | let status = if text.is_some() { |
| 285 | RagMessageStatus::Complete |
| 286 | } else { |
| 287 | RagMessageStatus::Failed |
| 288 | }; |
| 289 | let settled = query_as!( |
| 290 | RagMessage, |
| 291 | "UPDATE rag_message SET content = $2, status = $3, reply = $4, \ |
| 292 | error_code = $5, completed_at = $6 \ |
| 293 | WHERE id = $1 AND status = 'pending' \ |
| 294 | RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \ |
| 295 | user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \ |
| 296 | status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \ |
| 297 | error_code AS \"error_code: String\", \ |
| 298 | created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"", |
| 299 | id.uuid(), |
| 300 | text.map(|t| t.as_str().to_string()).unwrap_or_default(), |
| 301 | status.as_str(), |
| 302 | reply as _, |
| 303 | error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()), |
| 304 | Timestamp::now().as_millis(), |
| 305 | ) |
| 306 | .fetch_optional(db) |
| 307 | .await?; |
| 308 | settled.ok_or(AppError::NotFound) |
| 309 | } |
| 310 | #[cfg(test)] |
| 311 | mod tests { |
| 312 | use super::*; |
| 313 | use crate::domain::rag_message::RagCitedFile; |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | async fn a_thread( |
| 319 | user: &str, |
| 320 | thread: &str, |
| 321 | ) -> (Database, crate::database::TestDatabases, UserId, RagThreadId) { |
| 322 | let (db, leases) = crate::database::init_test_db().await; |
| 323 | let user = UserId::from_key(user); |
| 324 | let thread = RagThreadId::from_key(thread); |
| 325 | sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'rag-fixture', 0)") |
| 326 | .bind(user.uuid()) |
| 327 | .execute(&db) |
| 328 | .await |
| 329 | .unwrap(); |
| 330 | sqlx::query( |
| 331 | "INSERT INTO rag_thread (id, owner, created_at, updated_at) \ |
| 332 | VALUES ($1, $2, 0, 0)", |
| 333 | ) |
| 334 | .bind(thread.uuid()) |
| 335 | .bind(user.uuid()) |
| 336 | .execute(&db) |
| 337 | .await |
| 338 | .unwrap(); |
| 339 | (db, leases, user, thread) |
| 340 | } |
| 341 | |
| 342 | fn a_reply() -> Json<RagReply> { |
| 343 | Json(RagReply { |
| 344 | abstained: false, |
| 345 | reason: String::new(), |
| 346 | citations: vec![RagCitedFile { |
| 347 | n: 1, |
| 348 | file: None, |
| 349 | pages: vec![12], |
| 350 | span_ids: vec!["s1".to_string()], |
| 351 | ders: Some("Fizik".to_string()), |
| 352 | }], |
| 353 | }) |
| 354 | } |
| 355 | |
| 356 | #[tokio::test] |
| 357 | async fn a_turns_two_rows_never_sort_inverted() { |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | let (db, _leases, user, thread) = a_thread( |
| 363 | "019732e3-7b00-7000-8000-00000000cafe", |
| 364 | "019732e3-7b00-7000-8000-00000000beef", |
| 365 | ) |
| 366 | .await; |
| 367 | const TURNS: usize = 200; |
| 368 | |
| 369 | for turn in 0..TURNS { |
| 370 | let content = RagContent::try_new(&format!("soru {turn}")).unwrap(); |
| 371 | append_user(&db, &thread, &user, content).await.unwrap(); |
| 372 | append_pending_assistant(&db, &thread, &user) |
| 373 | .await |
| 374 | .unwrap(); |
| 375 | } |
| 376 | |
| 377 | let (whole, _) = list_for_thread(&db, &thread, None, 0).await.unwrap(); |
| 378 | let tail = list_tail(&db, &thread, TURNS * 2).await.unwrap(); |
| 379 | for messages in [&whole, &tail] { |
| 380 | assert_eq!(messages.len(), TURNS * 2); |
| 381 | for (turn, pair) in messages.chunks(2).enumerate() { |
| 382 | assert_eq!(pair[0].get_role(), RagMessageRole::User, "turn {turn}"); |
| 383 | assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}")); |
| 384 | assert_eq!( |
| 385 | pair[1].get_role(), |
| 386 | RagMessageRole::Assistant, |
| 387 | "turn {turn}" |
| 388 | ); |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | #[tokio::test] |
| 397 | async fn a_completed_answer_carries_its_reply() { |
| 398 | let (db, _leases, user, thread) = a_thread( |
| 399 | "019732e3-7b00-7000-8000-00000000cafe", |
| 400 | "019732e3-7b00-7000-8000-00000000beef", |
| 401 | ) |
| 402 | .await; |
| 403 | let pending = append_pending_assistant(&db, &thread, &user).await.unwrap(); |
| 404 | assert!(pending.get_reply().is_none(), "nothing is known yet"); |
| 405 | assert_eq!(pending.get_status(), RagMessageStatus::Pending); |
| 406 | |
| 407 | let reply = a_reply(); |
| 408 | let settled = complete(&db, pending.get_id(), RagContent::try_new("F = m·a").unwrap(), reply) |
| 409 | .await |
| 410 | .expect("land the answer"); |
| 411 | assert_eq!(settled.get_status(), RagMessageStatus::Complete); |
| 412 | assert!(settled.get_completed_at().is_some()); |
| 413 | assert_eq!(settled.get_reply(), Some(&a_reply().0)); |
| 414 | |
| 415 | |
| 416 | |
| 417 | let stored = read_for(&db, pending.get_id(), &user) |
| 418 | .await |
| 419 | .unwrap() |
| 420 | .expect("settled row"); |
| 421 | assert_eq!(stored.get_reply(), Some(&a_reply().0)); |
| 422 | } |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | #[tokio::test] |
| 429 | async fn a_late_answer_cannot_overwrite_a_swept_row() { |
| 430 | let (db, _leases, user, thread) = a_thread( |
| 431 | "019732e3-7b00-7000-8000-00000000cafe", |
| 432 | "019732e3-7b00-7000-8000-00000000beef", |
| 433 | ) |
| 434 | .await; |
| 435 | let pending = append_pending_assistant(&db, &thread, &user).await.unwrap(); |
| 436 | sqlx::query( |
| 437 | "UPDATE rag_message SET status = 'failed', error_code = 'interrupted', \ |
| 438 | completed_at = $1 WHERE id = $2", |
| 439 | ) |
| 440 | .bind(Timestamp::now().as_millis()) |
| 441 | .bind(pending.get_id().uuid()) |
| 442 | .execute(&db) |
| 443 | .await |
| 444 | .unwrap(); |
| 445 | |
| 446 | let late = complete( |
| 447 | &db, |
| 448 | pending.get_id(), |
| 449 | RagContent::try_new("F = m·a").unwrap(), |
| 450 | a_reply(), |
| 451 | ) |
| 452 | .await; |
| 453 | assert!( |
| 454 | matches!(late, Err(AppError::NotFound)), |
| 455 | "a settled row takes no second answer: {late:?}" |
| 456 | ); |
| 457 | let stored = read_for(&db, pending.get_id(), &user) |
| 458 | .await |
| 459 | .unwrap() |
| 460 | .expect("swept row"); |
| 461 | assert_eq!(stored.get_status(), RagMessageStatus::Failed); |
| 462 | assert_eq!(stored.get_error_code(), Some("interrupted")); |
| 463 | assert!(stored.get_reply().is_none(), "the late reply was not stored"); |
| 464 | } |
| 465 | } |