forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

rag_message.rs316 lines, 11.3 KiBHistoryRawDownload
1//! One turn of a RAG thread — the row shape and its read-time presentation.
2//! `user_id` is duplicated from the thread onto every message so an ownership
3//! check is one read, with no join.
4//!
5//! Persistence lives in [`crate::db::rag_message`]: the assistant's row is
6//! written `pending` *before* the AI call and flipped to `complete` or
7//! `failed` by the task that owns the bridge round trip, and a read projects a
8//! long-stale `pending` as failed without writing
9//! ([`RagMessage::projected`]) — the durable repair for a dead process happens
10//! once, at mint, in `database.rs`'s school migration sweep.
11//!
12//! What separates this row from the chatbot's is `reply`: a RAG answer is
13//! stored with the service's own JSON — whether it abstained, why, and which
14//! passages it cited — so a reader can open the evidence behind the text. A
15//! failed or pending turn stores none.
16
17use crate::constant::{MAX_CHATBOT_MESSAGE_LEN, RAG_PENDING_STALE_SECS, STALE_ERROR_CODE};
18use crate::domain::monotonic_id::next_uuid;
19use crate::domain::rag_thread::RagThreadId;
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::UserId;
22use crate::error::ValidationError;
23use crate::validate::validate_required;
24use serde::{Deserialize, Serialize};
25use sqlx::types::Json;
26
27#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
28#[sqlx(transparent)]
29pub struct RagMessageId(uuid::Uuid);
30
31impl RagMessageId {
32 /// Mints in write order. Unlike a plain random UUID, whose random low bits
33 /// sort arbitrarily among ids minted in the same millisecond, the
34 /// process-wide context increments — so the `id` tie-break in the
35 /// `ORDER BY` of
36 /// [`list_for_thread`](crate::db::rag_message::list_for_thread) /
37 /// [`list_tail`](crate::db::rag_message::list_tail) is the
38 /// order the rows were written. The user prompt and the assistant row one
39 /// POST writes back-to-back routinely share a millisecond, and a random
40 /// tie-break there renders the answer *above* its own question — and
41 /// hands the AI service a `[assistant, user]` history, breaking the
42 /// oldest-first contract.
43 pub fn generate() -> Self {
44 Self(next_uuid())
45 }
46
47 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
48 /// cannot take the newtype. Static `query!` binds take `self` directly.
49 pub fn uuid(&self) -> uuid::Uuid {
50 self.0
51 }
52
53 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
54 /// which matches no row.
55 pub fn from_key(key: &str) -> Self {
56 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
57 }
58
59 pub fn key(&self) -> String {
60 self.0.to_string()
61 }
62}
63
64/// Who said a turn. Stored as the bare lowercase string the `role` column's
65/// CHECK allows; a value the enum doesn't know comes back as a decode error,
66/// never a panic.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
68#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
69pub enum RagMessageRole {
70 User,
71 Assistant,
72}
73
74impl RagMessageRole {
75 /// The wire/storage form. Must stay in lockstep with `rename_all`.
76 pub fn as_str(self) -> &'static str {
77 match self {
78 RagMessageRole::User => "user",
79 RagMessageRole::Assistant => "assistant",
80 }
81 }
82}
83
84/// Where an assistant turn is in its lifecycle. A user turn is born
85/// `Complete` — nothing is ever awaited for it.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
87#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
88pub enum RagMessageStatus {
89 Pending,
90 Complete,
91 Failed,
92}
93
94impl RagMessageStatus {
95 pub fn as_str(self) -> &'static str {
96 match self {
97 RagMessageStatus::Pending => "pending",
98 RagMessageStatus::Complete => "complete",
99 RagMessageStatus::Failed => "failed",
100 }
101 }
102}
103
104/// One turn's text. The hard ceiling only, and the chatbot's
105/// ([`MAX_CHATBOT_MESSAGE_LEN`]): a question is a pasted prompt in either
106/// nest, and the school-adjustable `max_chatbot_message_len` is the web
107/// layer's to enforce, below this.
108#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
109#[sqlx(transparent)]
110pub struct RagContent(String);
111
112impl RagContent {
113 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
114 validate_required("content", value, MAX_CHATBOT_MESSAGE_LEN)?;
115 Ok(Self(value.to_string()))
116 }
117
118 /// The placeholder a `pending` assistant row carries until its answer
119 /// lands. Crate-visible: only the persistence layer writes it, for the
120 /// reserved row before the answer exists.
121 pub(crate) fn empty() -> Self {
122 Self(String::new())
123 }
124
125 pub fn as_str(&self) -> &str {
126 &self.0
127 }
128}
129
130/// One passage an answer drew on, as stored on the row. `n` is the marker the
131/// answer text points at (`[N]` resolves to the citation whose `n` is `N`);
132/// `file` is the `course_note_file` record key the service's `doc_id` was
133/// resolved through, absent while no file claims that document. Stored as
134/// JSON — this is the service's shape, kept, not re-derived.
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136pub struct RagCitedFile {
137 pub n: u32,
138 pub file: Option<String>,
139 pub pages: Vec<i64>,
140 pub span_ids: Vec<String>,
141 pub ders: Option<String>,
142}
143
144/// A RAG answer besides its text: whether the service declined to answer
145/// rather than answering, why, and the passages it drew on. Stored in the
146/// message's `reply` column, so a settled turn's evidence survives the
147/// request that produced it.
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149pub struct RagReply {
150 /// A true value is a complete, successful turn — the service chose not to
151 /// answer — not a failure, and `reason` says why.
152 pub abstained: bool,
153 /// The abstention's short machine code (`""` on an ordinary answer).
154 pub reason: String,
155 pub citations: Vec<RagCitedFile>,
156}
157
158#[derive(Debug, Clone, sqlx::FromRow)]
159pub struct RagMessage {
160 pub(crate) id: RagMessageId,
161 pub(crate) thread: RagThreadId,
162 pub(crate) user_id: UserId,
163 pub(crate) role: RagMessageRole,
164 pub(crate) status: RagMessageStatus,
165 pub(crate) content: RagContent,
166 /// The service's answer beside the text; `None` on a pending row, on a
167 /// failed one, and on every user turn.
168 pub(crate) reply: Option<Json<RagReply>>,
169 pub(crate) error_code: Option<String>,
170 pub(crate) created_at: Timestamp,
171 pub(crate) completed_at: Option<Timestamp>,
172}
173
174impl RagMessage {
175 pub fn get_id(&self) -> &RagMessageId {
176 &self.id
177 }
178
179 pub fn get_thread_id(&self) -> &RagThreadId {
180 &self.thread
181 }
182
183 pub fn get_user_id(&self) -> &UserId {
184 &self.user_id
185 }
186
187 pub fn get_role(&self) -> RagMessageRole {
188 self.role
189 }
190
191 pub fn get_content(&self) -> &RagContent {
192 &self.content
193 }
194
195 pub fn get_status(&self) -> RagMessageStatus {
196 self.status
197 }
198
199 pub fn get_reply(&self) -> Option<&RagReply> {
200 self.reply.as_ref().map(|reply| &reply.0)
201 }
202
203 pub fn get_error_code(&self) -> Option<&str> {
204 self.error_code.as_deref()
205 }
206
207 pub fn get_created_at(&self) -> Timestamp {
208 self.created_at
209 }
210
211 pub fn get_completed_at(&self) -> Option<Timestamp> {
212 self.completed_at
213 }
214
215 /// A row still `pending` past [`RAG_PENDING_STALE_SECS`] has lost the task
216 /// that owed it an answer; present it as failed.
217 ///
218 /// Read-time projection, not a lazy write-back: the read paths (poll loop,
219 /// thread load) run on every page and must not write, a write-back would
220 /// race the answering task that is merely slow — closing the door on a
221 /// reply that is still coming — and the durable repair for the real cause
222 /// (a dead process) already happens once, at mint. The stored row stays
223 /// truthful; only the answer handed to the caller is projected.
224 pub(crate) fn projected(mut self) -> Self {
225 let stale_at = self.created_at.as_millis() + RAG_PENDING_STALE_SECS * 1_000;
226 if self.status == RagMessageStatus::Pending && Timestamp::now().as_millis() > stale_at {
227 self.status = RagMessageStatus::Failed;
228 self.error_code = Some(STALE_ERROR_CODE.to_string());
229 }
230 self
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 #[tokio::test]
239 async fn content_is_required_and_capped() {
240 assert!(RagContent::try_new("").is_err());
241 assert!(RagContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN)).is_ok());
242 assert!(RagContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err());
243 }
244
245 /// The `role`/`status` columns are `TEXT` with CHECKs listing exactly
246 /// these spellings — queries match on them, so the storage form may not
247 /// drift from `as_str` (which `rename_all` mirrors).
248 #[test]
249 fn role_and_status_spellings_are_frozen() {
250 assert_eq!(RagMessageRole::User.as_str(), "user");
251 assert_eq!(RagMessageRole::Assistant.as_str(), "assistant");
252 assert_eq!(RagMessageStatus::Pending.as_str(), "pending");
253 assert_eq!(RagMessageStatus::Complete.as_str(), "complete");
254 assert_eq!(RagMessageStatus::Failed.as_str(), "failed");
255 }
256
257 /// The reply is stored as JSONB and handed to readers verbatim, so its key
258 /// names are a wire contract: a rename here would silently change what a
259 /// stored answer still says to every client (and the frontend is not the
260 /// thing that moves).
261 #[test]
262 fn a_reply_serializes_under_the_keys_a_reader_reads() {
263 let reply = RagReply {
264 abstained: false,
265 reason: String::new(),
266 citations: vec![RagCitedFile {
267 n: 1,
268 file: Some("019732e3-7b00-7000-8000-00000000f11e".to_string()),
269 pages: vec![3],
270 span_ids: vec!["s1".to_string()],
271 ders: Some("Fizik".to_string()),
272 }],
273 };
274 assert_eq!(
275 serde_json::to_value(&reply).unwrap(),
276 serde_json::json!({
277 "abstained": false,
278 "reason": "",
279 "citations": [{
280 "n": 1,
281 "file": "019732e3-7b00-7000-8000-00000000f11e",
282 "pages": [3],
283 "span_ids": ["s1"],
284 "ders": "Fizik",
285 }],
286 })
287 );
288 }
289
290 #[tokio::test]
291 async fn stale_pending_projects_as_failed() {
292 let aged = |secs: i64| {
293 RagMessage {
294 id: RagMessageId::generate(),
295 thread: RagThreadId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"),
296 user_id: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"),
297 role: RagMessageRole::Assistant,
298 content: RagContent::empty(),
299 status: RagMessageStatus::Pending,
300 reply: None,
301 error_code: None,
302 created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000),
303 completed_at: None,
304 }
305 .projected()
306 };
307
308 let fresh = aged(1);
309 assert_eq!(fresh.get_status(), RagMessageStatus::Pending);
310 assert_eq!(fresh.get_error_code(), None);
311
312 let stale = aged(RAG_PENDING_STALE_SECS + 1);
313 assert_eq!(stale.get_status(), RagMessageStatus::Failed);
314 assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE));
315 }
316}