forge
Explore
Log in

Don't you dare go Hollow

The /rag nest — threads, answers with citations, and scope derived from the caller's instances

Browse files at this commit

39f97e49b252c0d8daaf643b5a23ee075437a48aAhmet Kaan GümüşParent: 712ff31a61e0a6
  • feat
    • the /rag nest — threads, answers with citations, and scope derived from the caller's instances
Show full message
✨ feat: the /rag nest — threads, answers with citations, and scope derived from the caller's instances

Merges lane/rag-nest. A separate nest and tables (rag_thread, rag_message)
over a new rag.chat capability: every answer is stored verbatim (abstained,
reason, citations resolved to the course-note file the asker may view), the
scope sent to the service is the caller's (sinif, ders) pairs, and the school's
existing AI caps and a new per-user tier govern it. course_note_file gains
rag_doc_id so a citation's corpus doc id finds its PDF.

66 changed files +5061 -229

.env.examplemodified+6 -0
@@ -44,6 +44,12 @@ RUST_LOG=info,hezarfen_backend=debug
44 # another's. 0 disables it, like the tiers above.44 # another's. 0 disables it, like the tiers above.
45 # RATE_LIMIT_CHATBOT_PER_MINUTE=2045 # RATE_LIMIT_CHATBOT_PER_MINUTE=20
46 46
47+# RAG messages per minute, per USER — the same shape as the chatbot tier, and
48+# with a lower default for the same reason it exists: every message spends a
49+# retrieval over the course-note corpus before it generates anything. 0
50+# disables it.
51+# RATE_LIMIT_RAG_PER_MINUTE=6
52+
47 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP53 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP
48 # peer address. Enable ONLY behind a reverse proxy that appends the client IP54 # peer address. Enable ONLY behind a reverse proxy that appends the client IP
49 # to that header — otherwise the header is client-forged and limits are55 # to that header — otherwise the header is client-forged and limits are
.sqlx/query-2af8e5e68c35e70260a4d65a5e6b3c43ce67f0b8475264e32d74f178b20f4aec.jsonadded+137 -0
@@ -0,0 +1,137 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", error_code AS \"error_code: String\", created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" FROM rag_message WHERE thread = $1 AND status = 'complete' AND content <> '' ORDER BY created_at DESC, id DESC LIMIT $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagMessageId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_message",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "thread: RagThreadId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_message",
24+ "name": "thread"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "user_id: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_message",
35+ "name": "user_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "role: RagMessageRole",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_message",
46+ "name": "role"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: RagContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_message",
57+ "name": "content"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "status: RagMessageStatus",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "rag_message",
68+ "name": "status"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "reply: Json<RagReply>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "rag_message",
79+ "name": "reply"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code: String",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "rag_message",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "created_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "rag_message",
101+ "name": "created_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "completed_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "rag_message",
112+ "name": "completed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid",
120+ "Int8"
121+ ]
122+ },
123+ "nullable": [
124+ false,
125+ false,
126+ false,
127+ false,
128+ false,
129+ false,
130+ true,
131+ true,
132+ false,
133+ true
134+ ]
135+ },
136+ "hash": "2af8e5e68c35e70260a4d65a5e6b3c43ce67f0b8475264e32d74f178b20f4aec"
137+}
.sqlx/query-49f0e5053651cadafecb57ae7f2767887f635fda35c75c3d8fc1f884542db30f.jsonadded+80 -0
@@ -0,0 +1,80 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH seat AS (\n UPDATE app_user SET rag_thread_count = rag_thread_count + 1\n WHERE id = $1\n AND rag_thread_count < COALESCE(\n (SELECT max_chatbot_threads FROM settings WHERE id = 'school'),\n $2)\n RETURNING 1)\n INSERT INTO rag_thread (id, owner, title, created_at, updated_at)\n SELECT $3, $1, $4, $5, $5\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagThreadId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_thread",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "owner: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_thread",
24+ "name": "owner"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: RagThreadTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_thread",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_thread",
46+ "name": "created_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "updated_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_thread",
57+ "name": "updated_at"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid",
65+ "Int8",
66+ "Uuid",
67+ "Text",
68+ "Int8"
69+ ]
70+ },
71+ "nullable": [
72+ false,
73+ false,
74+ true,
75+ false,
76+ false
77+ ]
78+ },
79+ "hash": "49f0e5053651cadafecb57ae7f2767887f635fda35c75c3d8fc1f884542db30f"
80+}
.sqlx/query-6dbd932d776c792c2f44d8c05f52decc9e249bca5f40e7c05ad0501bd7a01199.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_message WHERE thread = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "6dbd932d776c792c2f44d8c05f52decc9e249bca5f40e7c05ad0501bd7a01199"
14+}
.sqlx/query-7eaec3c4c6985612a3cfee56a55788cd506183d68c31be80cd23700386f33900.jsonadded+136 -0
@@ -0,0 +1,136 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", error_code AS \"error_code: String\", created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" FROM rag_message WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagMessageId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_message",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "thread: RagThreadId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_message",
24+ "name": "thread"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "user_id: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_message",
35+ "name": "user_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "role: RagMessageRole",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_message",
46+ "name": "role"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: RagContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_message",
57+ "name": "content"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "status: RagMessageStatus",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "rag_message",
68+ "name": "status"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "reply: Json<RagReply>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "rag_message",
79+ "name": "reply"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code: String",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "rag_message",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "created_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "rag_message",
101+ "name": "created_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "completed_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "rag_message",
112+ "name": "completed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid"
120+ ]
121+ },
122+ "nullable": [
123+ false,
124+ false,
125+ false,
126+ false,
127+ false,
128+ false,
129+ true,
130+ true,
131+ false,
132+ true
133+ ]
134+ },
135+ "hash": "7eaec3c4c6985612a3cfee56a55788cd506183d68c31be80cd23700386f33900"
136+}
.sqlx/query-803a67a44ed50f647e4510b9b6395fe9220e55e90de00a5bd097dbaef58084f3.jsonadded+76 -0
@@ -0,0 +1,76 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_thread WHERE id = $1 RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagThreadId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_thread",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "owner: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_thread",
24+ "name": "owner"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: RagThreadTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_thread",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_thread",
46+ "name": "created_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "updated_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_thread",
57+ "name": "updated_at"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid"
65+ ]
66+ },
67+ "nullable": [
68+ false,
69+ false,
70+ true,
71+ false,
72+ false
73+ ]
74+ },
75+ "hash": "803a67a44ed50f647e4510b9b6395fe9220e55e90de00a5bd097dbaef58084f3"
76+}
.sqlx/query-8fa6da5726fc2b39c663989c5ab8c49ce962509f6bcd5d3c7b1f2c972fda5c6d.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE course_note_file SET rag_doc_id = $2 WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "8fa6da5726fc2b39c663989c5ab8c49ce962509f6bcd5d3c7b1f2c972fda5c6d"
15+}
.sqlx/query-af1ff99a75be6844f4af778ce494b772f61dd6dc26d09cb25ac24607ce8d29bd.jsonadded+76 -0
@@ -0,0 +1,76 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM rag_thread WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagThreadId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_thread",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "owner: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_thread",
24+ "name": "owner"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: RagThreadTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_thread",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_thread",
46+ "name": "created_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "updated_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_thread",
57+ "name": "updated_at"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid"
65+ ]
66+ },
67+ "nullable": [
68+ false,
69+ false,
70+ true,
71+ false,
72+ false
73+ ]
74+ },
75+ "hash": "af1ff99a75be6844f4af778ce494b772f61dd6dc26d09cb25ac24607ce8d29bd"
76+}
.sqlx/query-b0e320bd4fbd99b17fabf93fc9f54f6162a792c3c84b3b6ec8c8abbf44a7452a.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE app_user SET rag_thread_count = GREATEST(rag_thread_count - 1, 0) WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "b0e320bd4fbd99b17fabf93fc9f54f6162a792c3c84b3b6ec8c8abbf44a7452a"
14+}
.sqlx/query-baaf754ef93c6875fa09bddaced80784c735c4f26ff06ad504cf14fb5e8cf1d3.jsonadded+78 -0
@@ -0,0 +1,78 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE rag_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) WHERE id = $1 RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagThreadId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_thread",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "owner: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_thread",
24+ "name": "owner"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: RagThreadTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_thread",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "created_at: Timestamp",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_thread",
46+ "name": "created_at"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "updated_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_thread",
57+ "name": "updated_at"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid",
65+ "Text",
66+ "Int8"
67+ ]
68+ },
69+ "nullable": [
70+ false,
71+ false,
72+ true,
73+ false,
74+ false
75+ ]
76+ },
77+ "hash": "baaf754ef93c6875fa09bddaced80784c735c4f26ff06ad504cf14fb5e8cf1d3"
78+}
.sqlx/query-d8b553ba9c3c9a9365ead2c4206ceae4d1df0e7ba61dfb7b6784d867f90af7aa.jsonadded+76 -0
@@ -0,0 +1,76 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: CourseNoteFileId\",\n course_note AS \"course_note: CourseNoteId\", name AS \"name: FileName\",\n content_type AS \"content_type: FileContentType\", size FROM course_note_file\n WHERE rag_doc_id = $1 ORDER BY id",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: CourseNoteFileId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_note_file",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "course_note: CourseNoteId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_note_file",
24+ "name": "course_note"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "name: FileName",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "course_note_file",
35+ "name": "name"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "content_type: FileContentType",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "course_note_file",
46+ "name": "content_type"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "size",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "course_note_file",
57+ "name": "size"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Text"
65+ ]
66+ },
67+ "nullable": [
68+ false,
69+ false,
70+ false,
71+ false,
72+ false
73+ ]
74+ },
75+ "hash": "d8b553ba9c3c9a9365ead2c4206ceae4d1df0e7ba61dfb7b6784d867f90af7aa"
76+}
.sqlx/query-da9e74570ede58ed1f362c7136d4126a07cab2b67dbb8dd5bf66975409273384.jsonadded+137 -0
@@ -0,0 +1,137 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", error_code AS \"error_code: String\", created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" FROM rag_message WHERE thread = $1 ORDER BY created_at DESC, id DESC LIMIT $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagMessageId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_message",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "thread: RagThreadId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_message",
24+ "name": "thread"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "user_id: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_message",
35+ "name": "user_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "role: RagMessageRole",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_message",
46+ "name": "role"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: RagContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_message",
57+ "name": "content"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "status: RagMessageStatus",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "rag_message",
68+ "name": "status"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "reply: Json<RagReply>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "rag_message",
79+ "name": "reply"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code: String",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "rag_message",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "created_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "rag_message",
101+ "name": "created_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "completed_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "rag_message",
112+ "name": "completed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid",
120+ "Int8"
121+ ]
122+ },
123+ "nullable": [
124+ false,
125+ false,
126+ false,
127+ false,
128+ false,
129+ false,
130+ true,
131+ true,
132+ false,
133+ true
134+ ]
135+ },
136+ "hash": "da9e74570ede58ed1f362c7136d4126a07cab2b67dbb8dd5bf66975409273384"
137+}
.sqlx/query-dccb4d0bde914495cb2d55fdc176554d69cdebf8d2d7d70b67b06033fe775f1b.jsonadded+146 -0
@@ -0,0 +1,146 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH touch AS (\n UPDATE rag_thread SET updated_at = GREATEST($2, updated_at + 1)\n WHERE id = $1\n RETURNING 1)\n INSERT INTO rag_message (id, thread, user_id, role, content, status, reply, error_code, created_at, completed_at)\n SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11\n WHERE EXISTS (SELECT 1 FROM touch)\n RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", error_code AS \"error_code: String\", created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagMessageId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_message",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "thread: RagThreadId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_message",
24+ "name": "thread"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "user_id: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_message",
35+ "name": "user_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "role: RagMessageRole",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_message",
46+ "name": "role"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: RagContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_message",
57+ "name": "content"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "status: RagMessageStatus",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "rag_message",
68+ "name": "status"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "reply: Json<RagReply>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "rag_message",
79+ "name": "reply"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code: String",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "rag_message",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "created_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "rag_message",
101+ "name": "created_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "completed_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "rag_message",
112+ "name": "completed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid",
120+ "Int8",
121+ "Uuid",
122+ "Uuid",
123+ "Text",
124+ "Text",
125+ "Text",
126+ "Jsonb",
127+ "Text",
128+ "Int8",
129+ "Int8"
130+ ]
131+ },
132+ "nullable": [
133+ false,
134+ false,
135+ false,
136+ false,
137+ false,
138+ false,
139+ true,
140+ true,
141+ false,
142+ true
143+ ]
144+ },
145+ "hash": "dccb4d0bde914495cb2d55fdc176554d69cdebf8d2d7d70b67b06033fe775f1b"
146+}
.sqlx/query-deab46f003d9670e1d3ee565904ecbce26d35538acde51805415caa6f75d9e77.jsonadded+23 -0
@@ -0,0 +1,23 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT count(*) AS threads FROM rag_thread WHERE owner = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "threads",
9+ "type_info": "Int8",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid"
16+ ]
17+ },
18+ "nullable": [
19+ null
20+ ]
21+ },
22+ "hash": "deab46f003d9670e1d3ee565904ecbce26d35538acde51805415caa6f75d9e77"
23+}
.sqlx/query-f32e4625f22f3b3b8d7db1da34d98ad18e0faffd797f04af1c590e08d598cd27.jsonadded+141 -0
@@ -0,0 +1,141 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE rag_message SET content = $2, status = $3, reply = $4, error_code = $5, completed_at = $6 WHERE id = $1 AND status = 'pending' RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", error_code AS \"error_code: String\", created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: RagMessageId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_message",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "thread: RagThreadId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_message",
24+ "name": "thread"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "user_id: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "rag_message",
35+ "name": "user_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "role: RagMessageRole",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "rag_message",
46+ "name": "role"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "content: RagContent",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "rag_message",
57+ "name": "content"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "status: RagMessageStatus",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "rag_message",
68+ "name": "status"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "reply: Json<RagReply>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "rag_message",
79+ "name": "reply"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "error_code: String",
86+ "type_info": "Text",
87+ "origin": {
88+ "Table": {
89+ "table": "rag_message",
90+ "name": "error_code"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "created_at: Timestamp",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "rag_message",
101+ "name": "created_at"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "completed_at: Timestamp",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "rag_message",
112+ "name": "completed_at"
113+ }
114+ }
115+ }
116+ ],
117+ "parameters": {
118+ "Left": [
119+ "Uuid",
120+ "Text",
121+ "Text",
122+ "Jsonb",
123+ "Text",
124+ "Int8"
125+ ]
126+ },
127+ "nullable": [
128+ false,
129+ false,
130+ false,
131+ false,
132+ false,
133+ false,
134+ true,
135+ true,
136+ false,
137+ true
138+ ]
139+ },
140+ "hash": "f32e4625f22f3b3b8d7db1da34d98ad18e0faffd797f04af1c590e08d598cd27"
141+}
README.mdmodified+11 -1
@@ -720,7 +720,7 @@ drift from it**, which is enforced rather than asked for:
720 and fails unless each one is either referenced by `src/web/limits.rs` or720 and fails unless each one is either referenced by `src/web/limits.rs` or
721 listed as a deliberate exclusion *with a reason*. A new constant breaks the721 listed as a deliberate exclusion *with a reason*. A new constant breaks the
722 suite until someone decides, consciously, whether clients need it.722 suite until someone decides, consciously, whether clients need it.
723-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 219 published723+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 222 published
724 bounds back out of the emitted JSON, and asserts each equals its constant.724 bounds back out of the emitted JSON, and asserts each equals its constant.
725 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal725 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
726 only** — a `const` there does not compile — so the annotations are726 only** — a `const` there does not compile — so the annotations are
@@ -1153,6 +1153,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1153 | DELETE | `/academic-years/{id}` | manager | Delete an academic year. Requires manager+. Refused with a 409 while any şube or dönem still links it — move or delete them first. An archived year must be re-opened (`PATCH` is not enough: there is no unarchive here, so the row is only deletable while open) like every other past-structure write. |1153 | DELETE | `/academic-years/{id}` | manager | Delete an academic year. Requires manager+. Refused with a 409 while any şube or dönem still links it — move or delete them first. An archived year must be re-opened (`PATCH` is not enough: there is no unarchive here, so the row is only deletable while open) like every other past-structure write. |
1154 | POST | `/academic-years/{id}/archive` | manager | Archive an academic year. Requires manager+. Stamps `archived_at`, and from then on the whole year is past structure: no new şube, no new dönem, no exam inside it, and no edit or delete of the year itself. Idempotent — a second archive answers `200` with the stamp that already stood. There is no unarchive route: the row is deletable only while open. |1154 | POST | `/academic-years/{id}/archive` | manager | Archive an academic year. Requires manager+. Stamps `archived_at`, and from then on the whole year is past structure: no new şube, no new dönem, no exam inside it, and no edit or delete of the year itself. Idempotent — a second archive answers `200` with the stamp that already stood. There is no unarchive route: the row is deletable only while open. |
1155 | POST | `/academic-years/{id}/rollover` | manager | Carry another year's şubeler into this one. Requires manager+. Each şube of `from_year` whose grade the target year promotes is planted afresh here — same name, mapped grade, and copies of its instances (`ders_saati`, karne policy, teachers) and of every live member, who are also enrolled into the new instances. A grade with no promotion entry stays behind: that is graduation, and `graduated` names it. The target must be empty (a second rollover into it is a 409, which is what makes the command idempotent), open, and different from the source. |1155 | POST | `/academic-years/{id}/rollover` | manager | Carry another year's şubeler into this one. Requires manager+. Each şube of `from_year` whose grade the target year promotes is planted afresh here — same name, mapped grade, and copies of its instances (`ders_saati`, karne policy, teachers) and of every live member, who are also enrolled into the new instances. A grade with no promotion entry stays behind: that is graduation, and `graduated` names it. The target must be empty (a second rollover into it is a 409, which is what makes the command idempotent), open, and different from the source. |
1156+| GET | `/ai/capabilities` | no | The capabilities connected AI services are serving right now, per capability, with the work in flight — a discovery read for an operator or a service deciding what it may ask this bridge to do. |
1156 | GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + SHA-256 fingerprint) for a service to pin; `404` when the bridge is off. |1157 | GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + SHA-256 fingerprint) for a service to pin; `404` when the bridge is off. |
1157 | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |1158 | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec |
1158 | GET | `/appointments` | student | List bookings, newest first. Students and parents see the ones they requested; teacher+ see the ones aimed at their own slots — their request inbox. Managers and admins read their own inbox too (they may still decide any booking by id). Paged via `?limit=&offset=` (omit `limit` for every booking); returns a `{items, total, limit, offset}` envelope. |1159 | GET | `/appointments` | student | List bookings, newest first. Students and parents see the ones they requested; teacher+ see the ones aimed at their own slots — their request inbox. Managers and admins read their own inbox too (they may still decide any booking by id). Paged via `?limit=&offset=` (omit `limit` for every booking); returns a `{items, total, limit, offset}` envelope. |
@@ -1238,6 +1239,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1238 | GET | `/course-notes/{id}/files/{file_id}` | student | Download a course note file's bytes. `Content-Type` is the one declared on upload; `Content-Disposition` carries the original filename. |1239 | GET | `/course-notes/{id}/files/{file_id}` | student | Download a course note file's bytes. `Content-Type` is the one declared on upload; `Content-Disposition` carries the original filename. |
1239 | DELETE | `/course-notes/{id}/files/{file_id}` | teacher | Delete a course note file (row first, then its blob). Requires teacher+ and management rights over the course. |1240 | DELETE | `/course-notes/{id}/files/{file_id}` | teacher | Delete a course note file (row first, then its blob). Requires teacher+ and management rights over the course. |
1240 | GET | `/course-notes/{id}/rag` | student | List a course note's AI outputs, newest first. Visible to whoever can view the course. Paged via `?limit=&offset=`. |1241 | GET | `/course-notes/{id}/rag` | student | List a course note's AI outputs, newest first. Visible to whoever can view the course. Paged via `?limit=&offset=`. |
1242+| POST | `/course-notes/{id}/rag/reindex` | teacher | Re-index a course note now, without waiting for its next write. |
1241 | DELETE | `/course-notes/{id}/rag/{output_id}` | teacher | Delete one stored AI output. Requires teacher+ and management rights over the course. Dropping an output does not stop the next note or file change from regenerating one. |1243 | DELETE | `/course-notes/{id}/rag/{output_id}` | teacher | Delete one stored AI output. Requires teacher+ and management rights over the course. Dropping an output does not stop the next note or file change from regenerating one. |
1242 | GET | `/courses` | student | List the catalog courses visible to the caller: every course for manager+, otherwise the courses they teach somewhere plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |1244 | GET | `/courses` | student | List the catalog courses visible to the caller: every course for manager+, otherwise the courses they teach somewhere plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1243 | POST | `/courses` | teacher | Create a catalog course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp). A catalog row teaches nobody by itself: a şube attaches it into an instance (`POST /classes/{id}/instances`), and a `study`/`club` is joined school-wide (`POST /courses/{id}/members`). |1245 | POST | `/courses` | teacher | Create a catalog course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp). A catalog row teaches nobody by itself: a şube attaches it into an instance (`POST /classes/{id}/instances`), and a `study`/`club` is joined school-wide (`POST /courses/{id}/members`). |
@@ -1412,6 +1414,14 @@ window filtering, before paging; negative values are a `400` naming the field.
1412 | GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes. Access follows the question the solution hangs on — in practice school-wide, since solutions exist only on approved questions. |1414 | GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes. Access follows the question the solution hangs on — in practice school-wide, since solutions exist only on approved questions. |
1413 | POST | `/questions/{id}/solutions/{sid}/image` | student | Attach (or replace) the solution's photo. Author only — and at any time, since solutions are never frozen. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). |1415 | POST | `/questions/{id}/solutions/{sid}/image` | student | Attach (or replace) the solution's photo. Author only — and at any time, since solutions are never frozen. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). |
1414 | DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo. Author only, anytime — solutions are never frozen. |1416 | DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo. Author only, anytime — solutions are never frozen. |
1417+| GET | `/rag/threads` | student | The caller's own threads, most recently active first. Paged via `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's. |
1418+| POST | `/rag/threads` | student | Start a new RAG thread, optionally named. Every authenticated role may ask — parents included. A user may keep up to the school's `max_chatbot_threads` threads *across both AI nests*; at the cap the request is refused (409) until an old thread is deleted — the cap is storage protection, not a usage quota (that is the per-minute message limit). |
1419+| PATCH | `/rag/threads/{id}` | student | Rename a thread, or clear its name (`title: null`). Owner only; someone else's thread is a `404`, never a `403`. The edit counts as activity, so the thread moves to the top of the list. |
1420+| DELETE | `/rag/threads/{id}` | student | Delete a thread and every turn in it, permanently. Owner only; someone else's thread is a `404`, never a `403` (its existence is not leaked). |
1421+| GET | `/rag/threads/{id}/messages` | student | The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only. |
1422+| POST | `/rag/threads/{id}/messages` | student | Ask the corpus a question: `{content}`, at most the school's `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the moment both rows are written — the answer itself lands later, in the reserved assistant row. `503` when no AI service offers `rag.chat`, and nothing is written; `429` + `Retry-After` over the per-user send limit. |
1423+| GET | `/rag/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. |
1424+| GET | `/rag/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. |
1415 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |1425 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |
1416 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |1426 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |
1417 | GET | `/schools/{slug}` | builder | One school by slug. |1427 | GET | `/schools/{slug}` | builder | One school by slug. |
migrations/school/20260917000001_rag.sqladded+73 -0
@@ -0,0 +1,73 @@
1+-- School-database schema, part 6: the RAG nest — its own thread and message
2+-- tables, and the corpus document id the `rag.index` worker stamps on a
3+-- course-note file so a later citation can be resolved back to something a
4+-- reader can open.
5+--
6+-- Separate from the chatbot's tables on purpose: a RAG turn is a retrieval
7+-- over the school's course-note corpus followed by an answer, the service is
8+-- named on the wire as `rag.chat`, and the stored answer carries its citations
9+-- as JSON — a shape the chatbot's rows never hold. The two nests are gated as
10+-- one package (`Module::Chatbot`) but share no row.
11+--
12+-- Same translation rules as parts 1-5: entity ids are app-minted UUID v7 (no
13+-- DB default), timestamps stay BIGINT unix-ms, and all FKs are ON DELETE NO
14+-- ACTION — except `rag_message.thread`, which cascades: a turn has no life of
15+-- its own, so even a path that removes the thread without walking the children
16+-- cannot strand one.
17+
18+-- The seat counter this nest's threads are capped on, the twin of
19+-- `chatbot_thread_count` and a column of its own rather than a shared pool:
20+-- the school's `max_chatbot_threads` governs both nests' saved threads, but
21+-- each nest holds its own seats, so a user's RAG threads cannot spend the
22+-- chatbot's room or the reverse — and the counter a claim moves counts exactly
23+-- rows it guards (the single-record `UPDATE` is the claim; see
24+-- `db::rag_thread::create_capped`).
25+ALTER TABLE app_user ADD COLUMN rag_thread_count BIGINT NOT NULL DEFAULT 0;
26+
27+CREATE TABLE rag_thread (
28+ id uuid PRIMARY KEY,
29+ owner uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
30+ title TEXT NULL,
31+ created_at BIGINT NOT NULL,
32+ updated_at BIGINT NOT NULL
33+);
34+
35+-- The list's sort key, the same shape `chatbot_thread_user_updated` carries.
36+CREATE INDEX rag_thread_owner_updated ON rag_thread (owner, updated_at);
37+
38+-- One turn of a RAG thread. `user_id` is duplicated off the thread exactly as
39+-- `chatbot_message` duplicates it, so an ownership check is one read with no
40+-- join. `role`/`status` spell their enums in a CHECK for the same reason the
41+-- chatbot's columns do: the Rust enums are the source, the CHECK is the backstop.
42+--
43+-- `content` is `''` on a reserved (pending) assistant row, hence the DEFAULT.
44+-- `reply` is the service's own JSON — whether it abstained, why, and the
45+-- citations — NULL until the answer lands; JSONB because its shape belongs to
46+-- the service, not this schema. There is no `truncated` twin of the chatbot's
47+-- column: an answer whose citations exceed MAX_RAG_CITATIONS is refused whole
48+-- (a clipped citation list still renders `[N]` markers into nothing), so no
49+-- read ever has to ask whether what it got is all there was.
50+CREATE TABLE rag_message (
51+ id uuid PRIMARY KEY,
52+ thread uuid NOT NULL REFERENCES rag_thread(id) ON DELETE CASCADE,
53+ user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
54+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
55+ status TEXT NOT NULL CHECK (status IN ('pending', 'complete', 'failed')),
56+ content TEXT NOT NULL DEFAULT '',
57+ reply jsonb NULL,
58+ error_code TEXT NULL,
59+ created_at BIGINT NOT NULL,
60+ completed_at BIGINT NULL
61+);
62+
63+CREATE INDEX rag_message_thread_created ON rag_message (thread, created_at);
64+CREATE INDEX rag_message_user ON rag_message (user_id);
65+CREATE INDEX rag_message_status_created ON rag_message (status, created_at);
66+
67+-- The corpus document id `rag.index` echoed back for this file's bytes: the
68+-- handle a citation's `doc_id` resolves through to a file. Deliberately not
69+-- unique — identical bytes hash to one document, so several files may claim
70+-- the same id and the resolver answers with the first file that owns it.
71+-- NULL until the worker has indexed the file.
72+ALTER TABLE course_note_file ADD COLUMN rag_doc_id TEXT;
73+CREATE INDEX course_note_file_rag_doc_id ON course_note_file (rag_doc_id);
src/ai/rag.rsmodified+38 -0
@@ -90,6 +90,12 @@ impl RagIndexPayload {
90 /// service: no dispatch, no `rag_output` row. That is `Module::Chatbot`, the90 /// service: no dispatch, no `rag_output` row. That is `Module::Chatbot`, the
91 /// package's only module, so it gates every outbound dispatch and not just the91 /// package's only module, so it gates every outbound dispatch and not just the
92 /// `/chatbot` nest.92 /// `/chatbot` nest.
93+///
94+/// The answer may also name the doc id the service minted per file — `files`
95+/// as `[{id, doc_id}]` — which is stamped onto the matching attachment rows,
96+/// and only onto this note's own files. Best-effort: a failed stamp is logged
97+/// and the output still lands, because the map is optional on the wire and a
98+/// service that omits it is simply not heard from on that front.
93 pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: &CourseNote) {99 pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: &CourseNote) {
94 if !tenant.modules.contains(Module::Chatbot) {100 if !tenant.modules.contains(Module::Chatbot) {
95 tracing::debug!(101 tracing::debug!(
@@ -150,6 +156,38 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note:
150 return;156 return;
151 }157 }
152 158
159+ // A service may name the doc id it minted for each file — `files` as
160+ // `[{id, doc_id}]` — so a row remembers what its bytes were indexed as.
161+ // Only ids of *this* note's attachments are honoured: a service bug
162+ // naming another note's file must not stamp that row. Best-effort — a
163+ // failed write is logged and the stored answer still lands.
164+ if let Some(claims) = answer.get("files").and_then(serde_json::Value::as_array) {
165+ for claim in claims {
166+ let (Some(id), Some(doc_id)) = (
167+ claim.get("id").and_then(serde_json::Value::as_str),
168+ claim.get("doc_id").and_then(serde_json::Value::as_str),
169+ ) else {
170+ continue;
171+ };
172+ let Some(file) = files.iter().find(|file| file.get_id().key() == id) else {
173+ continue;
174+ };
175+ if let Err(err) =
176+ crate::db::course_note_file::set_rag_doc_id(&state.db, file.get_id(), doc_id).await
177+ {
178+ tracing::warn!(
179+ "could not stamp doc id on course note file {}: {err}",
180+ file.get_id().key()
181+ );
182+ }
183+ }
184+ } else {
185+ tracing::debug!(
186+ "the rag.index answer for course note {} names no doc ids",
187+ note.get_id().key()
188+ );
189+ }
190+
153 let sources = files.iter().map(|file| file.get_id().clone()).collect();191 let sources = files.iter().map(|file| file.get_id().clone()).collect();
154 if let Err(err) = replace(&state.db, note, sources, answer).await {192 if let Err(err) = replace(&state.db, note, sources, answer).await {
155 tracing::warn!("could not store the rag.index output: {err}");193 tracing::warn!("could not store the rag.index output: {err}");
src/ai/rag_chat.rsmodified+242 -0
@@ -16,6 +16,9 @@
16 use serde::{Deserialize, Serialize};16 use serde::{Deserialize, Serialize};
17 17
18 use crate::ai::chat::ChatRole;18 use crate::ai::chat::ChatRole;
19+use crate::constant::{
20+ AI_RAG_CHAT_CAPABILITY, AI_RAG_CHAT_TIMEOUT_SECS, MAX_RAG_CITATIONS, MAX_RAG_CITATION_PAGES,
21+};
19 22
20 /// One `(sınıf, ders)` pair the question is scoped to.23 /// One `(sınıf, ders)` pair the question is scoped to.
21 ///24 ///
@@ -127,6 +130,245 @@ pub struct RagChatReplyPayload {
127 pub citations: Vec<RagCitation>,130 pub citations: Vec<RagCitation>,
128 }131 }
129 132
133+/// Ask a RAG service one question and resolve what came back.
134+///
135+/// The request is built from what the session already proves — `asker` and
136+/// `asker_role` are read from the live session by the caller, never taken from
137+/// a body, and `scope` from the asker's own memberships — and the reply is
138+/// mapped into what a message row can hold: the answer text, the abstention,
139+/// and the citations whose corpus `doc_id` resolves to a course-note file the
140+/// asker may view.
141+///
142+/// `Err` is a short, stable code for the turn's `error_code` — a transport
143+/// failure, the service's own `Response::Err` verdict, or `bad_reply` when the
144+/// reply was unreadable or exceeded a storage cap. Two codes are special:
145+/// `role_required` and `scope_mismatch` mean the **backend** built a request
146+/// the service may not answer. The turn still fails — an answer is not safe to
147+/// invent — but this side of the bridge is the bug, so it is logged as one.
148+#[allow(clippy::too_many_arguments)] // the whole turn context, spelled once
149+pub async fn answer(
150+ db: &crate::database::Database,
151+ bridge: &crate::ai::AiBridge,
152+ slug: &crate::tenant::Slug,
153+ thread: &crate::domain::rag_thread::RagThreadId,
154+ fresh: &[crate::domain::rag_message::RagMessageId; 2],
155+ prompt: String,
156+ asker: &crate::domain::user::UserId,
157+ asker_role: crate::domain::role::Role,
158+ scope: Vec<RagScopePair>,
159+ history: Vec<RagTurn>,
160+) -> Result<(String, crate::domain::rag_message::RagReply), String> {
161+ let scope_pairs = scope.len();
162+ let payload = serde_json::to_value(RagChatRequestPayload {
163+ message: prompt,
164+ asker: asker.key(),
165+ asker_role: asker_role.as_str().to_string(),
166+ scope,
167+ history,
168+ })
169+ .map_err(|err| {
170+ tracing::error!("could not encode a rag.chat request: {err}");
171+ "internal".to_string()
172+ })?;
173+ tracing::debug!(
174+ "dispatching rag.chat for thread {} (answer {}): {scope_pairs} scope pairs",
175+ thread.key(),
176+ fresh[1].key()
177+ );
178+
179+ let raw = bridge
180+ .dispatch_with_timeout(
181+ slug,
182+ AI_RAG_CHAT_CAPABILITY,
183+ payload,
184+ std::time::Duration::from_secs(AI_RAG_CHAT_TIMEOUT_SECS),
185+ )
186+ .await
187+ .map_err(failure_code)?;
188+ let reply: RagChatReplyPayload = serde_json::from_value(raw).map_err(|err| {
189+ tracing::warn!("AI service answered with an unreadable rag.chat payload: {err}");
190+ "bad_reply".to_string()
191+ })?;
192+
193+ // The service is a trust boundary: a reply past a storage cap is refused
194+ // whole rather than clipped. A half-cited answer reads as a complete one,
195+ // and an unbounded answer is bytes a service chose to write into a
196+ // school's database.
197+ if reply.citations.len() > MAX_RAG_CITATIONS {
198+ tracing::error!(
199+ "rag.chat returned {} citations, over the {MAX_RAG_CITATIONS} cap",
200+ reply.citations.len()
201+ );
202+ return Err("bad_reply".to_string());
203+ }
204+ if let Some(over) = reply
205+ .citations
206+ .iter()
207+ .find(|citation| citation.pages.len() > MAX_RAG_CITATION_PAGES)
208+ {
209+ tracing::error!(
210+ "rag.chat citation {} names {} pages, over the {MAX_RAG_CITATION_PAGES} cap",
211+ over.n,
212+ over.pages.len()
213+ );
214+ return Err("bad_reply".to_string());
215+ }
216+
217+ // The two verdicts that mean the *backend* built a bad request: the scope
218+ // or the asker's role it sent is not something the service may answer. The
219+ // turn still fails, but this is a bug on this side of the bridge, so it is
220+ // logged as one rather than as an ordinary service refusal.
221+ if matches!(reply.reason.as_str(), "role_required" | "scope_mismatch") {
222+ tracing::error!(
223+ "rag.chat refused a request the backend built: {} (asker {})",
224+ reply.reason,
225+ asker.key()
226+ );
227+ return Err(reply.reason);
228+ }
229+
230+ if reply.text.trim().is_empty() && !reply.abstained {
231+ // Nothing to show, and the domain would refuse to store it anyway. A
232+ // blank bubble is indistinguishable from a bug, so it is reported as
233+ // one.
234+ tracing::warn!("rag.chat answered with a blank, non-abstained reply");
235+ return Err("empty_reply".to_string());
236+ }
237+
238+ let citations = resolve_citations(db, asker, &reply.citations).await;
239+ Ok((
240+ reply.text,
241+ crate::domain::rag_message::RagReply {
242+ abstained: reply.abstained,
243+ reason: reply.reason,
244+ citations,
245+ },
246+ ))
247+}
248+
249+/// Resolve each citation's corpus `doc_id` to the course-note file that owns
250+/// it, keeping only a file whose course the asker may view.
251+///
252+/// One read per *distinct* `doc_id`: identical PDF bytes resolve to the same
253+/// document, so one document may be claimed by several files — across courses,
254+/// which is exactly why the visibility check is per candidate and not per
255+/// document. The first visible candidate wins, in the store's own order, so two
256+/// identical turns resolve a citation the same way. A citation whose document
257+/// no visible file claims keeps every other field and stores `file: null` —
258+/// the passage stays citable, only not openable.
259+async fn resolve_citations(
260+ db: &crate::database::Database,
261+ asker: &crate::domain::user::UserId,
262+ citations: &[RagCitation],
263+) -> Vec<crate::domain::rag_message::RagCitedFile> {
264+ let user = match crate::service::user::read(db, asker).await {
265+ Ok(Some(user)) => Some(user),
266+ // The asker vanished mid-turn (only reachable through a deleted
267+ // account): nothing can be visible to them, so nothing resolves.
268+ Ok(None) => {
269+ tracing::warn!("the asker is gone; citations stay unresolved");
270+ None
271+ }
272+ Err(err) => {
273+ tracing::warn!("could not read the asker for citation resolution: {err}");
274+ None
275+ }
276+ };
277+
278+ let mut candidates: std::collections::HashMap<&str, Vec<crate::domain::course_note_file::CourseNoteFile>> =
279+ std::collections::HashMap::new();
280+ for citation in citations {
281+ if !candidates.contains_key(citation.doc_id.as_str()) {
282+ let files =
283+ match crate::db::course_note_file::find_by_rag_doc_id(db, &citation.doc_id).await {
284+ Ok(files) => files,
285+ Err(err) => {
286+ tracing::warn!("could not resolve doc {}: {err}", citation.doc_id);
287+ Vec::new()
288+ }
289+ };
290+ candidates.insert(citation.doc_id.as_str(), files);
291+ }
292+ }
293+
294+ let mut resolved = Vec::with_capacity(citations.len());
295+ for citation in citations {
296+ let file = match &user {
297+ Some(user) => {
298+ let files = candidates
299+ .get(citation.doc_id.as_str())
300+ .map(Vec::as_slice)
301+ .unwrap_or(&[]);
302+ first_visible_file(db, user, files).await
303+ }
304+ None => None,
305+ };
306+ resolved.push(crate::domain::rag_message::RagCitedFile {
307+ n: citation.n,
308+ file,
309+ pages: citation.pages.clone(),
310+ span_ids: citation.span_ids.clone(),
311+ ders: citation.ders.clone(),
312+ });
313+ }
314+ resolved
315+}
316+
317+/// The first candidate file whose owning course `user` may view, in the
318+/// store's order; `None` when the document is claimed by no file they can
319+/// open. A read that fails mid-walk is treated like a file they cannot see —
320+/// the citation still lands, only unresolved.
321+async fn first_visible_file(
322+ db: &crate::database::Database,
323+ user: &crate::domain::user::User,
324+ candidates: &[crate::domain::course_note_file::CourseNoteFile],
325+) -> Option<String> {
326+ for candidate in candidates {
327+ let Some(note) = crate::db::course_note::read(db, candidate.get_course_note())
328+ .await
329+ .ok()
330+ .flatten()
331+ else {
332+ continue;
333+ };
334+ let Some(course) = crate::db::course::read(db, note.get_course()).await.ok().flatten()
335+ else {
336+ continue;
337+ };
338+ match crate::service::course::can_view_course(&course, user, db).await {
339+ Ok(true) => return Some(candidate.get_id().key().to_string()),
340+ Ok(false) => {}
341+ Err(err) => {
342+ tracing::warn!("could not check course visibility for a citation: {err}");
343+ }
344+ }
345+ }
346+ None
347+}
348+
349+/// A dispatch failure as a short, stable code the frontend can branch on. The
350+/// same mapping the chatbot nest applies to its own round trip.
351+fn failure_code(err: crate::ai::AiError) -> String {
352+ use crate::ai::AiError;
353+ match err {
354+ AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(),
355+ AiError::Busy(_) => "busy".to_string(),
356+ AiError::Timeout(_) => "timed_out".to_string(),
357+ AiError::Transport(_) => "transport".to_string(),
358+ AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(),
359+ // The service's own verdict. Kept verbatim (the domain trims it) so a
360+ // service can define codes the backend has never heard of.
361+ AiError::Remote { code, message } => {
362+ tracing::warn!("AI RAG service refused the request: {code}: {message}");
363+ if code.trim().is_empty() {
364+ "service_error".to_string()
365+ } else {
366+ code
367+ }
368+ }
369+ }
370+}
371+
130 #[cfg(test)]372 #[cfg(test)]
131 mod tests {373 mod tests {
132 use super::*;374 use super::*;
src/ai/server.rsmodified+1 -1
@@ -32,9 +32,9 @@ use crate::domain::user::{User, UserId};
32 use crate::error::AppError;32 use crate::error::AppError;
33 use crate::module::Module;33 use crate::module::Module;
34 use crate::telemetry::Metrics;34 use crate::telemetry::Metrics;
35+use crate::service::course::can_view_course;
35 use crate::tenant::{ResolvedTenant, Slug, Tenants};36 use crate::tenant::{ResolvedTenant, Slug, Tenants};
36 use crate::web::blob_path;37 use crate::web::blob_path;
37-use crate::web::courses::can_view_course;
38 use crate::web::extractor::AiPrincipal;38 use crate::web::extractor::AiPrincipal;
39 use crate::web::tenant_state::{TenantExt, school_files_path};39 use crate::web::tenant_state::{TenantExt, school_files_path};
40 40
src/config.rsmodified+10 -1
@@ -2,7 +2,7 @@ use std::env;
2 2
3 use crate::constant::{3 use crate::constant::{
4 AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT,4 AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT,
5- DEFAULT_AUTH_RATE_LIMIT, DEFAULT_CHATBOT_RATE_LIMIT,5+ DEFAULT_AUTH_RATE_LIMIT, DEFAULT_CHATBOT_RATE_LIMIT, DEFAULT_RAG_RATE_LIMIT,
6 };6 };
7 use crate::rate_limit::RateLimitConfig;7 use crate::rate_limit::RateLimitConfig;
8 use crate::telemetry::{LogFormat, TelemetryConfig, TelemetryError};8 use crate::telemetry::{LogFormat, TelemetryConfig, TelemetryError};
@@ -30,6 +30,11 @@ pub struct Config {
30 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is30 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
31 /// keyed by user and is enforced inside the handler.31 /// keyed by user and is enforced inside the handler.
32 pub chatbot_per_minute: u32,32 pub chatbot_per_minute: u32,
33+ /// RAG messages one user may send per minute
34+ /// (`RATE_LIMIT_RAG_PER_MINUTE`). `0` disables the tier. Kept out of
35+ /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
36+ /// keyed by user and is enforced inside the handler.
37+ pub rag_per_minute: u32,
33 /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When38 /// Startup builder seed (`BUILDER_USERNAME` + `BUILDER_PASSWORD`). When
34 /// both are set, a builder account with these credentials is created in the39 /// both are set, a builder account with these credentials is created in the
35 /// control database at boot if the username doesn't exist yet. Blank values40 /// control database at boot if the username doesn't exist yet. Blank values
@@ -79,6 +84,10 @@ impl Config {
79 env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),84 env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),
80 DEFAULT_CHATBOT_RATE_LIMIT,85 DEFAULT_CHATBOT_RATE_LIMIT,
81 ),86 ),
87+ rag_per_minute: parse_limit(
88+ env::var("RATE_LIMIT_RAG_PER_MINUTE").ok(),
89+ DEFAULT_RAG_RATE_LIMIT,
90+ ),
82 builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()),91 builder_username: parse_optional(env::var("BUILDER_USERNAME").ok()),
83 builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()),92 builder_password: parse_optional(env::var("BUILDER_PASSWORD").ok()),
84 ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()),93 ai_quic_addr: parse_optional(env::var("AI_QUIC_ADDR").ok()),
src/constant.rsmodified+16 -0
@@ -615,6 +615,22 @@ pub const MAX_RAG_SCOPE_PAIRS: usize = 200;
615 /// a retrieval over the whole course-note corpus before it generates anything.615 /// a retrieval over the whole course-note corpus before it generates anything.
616 pub const DEFAULT_RAG_RATE_LIMIT: u32 = 6;616 pub const DEFAULT_RAG_RATE_LIMIT: u32 = 6;
617 617
618+/// The most citations one `rag.chat` answer may carry into its stored reply.
619+/// The service is a trust boundary — everything it sends is written verbatim
620+/// into a school's database — so an answer citing more is refused whole rather
621+/// than trimmed: dropping entries would leave `[N]` markers in the answer text
622+/// pointing at nothing, and a reader cannot tell a clipped citation list from
623+/// a complete one.
624+pub const MAX_RAG_CITATIONS: usize = 50;
625+
626+/// The most pages one citation may name, the second axis of the same bound.
627+/// One reply's citations are therefore at most
628+/// `MAX_RAG_CITATIONS × MAX_RAG_CITATION_PAGES` page numbers, so however a
629+/// service distributes them it cannot turn a single stored answer into an
630+/// unbounded payload — the same storage-protection shape as
631+/// [`MAX_NOTE_FILES`], but for a body this backend does not compose.
632+pub const MAX_RAG_CITATION_PAGES: usize = 50;
633+
618 /// Hard ceiling on one chat message's characters — the newtype bound, above634 /// Hard ceiling on one chat message's characters — the newtype bound, above
619 /// which no school setting can reach. Sized for a pasted question with its635 /// which no school setting can reach. Sized for a pasted question with its
620 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.636 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
src/database.rsmodified+20 -5
@@ -22,7 +22,9 @@ use sqlx::migrate::{MigrateError, Migrator};
22 use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};22 use sqlx::postgres::{PgConnectOptions, PgConnection, PgPoolOptions};
23 23
24 use crate::config::Config;24 use crate::config::Config;
25-use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};25+use crate::constant::{
26+ CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS, RAG_PENDING_STALE_SECS,
27+};
26 use crate::domain::timestamp::Timestamp;28 use crate::domain::timestamp::Timestamp;
27 use crate::domain::user::{Password, Username};29 use crate::domain::user::{Password, Username};
28 use crate::error::AppError;30 use crate::error::AppError;
@@ -255,10 +257,6 @@ async fn migrator(set: &str) -> Result<Migrator, AppError> {
255 .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}")))257 .map_err(|err| AppError::Internal(format!("cannot read the {set} migrations: {err}")))
256 }258 }
257 259
258-/// Apply the school schema to a school database — the template at boot, every
259-/// newly minted school at create — then sweep the chatbot turns the previous
260-/// process owed an answer. Idempotent: an already-migrated database runs only
261-/// the sweep.
262 /// Apply the control schema (schools, builders, the shared rate-limit260 /// Apply the control schema (schools, builders, the shared rate-limit
263 /// window) to a control database. Idempotent: an already-migrated database261 /// window) to a control database. Idempotent: an already-migrated database
264 /// runs nothing. The boot path folds this into [`boot_control`]; suites that262 /// runs nothing. The boot path folds this into [`boot_control`]; suites that
@@ -272,6 +270,10 @@ pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> {
272 Ok(())270 Ok(())
273 }271 }
274 272
273+/// Apply the school schema to a school database — the template at boot, every
274+/// newly minted school at create — then sweep the chatbot and RAG turns the
275+/// previous process owed an answer. Idempotent: an already-migrated database
276+/// runs only the sweep.
275 pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {277 pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
276 migrator("school")278 migrator("school")
277 .await?279 .await?
@@ -297,6 +299,19 @@ pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> {
297 .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000)299 .bind(now - CHATBOT_PENDING_STALE_SECS * 1_000)
298 .execute(pool)300 .execute(pool)
299 .await?;301 .await?;
302+ // The RAG nest mirrors the chatbot's asynchronous send, so it owes the
303+ // same sweep with its own horizon (`RAG_PENDING_STALE_SECS`): a `rag_message`
304+ // left `pending` by the dead process presents as failed to any reader
305+ // either way, and the same `interrupted` code records why.
306+ sqlx::query(
307+ "UPDATE rag_message SET status = 'failed', error_code = 'interrupted',
308+ completed_at = $1
309+ WHERE status = 'pending' AND created_at < $2",
310+ )
311+ .bind(now)
312+ .bind(now - RAG_PENDING_STALE_SECS * 1_000)
313+ .execute(pool)
314+ .await?;
300 Ok(())315 Ok(())
301 }316 }
302 317
src/db/course_note_file.rsmodified+48 -0
@@ -1,6 +1,11 @@
1 //! The `course_note_file` table: attachment rows for a course note, listed1 //! The `course_note_file` table: attachment rows for a course note, listed
2 //! newest first, with the note's file cap claimed and released in the same2 //! newest first, with the note's file cap claimed and released in the same
3 //! write as the row.3 //! write as the row.
4+//!
5+//! The `rag_doc_id` column belongs to the RAG index path alone — stamped by
6+//! [`set_rag_doc_id`] and read back by [`find_by_rag_doc_id`] — and is
7+//! deliberately absent from [`CourseNoteFile`]: no other query has to know
8+//! the column exists.
4 9
5 use crate::constant::MAX_COURSE_NOTE_FILES;10 use crate::constant::MAX_COURSE_NOTE_FILES;
6 use crate::database::{Database, tx_with_retry, unique_violation};11 use crate::database::{Database, tx_with_retry, unique_violation};
@@ -112,6 +117,49 @@ pub async fn list_for(
112 .await117 .await
113 }118 }
114 119
120+/// Every file row claiming `doc_id` — the content hash an indexing service
121+/// minted for a file's bytes. The column is deliberately not unique
122+/// (identical bytes produce the same doc id), so one doc may be claimed by
123+/// several files, and a file's next re-index may find its bytes already
124+/// covered. Ordered by id so callers presenting the rows do not shuffle
125+/// between reads.
126+pub async fn find_by_rag_doc_id(
127+ db: &Database,
128+ doc_id: &str,
129+) -> Result<Vec<CourseNoteFile>, AppError> {
130+ let files = sqlx::query_as!(
131+ CourseNoteFile,
132+ r#"SELECT id AS "id: CourseNoteFileId",
133+ course_note AS "course_note: CourseNoteId", name AS "name: FileName",
134+ content_type AS "content_type: FileContentType", size FROM course_note_file
135+ WHERE rag_doc_id = $1 ORDER BY id"#,
136+ doc_id
137+ )
138+ .fetch_all(db)
139+ .await?;
140+ Ok(files)
141+}
142+
143+/// Stamp the indexing service's `doc_id` onto a file row — what a service
144+/// staged, so the next refresh can tell whether those bytes are already
145+/// covered. A plain id-keyed update: the column is owned by the RAG index
146+/// path alone, and no cap or counter moves with it. An unknown id updates
147+/// nothing, which the caller already tolerates as best-effort.
148+pub async fn set_rag_doc_id(
149+ db: &Database,
150+ file: &CourseNoteFileId,
151+ doc_id: &str,
152+) -> Result<(), AppError> {
153+ sqlx::query!(
154+ r#"UPDATE course_note_file SET rag_doc_id = $2 WHERE id = $1"#,
155+ file.uuid(),
156+ doc_id
157+ )
158+ .execute(db)
159+ .await?;
160+ Ok(())
161+}
162+
115 /// The blob names (the rows' own ids, since a file's blob is named by its163 /// The blob names (the rows' own ids, since a file's blob is named by its
116 /// id) behind every note attachment of `course` — collected *before* the164 /// id) behind every note attachment of `course` — collected *before* the
117 /// course-delete cascade wipes the rows.165 /// course-delete cascade wipes the rows.
src/db/mod.rsmodified+2 -0
@@ -58,7 +58,9 @@ pub mod pool_question;
58 pub mod pool_question_image;58 pub mod pool_question_image;
59 pub mod profile;59 pub mod profile;
60 pub mod question_image;60 pub mod question_image;
61+pub mod rag_message;
61 pub mod rag_output;62 pub mod rag_output;
63+pub mod rag_thread;
62 pub mod registration;64 pub mod registration;
63 pub mod session;65 pub mod session;
64 pub mod session_attendance;66 pub mod session_attendance;
src/db/rag_message.rsadded+465 -0
@@ -0,0 +1,465 @@
1+//! The `rag_message` table: the turns of a thread, both sides persisted.
2+//! The user's question lands `complete`, and the assistant's row is written
3+//! `pending` *before* the AI call so a reload never loses an answer in
4+//! flight. The task that owns the bridge round trip then flips it to
5+//! `complete` (with the text and the service's reply) or `failed` (with a
6+//! code), and the boot sweep in `database.rs` fails whatever a process death
7+//! left behind past the staleness window. Every turn is written *through* its
8+//! thread's own row — its guarded statement bumps `updated_at`, so a turn can
9+//! never outlive the thread it belongs to. The row shape lives in
10+//! [`crate::domain::rag_message`].
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+/// Write one turn *through its thread's own row*: the thread's activity
26+/// bump and the turn's insert are a single guarded statement, which is what
27+/// makes the thread's existence something this write writes rather than
28+/// something the caller read and then trusted — a
29+/// [`delete`](crate::db::rag_thread::delete) racing it touches the very
30+/// row this statement's gate updates, so under Postgres's row locking the
31+/// two serialize and no turn is left under a thread that is gone. It also
32+/// carries the thread's activity stamp, so a turn and its `updated_at` land
33+/// together. The stamp is written strictly upwards —
34+/// `GREATEST($now, updated_at + 1)` — because a turn's two rows routinely
35+/// land inside one millisecond and `updated_at` is the thread list's
36+/// ordering key.
37+///
38+/// [`AppError::NotFound`] = the thread is gone, and nothing was written.
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+ // No row out of the conditional insert means the thread's touch matched
70+ // nothing: the thread is gone, and nothing was written.
71+ inserted.ok_or(AppError::NotFound)
72+}
73+
74+/// Append the user's question. Nothing is awaited for it, so it is born
75+/// complete — and it carries no reply: there is nothing but the text.
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+/// Reserve the assistant's answer *before* the AI call: the row exists,
102+/// empty and `pending`, so a reload finds the turn and can wait on it. The
103+/// reply column stays NULL until the answer lands — the service's JSON is not
104+/// known yet.
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+/// The whole thread, oldest first — the order both the UI and the AI
129+/// history payload read in.
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+/// The last `limit` turns, still oldest-first — the tail replayed to the
147+/// AI service as context. Taken newest-first in the database (so the
148+/// `LIMIT` keeps the *recent* end) and flipped back here.
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+/// The last `limit` *settled* turns that carry text, still oldest-first —
173+/// the tail replayed to the AI service as context. The filter runs in the
174+/// query, not after it: a `LIMIT` over the raw tail hands back fewer usable
175+/// rows the moment a run of answers fails, silently shrinking the context
176+/// instead of reaching further back. No projection is applied — it only
177+/// ever rewrites a `pending` row, and none is selected here.
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+/// The user turn a reserved answer belongs to, by *identity*: the question
203+/// row of the very POST that reserved it, whose id the answering task
204+/// carries.
205+///
206+/// Never derived from write order. Two POSTs on one thread interleave
207+/// across the two creates — the rows land `userA, userB, asstA, asstB` —
208+/// so "the newest user row written before this answer" resolves *both*
209+/// answers to question B, and question A is never answered.
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+/// Read one turn only if `user` owns it — the poll loop's read.
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+/// Land the answer: the text and the service's reply (abstention, reason,
253+/// citations), the pair every settled answer is judged by. Gated on
254+/// `status = 'pending'` in the `WHERE`, so a late answer can't overwrite a row
255+/// the boot sweep (or a timeout) already failed, and two answers can't both
256+/// apply.
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+/// Mark the answer failed with a short code (`unavailable`, the service's
267+/// own error code, …). Same pending gate as [`complete`]; a failed turn
268+/// stores no reply — the service never produced one worth keeping.
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+ /// A real owner and a real thread row: every turn is written through its
316+ /// thread, so a turn with no thread is refused (see [`insert`]), and the
317+ /// owner is a foreign key. Fixed keys, one per test.
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+ // Both rows of a turn land in the same millisecond routinely, so the
359+ // `id` tie-break decides the thread's order. With a random ULID this
360+ // inverted a fifth of the pairs; here every pair must read back
361+ // question-then-answer, from both read paths.
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+ /// A settled answer carries the service's reply, and the reserved row it
394+ /// replaced carried none — the column is written once, by the flip that
395+ /// settles the turn.
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+ // Re-read out of the store: the JSONB round trip is the contract a
416+ // reader receives, and a return value is not evidence.
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+ /// The boot sweep (or a timeout) fails a `pending` row; a reply that
425+ /// arrives afterwards must be refused, not written over it — the
426+ /// `status = 'pending'` gate in [`settle`] is the whole of that rule, and
427+ /// the stored row is the verdict.
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+}
src/db/rag_thread.rsadded+460 -0
@@ -0,0 +1,460 @@
1+//! The `rag_thread` table: one user's RAG threads, listed
2+//! newest-activity-first, deleted together with every turn in them. The
3+//! entity and its validated newtypes live in
4+//! [`crate::domain::rag_thread`]; this module is where their rows are
5+//! read and written.
6+//!
7+//! The cap is the chatbot nest's, read from the settings singleton
8+//! (`max_chatbot_threads`) — the school sets one ceiling for its AI package —
9+//! but the seats are this nest's own (`app_user.rag_thread_count`), so a
10+//! user's RAG threads and their chatbot threads never spend each other's room.
11+
12+use crate::constant::DEFAULT_MAX_CHATBOT_THREADS;
13+use crate::database::{Database, tx_with_retry};
14+use crate::db::page::PagedList;
15+use crate::domain::rag_thread::{RagThread, RagThreadId, RagThreadTitle};
16+use crate::domain::timestamp::Timestamp;
17+use crate::domain::user::UserId;
18+use crate::error::AppError;
19+use sqlx::query_as;
20+
21+/// Start a thread unless `user` is already at the school's
22+/// `max_chatbot_threads`. The claim recipe of one: the slot bump on the
23+/// user row, the live cap read, and the thread's insert are a single
24+/// statement — two requests racing the same user's last slot cannot both
25+/// win, and the counter can never count a row that did not commit.
26+///
27+/// The cap is the one *live* on the settings singleton, sub-queried inside
28+/// that same conditional write rather than bound as a number: this cap does
29+/// not live on the parent row (the seat is on the user, the limit is the
30+/// school's), and a snapshot of it admits every request already in flight
31+/// when a `PATCH /settings` lowers it. `DEFAULT_MAX_CHATBOT_THREADS` is the
32+/// fallback the settings row's own NULL means — no row, or a school that
33+/// never set the knob. The knob is shared with the chatbot nest on purpose
34+/// (one AI package, one ceiling); the *column* is not — `rag_thread_count`
35+/// counts only these threads, exactly the rows this claim guards.
36+///
37+/// The seat is taken on the user's own row, which is also the key a role
38+/// change writes, so this write already contends with a demotion — no
39+/// separate holder claim is needed.
40+pub async fn create_capped(
41+ db: &Database,
42+ user: &UserId,
43+ title: Option<RagThreadTitle>,
44+) -> Result<RagThread, AppError> {
45+ let now = Timestamp::now();
46+ match query_as!(
47+ RagThread,
48+ "WITH seat AS (
49+ UPDATE app_user SET rag_thread_count = rag_thread_count + 1
50+ WHERE id = $1
51+ AND rag_thread_count < COALESCE(
52+ (SELECT max_chatbot_threads FROM settings WHERE id = 'school'),
53+ $2)
54+ RETURNING 1)
55+ INSERT INTO rag_thread (id, owner, title, created_at, updated_at)
56+ SELECT $3, $1, $4, $5, $5
57+ WHERE EXISTS (SELECT 1 FROM seat)
58+ RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", \
59+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
60+ user.uuid(),
61+ DEFAULT_MAX_CHATBOT_THREADS,
62+ RagThreadId::generate().uuid(),
63+ title.map(|t| t.as_str().to_string()),
64+ now.as_millis(),
65+ )
66+ .fetch_optional(db)
67+ .await?
68+ {
69+ Some(saved) => Ok(saved),
70+ // Full, or the user's row is gone — the conditional write matches
71+ // nothing either way, as before.
72+ None => Err(AppError::Conflict(
73+ "you have reached the school's limit on saved threads — delete one first",
74+ )),
75+ }
76+}
77+
78+/// A user's threads, most recently active first — the sort the
79+/// `rag_thread_owner_updated` index exists for.
80+pub async fn list_for_user(
81+ db: &Database,
82+ user: &UserId,
83+ limit: Option<i64>,
84+ offset: i64,
85+) -> Result<(Vec<RagThread>, i64), AppError> {
86+ PagedList::new(
87+ "rag_thread WHERE owner = $1",
88+ "ORDER BY updated_at DESC, id DESC",
89+ )
90+ .bind(user.uuid())
91+ .run(limit, offset, db)
92+ .await
93+}
94+
95+/// How many threads `user` keeps — the `max_chatbot_threads` cap check, read
96+/// against this nest's own seats.
97+pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> {
98+ let row = sqlx::query!(
99+ "SELECT count(*) AS threads FROM rag_thread WHERE owner = $1",
100+ user.uuid()
101+ )
102+ .fetch_one(db)
103+ .await?;
104+ Ok(row.threads.unwrap_or(0).max(0) as usize)
105+}
106+
107+/// Read a thread only if `user` owns it — a foreign id reads as absent, so
108+/// the web layer answers 404 rather than leaking that it exists.
109+pub async fn read_for(
110+ db: &Database,
111+ id: &RagThreadId,
112+ user: &UserId,
113+) -> Result<Option<RagThread>, AppError> {
114+ let thread = query_as!(
115+ RagThread,
116+ "SELECT id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM rag_thread WHERE id = $1",
117+ id.uuid()
118+ )
119+ .fetch_optional(db)
120+ .await?;
121+ Ok(thread.filter(|thread| &thread.owner == user))
122+}
123+
124+// Stamping new activity is not a call of its own: it is the monotonic bump
125+// inside every write that touches the thread (a turn's insert, the rename,
126+// the delete below), so a stamp can no longer be lost (it used to be a
127+// best-effort query after the two creates, whose failure was a `warn!`) and
128+// no turn can be written without it.
129+
130+/// Rename the thread (`None` clears the name back to untitled), stamping
131+/// the edit as activity. Field-scoped: a turn may be landing concurrently.
132+/// The stamp is written strictly upwards — `GREATEST($now, updated_at + 1)`
133+/// — because a thread's writes routinely land inside one millisecond and
134+/// `updated_at` is the list's ordering key; the stamp may sit a few
135+/// milliseconds ahead of the clock, which an ordering key does not care
136+/// about. Zero rows: the thread is gone, the same 404 the delete answers.
137+pub async fn rename(
138+ db: &Database,
139+ thread: &RagThread,
140+ title: Option<RagThreadTitle>,
141+) -> Result<RagThread, AppError> {
142+ let updated = query_as!(
143+ RagThread,
144+ "UPDATE rag_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) \
145+ WHERE id = $1 \
146+ RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", \
147+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
148+ thread.get_id().uuid(),
149+ title.map(|t| t.as_str().to_string()),
150+ Timestamp::now().as_millis(),
151+ )
152+ .fetch_optional(db)
153+ .await?;
154+ updated.ok_or(AppError::NotFound)
155+}
156+
157+/// Delete the thread and every turn in it — one transaction, so a crash
158+/// can't orphan messages under a vanished thread. The owner's slot comes
159+/// back in that same transaction, or the cap would ratchet shut.
160+///
161+/// A turn's insert (see [`crate::db::rag_message`]) writes *through*
162+/// the thread's row — its guarded statement moves `updated_at`, the key
163+/// this delete's final write removes — so under Postgres's row locking the
164+/// two serialize: either the turn saw the thread and committed first (the
165+/// delete then refuses nothing, the sweep takes the turn), or the thread
166+/// was gone and the turn's gate matched nothing. No turn outlives its
167+/// thread. On a re-sent round the thread is already gone, so the caller
168+/// gets the `404` that is the truth.
169+pub async fn delete(db: &Database, thread: RagThread) -> Result<RagThread, AppError> {
170+ tx_with_retry(db, false, async move |tx| {
171+ // Children first, exactly like the chatbot's delete: `rag_message`'s
172+ // foreign key cascades by itself, but a cascade removes rows the
173+ // caller cannot see, and this transaction also has to read the parent
174+ // row back to free its seat.
175+ sqlx::query!(
176+ "DELETE FROM rag_message WHERE thread = $1",
177+ thread.get_id().uuid()
178+ )
179+ .execute(&mut *tx)
180+ .await?;
181+ let gone = query_as!(
182+ RagThread,
183+ "DELETE FROM rag_thread WHERE id = $1 \
184+ RETURNING id AS \"id: RagThreadId\", owner AS \"owner: UserId\", title AS \"title: RagThreadTitle\", \
185+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
186+ thread.get_id().uuid()
187+ )
188+ .fetch_optional(&mut *tx)
189+ .await?;
190+ if let Some(gone) = &gone {
191+ sqlx::query!(
192+ "UPDATE app_user SET rag_thread_count = GREATEST(rag_thread_count - 1, 0) \
193+ WHERE id = $1",
194+ gone.get_owner().uuid()
195+ )
196+ .execute(&mut *tx)
197+ .await?;
198+ }
199+ gone.ok_or(AppError::NotFound)
200+ })
201+ .await
202+}
203+#[cfg(test)]
204+mod tests {
205+ use super::*;
206+ use sqlx::Row as _;
207+
208+ use crate::db::rag_message;
209+ use crate::domain::rag_message::RagContent;
210+ use crate::domain::settings::{Settings, SettingsParams};
211+
212+ /// The fixed fixture person, by a valid id every helper can name.
213+ const U: &str = "019732e3-7b00-7000-8000-00000000aaaa";
214+
215+ /// The owner's counter and the threads it counts, both re-read out of the
216+ /// store — never off a return value.
217+ async fn stored(db: &Database) -> (i64, usize) {
218+ let counter = sqlx::query("SELECT rag_thread_count FROM app_user WHERE id = $1")
219+ .bind(UserId::from_key(U).uuid())
220+ .fetch_one(db)
221+ .await
222+ .unwrap()
223+ .try_get::<i64, _>(0)
224+ .unwrap();
225+ let rows = sqlx::query("SELECT count(*) FROM rag_thread")
226+ .fetch_one(db)
227+ .await
228+ .unwrap()
229+ .try_get::<i64, _>(0)
230+ .unwrap();
231+ (counter, rows as usize)
232+ }
233+
234+ async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) {
235+ let (db, leases) = crate::database::init_test_db().await;
236+ sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'u', 0)")
237+ .bind(UserId::from_key(U).uuid())
238+ .execute(&db)
239+ .await
240+ .unwrap();
241+ crate::db::settings::save(
242+ &db,
243+ Settings::try_new(SettingsParams {
244+ max_chatbot_threads: threads,
245+ ..Settings::defaults().params()
246+ })
247+ .unwrap(),
248+ )
249+ .await
250+ .unwrap();
251+ (db, leases)
252+ }
253+
254+ /// The seat and the row commit together, so the counter the cap reads can
255+ /// never disagree with the threads it counts — and a create refused at the
256+ /// cap advances neither.
257+ #[tokio::test]
258+ async fn a_capped_create_moves_the_counter_with_the_row() {
259+ let (db, _leases) = a_user_capped_at(1).await;
260+ let user = UserId::from_key(U);
261+
262+ create_capped(&db, &user, None).await.expect("first thread");
263+ assert_eq!(stored(&db).await, (1, 1));
264+
265+ let refused = create_capped(&db, &user, None).await;
266+ assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
267+ assert_eq!(
268+ stored(&db).await,
269+ (1, 1),
270+ "a refused create advances neither"
271+ );
272+ }
273+
274+ /// A turn is written *through* its thread's row, so a thread that is gone
275+ /// takes the write with it — and one that is there is stamped by it.
276+ /// The race this shape exists to close is the `#[ignore]`d test below;
277+ /// this one pins the logic, which the in-memory engine can answer.
278+ #[tokio::test]
279+ async fn a_turn_writes_its_thread_and_dies_with_it() {
280+ let (db, _leases) = a_user_capped_at(2).await;
281+ let user = UserId::from_key(U);
282+ let thread = create_capped(&db, &user, None).await.expect("thread");
283+ let opened = thread.get_updated_at().as_millis();
284+
285+ let ask = || RagContent::try_new("selam").unwrap();
286+ rag_message::append_user(&db, thread.get_id(), &user, ask())
287+ .await
288+ .expect("append");
289+ let stamped = read_for(&db, thread.get_id(), &user)
290+ .await
291+ .expect("re-read")
292+ .expect("still there")
293+ .get_updated_at()
294+ .as_millis();
295+ // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
296+ // the row unchanged is elided, and both rows of a turn are routinely
297+ // written inside one millisecond of the thread's own creation.
298+ assert!(stamped > opened, "{stamped} !> {opened}");
299+
300+ let id = thread.get_id().clone();
301+ delete(&db, thread).await.expect("delete");
302+ let orphan = rag_message::append_user(&db, &id, &user, ask()).await;
303+ assert!(
304+ matches!(orphan, Err(AppError::NotFound)),
305+ "a turn on a deleted thread must be refused: {orphan:?}"
306+ );
307+ assert_eq!(
308+ rag_message::list_for_thread(&db, &id, None, 0)
309+ .await
310+ .expect("list")
311+ .1,
312+ 0,
313+ "the refused turn wrote nothing"
314+ );
315+ }
316+
317+ /// The stamp moves **strictly upwards**, never to the clock — the property
318+ /// the whole shape rests on, since an `UPDATE` that leaves the row
319+ /// unchanged is elided, never reaches the store's write set, and so
320+ /// collides with the racing delete not at all.
321+ ///
322+ /// The test above cannot see it: it compares one append against
323+ /// `create_capped`, which costs a millisecond or so on its own, and a plain
324+ /// `$now` clears that. Nor can a burst of appends — each is a transaction
325+ /// of its own and takes about as long, so the clock has moved on by the
326+ /// time the next one reads it. Timing cannot reach the window on demand.
327+ ///
328+ /// So the *state* the window produces is set up directly instead: a stamp
329+ /// **ahead of the clock**, which is precisely what `GREATEST` leaves
330+ /// behind (see [`crate::db::rag_message`]'s insert) and therefore an
331+ /// ordinary row, not a contrived one. From there the two rules are told
332+ /// apart with no race at all — upwards keeps climbing off the stored
333+ /// value, the clock drags the stamp back down to itself. The lead is a
334+ /// second, far more than two writes can burn, and the guard below fails
335+ /// loudly rather than vacuously on a machine that manages to burn it.
336+ #[tokio::test]
337+ async fn a_stamp_ahead_of_the_clock_still_climbs() {
338+ const LEAD: i64 = 1_000;
339+
340+ let (db, _leases) = a_user_capped_at(1).await;
341+ let user = UserId::from_key(U);
342+ let thread = create_capped(&db, &user, None).await.expect("thread");
343+
344+ let parked = Timestamp::now().as_millis() + LEAD;
345+ sqlx::query("UPDATE rag_thread SET updated_at = $1 WHERE id = $2")
346+ .bind(parked)
347+ .bind(thread.get_id().uuid())
348+ .execute(&db)
349+ .await
350+ .unwrap();
351+
352+ for _ in 0..2 {
353+ rag_message::append_user(
354+ &db,
355+ thread.get_id(),
356+ &user,
357+ RagContent::try_new("selam").unwrap(),
358+ )
359+ .await
360+ .expect("append");
361+ }
362+ let stamped = read_for(&db, thread.get_id(), &user)
363+ .await
364+ .expect("re-read")
365+ .expect("still there")
366+ .get_updated_at()
367+ .as_millis();
368+
369+ assert!(
370+ Timestamp::now().as_millis() < parked,
371+ "the clock caught the {LEAD}ms lead up during two appends, so this \
372+ probe proves nothing"
373+ );
374+ assert_eq!(
375+ stamped,
376+ parked + 2,
377+ "two appends off a stamp of {parked} must leave {}: a stamp that \
378+ follows the clock instead is one an unchanged-row UPDATE elides",
379+ parked + 2
380+ );
381+ }
382+
383+ /// No turn may survive the delete that swept its thread. An orphan is not
384+ /// litter: nothing sweeps `rag_message` afterwards, and a `GET` on the
385+ /// turn would answer with the text of a thread the user had deleted.
386+ ///
387+ /// The window is between [`delete`]'s sweep and its commit:
388+ /// a create landing in there reads a thread that is still present
389+ /// (uncommitted) while the sweep ran on a snapshot predating the new row,
390+ /// so both commit. It is closed by making the create **write** the thread
391+ /// row ([`crate::db::rag_message`]'s insert) instead of reading it — the
392+ /// two transactions then touch one key and the store refuses to commit
393+ /// both.
394+ ///
395+ /// The window the schema event used to force open is the thread row's own
396+ /// lock now: a turn is written *through* the row, so a turn racing the
397+ /// delete serializes on that row instead of committing past the sweep. A
398+ /// barrier start lets both orders happen, and the invariant must hold in
399+ /// each.
400+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
401+ async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
402+ // One thread minted per round: the cap must cover every round, since
403+ // the rounds where the turn wins keep their thread (and its seat).
404+ let (db, _leases) = a_user_capped_at(8).await;
405+
406+ let user = UserId::from_key(U);
407+ let (mut orphans, mut swept) = (0, 0);
408+ for round in 0..8 {
409+ let thread = create_capped(&db, &user, None).await.expect("thread");
410+ let id = thread.get_id().clone();
411+
412+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
413+ let drop_it = {
414+ let (db, thread, gate) = (db.clone(), thread, gate.clone());
415+ tokio::spawn(async move {
416+ gate.wait().await;
417+ delete(&db, thread).await
418+ })
419+ };
420+ let turn = {
421+ let (id, db, user, gate) = (id.clone(), db.clone(), user, gate);
422+ tokio::spawn(async move {
423+ gate.wait().await;
424+ rag_message::append_user(
425+ &db,
426+ &id,
427+ &user,
428+ RagContent::try_new("selam").unwrap(),
429+ )
430+ .await
431+ .map(|_| ())
432+ })
433+ };
434+ let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
435+ // A 404 for the turn, or a NotFound for the delete, is a correct
436+ // answer — the only defect is stored state.
437+ assert!(
438+ !matches!(turn, Err(AppError::Db(_))),
439+ "round {round}: a raced turn must be answered, not 500: {turn:?}"
440+ );
441+
442+ // Stored state is the whole verdict; a return value is not evidence.
443+ if read_for(&db, &id, &user).await.unwrap().is_none() {
444+ swept += 1;
445+ orphans += rag_message::list_for_thread(&db, &id, None, 0)
446+ .await
447+ .unwrap()
448+ .1;
449+ } else if drop_it.is_ok() {
450+ panic!("round {round}: the delete reported success but the thread is still there");
451+ }
452+ }
453+ eprintln!("rag_thread::delete raced by a turn: {swept}/8 rounds deleted the thread");
454+ assert!(
455+ swept > 0,
456+ "no round ever deleted the thread, so the race never actually ran"
457+ );
458+ assert_eq!(orphans, 0, "a turn outlived its thread");
459+ }
460+}
src/domain/mod.rsmodified+2 -0
@@ -59,7 +59,9 @@ pub mod pool_question_image;
59 pub mod preferences;59 pub mod preferences;
60 pub mod profile;60 pub mod profile;
61 pub mod question_image;61 pub mod question_image;
62+pub mod rag_message;
62 pub mod rag_output;63 pub mod rag_output;
64+pub mod rag_thread;
63 pub mod registration;65 pub mod registration;
64 pub mod role;66 pub mod role;
65 pub mod session;67 pub mod session;
src/domain/rag_message.rsadded+316 -0
@@ -0,0 +1,316 @@
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+
17+use crate::constant::{MAX_CHATBOT_MESSAGE_LEN, RAG_PENDING_STALE_SECS, STALE_ERROR_CODE};
18+use crate::domain::monotonic_id::next_uuid;
19+use crate::domain::rag_thread::RagThreadId;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::ValidationError;
23+use crate::validate::validate_required;
24+use serde::{Deserialize, Serialize};
25+use sqlx::types::Json;
26+
27+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
28+#[sqlx(transparent)]
29+pub struct RagMessageId(uuid::Uuid);
30+
31+impl 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")]
69+pub enum RagMessageRole {
70+ User,
71+ Assistant,
72+}
73+
74+impl 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")]
88+pub enum RagMessageStatus {
89+ Pending,
90+ Complete,
91+ Failed,
92+}
93+
94+impl 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)]
110+pub struct RagContent(String);
111+
112+impl 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)]
136+pub 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)]
149+pub 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)]
159+pub 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+
174+impl 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)]
235+mod 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+}
src/domain/rag_thread.rsadded+115 -0
@@ -0,0 +1,115 @@
1+//! A RAG thread. It only groups turns and carries the ordering key the
2+//! list view sorts on: `updated_at` moves on every new turn, so a user's
3+//! threads list newest-activity-first. The turns themselves live in
4+//! [`crate::db::rag_message`], and deleting a thread cascades them; the
5+//! threads' own persistence lives in [`crate::db::rag_thread`].
6+//!
7+//! A user's RAG threads are capped per nest but on the **chatbot's knob**:
8+//! `app_user.rag_thread_count` holds this nest's seats, and the school's
9+//! `max_chatbot_threads` is the number both nests are read against — the two
10+//! are one package (`/chatbot` and `/rag` are both `Module::Chatbot`), and the
11+//! cap exists to bound what one account may store in a school's database, so
12+//! one knob governs the whole package. Each nest holds its own seats all the
13+//! same: a user at the cap in one nest may still open a thread in the other,
14+//! and the counter a claim moves counts exactly the rows it guards.
15+
16+use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN;
17+use crate::domain::monotonic_id::next_uuid;
18+use crate::domain::timestamp::Timestamp;
19+use crate::domain::user::UserId;
20+use crate::error::ValidationError;
21+use crate::validate::validate_required;
22+
23+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
24+#[sqlx(transparent)]
25+pub struct RagThreadId(uuid::Uuid);
26+
27+impl RagThreadId {
28+ /// Mints from the process-wide monotonic generator, not a plain random
29+ /// UUID: threads sort `updated_at DESC, id DESC` and the id breaks the tie
30+ /// between two threads last touched in the same millisecond,
31+ /// and a random low half sorts arbitrarily inside one millisecond.
32+ pub fn generate() -> Self {
33+ Self(next_uuid())
34+ }
35+
36+ /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
37+ /// cannot take the newtype. Static `query!` binds take `self` directly.
38+ pub fn uuid(&self) -> uuid::Uuid {
39+ self.0
40+ }
41+
42+ /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
43+ /// which matches no row.
44+ pub fn from_key(key: &str) -> Self {
45+ Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
46+ }
47+
48+ pub fn key(&self) -> String {
49+ self.0.to_string()
50+ }
51+}
52+
53+/// A user-chosen thread name. Required-and-bounded here; "untitled" is
54+/// `Option<RagThreadTitle>` on the row. Named like the chatbot's
55+/// ([`crate::domain::chatbot_thread::ChatbotThreadTitle`]) and bounded by the
56+/// same constant: a name is a line a user typed either way.
57+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
58+#[sqlx(transparent)]
59+pub struct RagThreadTitle(String);
60+
61+impl RagThreadTitle {
62+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
63+ validate_required("title", value, MAX_CHATBOT_THREAD_TITLE_LEN)?;
64+ Ok(Self(value.to_string()))
65+ }
66+
67+ pub fn as_str(&self) -> &str {
68+ &self.0
69+ }
70+}
71+
72+#[derive(Debug, Clone, sqlx::FromRow)]
73+pub struct RagThread {
74+ pub(crate) id: RagThreadId,
75+ /// The owning user. The column is `owner`, not the chatbot's `user_id` —
76+ /// the RAG nest stores no second participant a name had to disambiguate.
77+ pub(crate) owner: UserId,
78+ pub(crate) title: Option<RagThreadTitle>,
79+ pub(crate) created_at: Timestamp,
80+ pub(crate) updated_at: Timestamp,
81+}
82+
83+impl RagThread {
84+ pub fn get_id(&self) -> &RagThreadId {
85+ &self.id
86+ }
87+
88+ pub fn get_owner(&self) -> &UserId {
89+ &self.owner
90+ }
91+
92+ pub fn get_title(&self) -> Option<&RagThreadTitle> {
93+ self.title.as_ref()
94+ }
95+
96+ pub fn get_created_at(&self) -> Timestamp {
97+ self.created_at
98+ }
99+
100+ pub fn get_updated_at(&self) -> Timestamp {
101+ self.updated_at
102+ }
103+}
104+
105+#[cfg(test)]
106+mod tests {
107+ use super::*;
108+
109+ #[tokio::test]
110+ async fn title_is_required_and_bounded() {
111+ assert_eq!(RagThreadTitle::try_new("Fizik").unwrap().as_str(), "Fizik");
112+ assert!(RagThreadTitle::try_new(" ").is_err());
113+ assert!(RagThreadTitle::try_new(&"x".repeat(201)).is_err());
114+ }
115+}
src/lib.rsmodified+4 -1
@@ -56,7 +56,8 @@ use crate::web::module_gate::gate;
56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),56 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),57 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),58 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
59- (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),59+ (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."),
60+ (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
60 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),61 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),
61 (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),62 (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
62 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"),63 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"),
@@ -159,6 +160,7 @@ pub fn build_router(state: AppState) -> Router {
159 "/chatbot",160 "/chatbot",
160 gate(web::chatbot::routes(), &state, Module::Chatbot),161 gate(web::chatbot::routes(), &state, Module::Chatbot),
161 )162 )
163+ .nest("/rag", gate(web::rag::routes(), &state, Module::Chatbot))
162 .nest("/users", web::users::routes())164 .nest("/users", web::users::routes())
163 .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))165 .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))
164 .nest(166 .nest(
@@ -240,6 +242,7 @@ pub fn build_router(state: AppState) -> Router {
240 // rather than in `main`, so a router built anywhere gets the same behaviour.242 // rather than in `main`, so a router built anywhere gets the same behaviour.
241 api_limiter.share("api", state.db.clone());243 api_limiter.share("api", state.db.clone());
242 state.chatbot_limit.share("chatbot", state.db.clone());244 state.chatbot_limit.share("chatbot", state.db.clone());
245+ state.rag_limit.share("rag", state.db.clone());
243 let metrics = state.metrics.clone();246 let metrics = state.metrics.clone();
244 247
245 let cors_allowlist = cors_allowlist_from_env();248 let cors_allowlist = cors_allowlist_from_env();
src/main.rsmodified+1 -0
@@ -39,6 +39,7 @@ async fn main() -> anyhow::Result<()> {
39 cookie_secure: cfg.cookie_secure,39 cookie_secure: cfg.cookie_secure,
40 rate_limit: cfg.rate_limit.clone(),40 rate_limit: cfg.rate_limit.clone(),
41 chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),41 chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),
42+ rag_limit: UserRateLimiter::per_user_minute(cfg.rag_per_minute),
42 exam_presence: Default::default(),43 exam_presence: Default::default(),
43 board_hub: Default::default(),44 board_hub: Default::default(),
44 ai,45 ai,
src/service/course.rsmodified+60 -5
@@ -1,14 +1,16 @@
1 //! Course workflows: the catalog's CRUD — the template a şube attaches, with1 //! Course workflows: the catalog's CRUD — the template a şube attaches, with
2 //! no term, capacity or teacher list of its own any more (D1/D5/D6: staffing2 //! no term, capacity or teacher list of its own any more (D1/D5/D6: staffing
3-//! and roster live on the instances, [`crate::service::class_course`]) — and3+//! and roster live on the instances, [`crate::service::class_course`]) — the
4-//! the delete that collects the image/homework/note-file blob keys before the4+//! two gates over a catalog row every caller of those routes shares
5-//! guarded cascade sweeps those rows. The queries live in5+//! ([`can_manage_course`], [`can_view_course`]), and the delete that collects
6-//! [`crate::db::course`].6+//! the image/homework/note-file blob keys before the guarded cascade sweeps
7+//! those rows. The queries live in [`crate::db::course`].
7 8
8 use crate::database::Database;9 use crate::database::Database;
9 use crate::db::course;10 use crate::db::course;
10 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};11 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
11-use crate::domain::user::UserId;12+use crate::domain::role::Role;
13+use crate::domain::user::{User, UserId};
12 use crate::error::AppError;14 use crate::error::AppError;
13 15
14 /// Mint a catalog course. The catalog is not bound to a dönem (D1): exams are,16 /// Mint a catalog course. The catalog is not bound to a dönem (D1): exams are,
@@ -49,6 +51,59 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>,
49 course::list_by_ids(db, ids).await51 course::list_by_ids(db, ids).await
50 }52 }
51 53
54+/// Who may write the **catalog** row (edit it, delete it, write its
55+/// subjects): its creator, or anyone `manager` and above — and in every case
56+/// only while the caller is *still* `teacher` or above.
57+///
58+/// The `teacher` floor is enforced here rather than left to the callers: half
59+/// of them extract `CurrentUser`, not `RequireTeacher`, so a creator demoted
60+/// to `student` or `parent` would otherwise keep catalog rights forever (the
61+/// `creator` column is a historical fact and is never swept).
62+///
63+/// The teacher *assignment* list is gone from this row (D6): who teaches is
64+/// per instance now, and being assigned to one grants rights inside it — via
65+/// [`super::instance::can_manage_instance`] — never over the catalog.
66+///
67+/// It lives here, not in the web layer, because the gates over a catalog row
68+/// are a service rule the RAG surfaces read too ([`super::rag_scope`] scopes
69+/// what a course note's own reader may ask about).
70+pub fn can_manage_course(course: &Course, user: &User) -> bool {
71+ user.get_role().at_least(Role::Teacher)
72+ && (course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager))
73+}
74+
75+/// Who may read a catalog course (its details, its curriculum subjects):
76+/// anyone who can manage it, a teacher assigned to one of its **instances**,
77+/// and anyone the course reaches — a student enrolled in any of its instances,
78+/// or a member of the course itself. Other teachers and unenrolled students see
79+/// nothing.
80+///
81+/// The assigned-teacher arm is what keeps the catalog honest about the
82+/// instance layer: those teachers author homework and exam questions *inside*
83+/// the instance (D10 lets them), and every one of those routes needs a
84+/// `subject_id` belonging to this very course — so a `403` here would hand them
85+/// a picker they cannot fill. At HEAD the assignment list lived on the catalog
86+/// row and the arm came for free; after D6 it is read through the instances
87+/// they teach ([`list_for_teacher`]).
88+pub async fn can_view_course(
89+ course: &Course,
90+ user: &User,
91+ db: &Database,
92+) -> Result<bool, AppError> {
93+ if can_manage_course(course, user) {
94+ return Ok(true);
95+ }
96+ if user.get_role().at_least(Role::Teacher)
97+ && list_for_teacher(db, user.get_id())
98+ .await?
99+ .iter()
100+ .any(|taught| taught.get_id() == course.get_id())
101+ {
102+ return Ok(true);
103+ }
104+ crate::db::enrollment::user_is_in_course(db, course.get_id(), user.get_id()).await
105+}
106+
52 /// Only what the request carried is written: an omitted field (`None`) is107 /// Only what the request carried is written: an omitted field (`None`) is
53 /// not stored at all, so a concurrent PATCH of that field survives.108 /// not stored at all, so a concurrent PATCH of that field survives.
54 pub async fn update(109 pub async fn update(
src/service/instance.rsadded+115 -0
@@ -0,0 +1,115 @@
1+//! Instance visibility: the two questions every instance-scoped surface asks
2+//! before it reads or writes anything — whether this caller may act on one
3+//! instance, and which instances are theirs at all. Both lived in
4+//! [`crate::web::instances`] while the HTTP layer was their only caller; the
5+//! RAG scope deriver ([`super::rag_scope`]) asks the same two questions, and a
6+//! service may not reach up into the web layer — nor grow a second copy of a
7+//! rule that two surfaces must never disagree about.
8+//!
9+//! The D10 rule itself is [`super::class_course::ensure_instance_teacher`],
10+//! which [`can_manage_instance`] asks as a boolean so a route can word its own
11+//! `403`; the row reads are [`crate::db`]'s.
12+
13+use std::collections::HashSet;
14+
15+use crate::database::Database;
16+use crate::domain::class_course::{ClassCourse, ClassCourseId};
17+use crate::domain::class_group::ClassGroupId;
18+use crate::domain::role::Role;
19+use crate::domain::user::User;
20+use crate::error::AppError;
21+
22+/// Whether `user` may act inside this instance — D10, asked as a boolean so a
23+/// handler can word its own `403` (the one gate every instance-scoped route
24+/// shares; [`super::class_course::ensure_instance_teacher`] is the same rule
25+/// with the refusal in it).
26+pub async fn can_manage_instance(
27+ db: &Database,
28+ instance: &ClassCourseId,
29+ user: &User,
30+) -> Result<bool, AppError> {
31+ Ok(
32+ super::class_course::ensure_instance_teacher(db, user, instance)
33+ .await
34+ .is_ok(),
35+ )
36+}
37+
38+/// The instances a caller may see, each with whether they run it: the
39+/// instances their şubeler carry (a student's roster, and a homeroom
40+/// teacher's), the instances they were assigned to teach (a teacher), and —
41+/// for a homeroom teacher — their own şube's. The per-instance answer is the
42+/// same D10 rule every instance-scoped gate applies, computed once for the
43+/// list.
44+///
45+/// [`crate::web::instances`] serves this set to every caller as
46+/// `GET /instances/me`; the catalog-wide list other instance routes hand a
47+/// manager+ is [`crate::web::courses`]'. [`super::rag_scope`] scopes a RAG
48+/// question by it, which is why it lives here now.
49+///
50+/// Staff are *not* members of the section they run, so the two ways a teacher
51+/// reaches a şube are read separately and unioned: `class_member` (a student's
52+/// live stint) and the homeroom column (`class_group.teacher`, read through
53+/// [`super::class_group::list_for_teacher`]). Leaving the second out dropped
54+/// every row for a homeroom teacher who was neither enrolled nor assigned —
55+/// even though [`super::class_course::ensure_instance_teacher`] lets them act
56+/// on all of them.
57+pub async fn visible_instances(
58+ user: &User,
59+ db: &Database,
60+) -> Result<Vec<(ClassCourse, bool)>, AppError> {
61+ let mut rows: Vec<(ClassCourse, bool)> = Vec::new();
62+ // The şubeler the caller is a live member of, unioned with the ones they
63+ // are the homeroom teacher of (an empty second read for a student, and a
64+ // cheap one for anyone else — it is keyed on the teacher column).
65+ //
66+ // The homeroom half carries the live-`teacher` floor the whole gate does
67+ // (see [`super::class_course::ensure_instance_teacher`]): the column is
68+ // history, a role flip that never ran the cascade leaves it standing, and
69+ // an account below `teacher` may not keep reaching its sections — nor have
70+ // the `manages` flag that shows them the drafts.
71+ let staff = user.get_role().at_least(Role::Teacher);
72+ let (members, _) = crate::db::class_member::list_for_user(db, user.get_id(), None, 0).await?;
73+ let mut classes: Vec<ClassGroupId> = members
74+ .iter()
75+ .map(|member| member.get_class().clone())
76+ .collect();
77+ let homeroom = if staff {
78+ super::class_group::list_for_teacher(db, user.get_id()).await?
79+ } else {
80+ Vec::new()
81+ };
82+ let homeroom_keys: Vec<String> = homeroom.iter().map(|class| class.get_id().key()).collect();
83+ let mut seen: HashSet<String> = classes.iter().map(|class| class.key()).collect();
84+ classes.extend(
85+ homeroom
86+ .iter()
87+ .map(|class| class.get_id().clone())
88+ .filter(|class| seen.insert(class.key())),
89+ );
90+ for instance in crate::db::class_course::list_for_class_ids(db, &classes).await? {
91+ let manages = homeroom_keys.contains(&instance.get_class().key());
92+ rows.push((instance, manages));
93+ }
94+ // The instances the caller teaches: read through the catalog courses they
95+ // are assigned in (the junction has no teacher-keyed read of its own) and
96+ // kept only where the assignment actually names them.
97+ if user.get_role().at_least(Role::Teacher) {
98+ for course in super::course::list_for_teacher(db, user.get_id()).await? {
99+ let (taught, _) =
100+ crate::db::class_course::list_for_course(db, course.get_id(), None, 0).await?;
101+ for instance in taught {
102+ if rows
103+ .iter()
104+ .any(|(row, _)| row.get_id() == instance.get_id())
105+ {
106+ continue;
107+ }
108+ if can_manage_instance(db, instance.get_id(), user).await? {
109+ rows.push((instance, true));
110+ }
111+ }
112+ }
113+ }
114+ Ok(rows)
115+}
src/service/mod.rsmodified+4 -0
@@ -35,6 +35,7 @@ pub mod homework;
35 pub mod homework_file;35 pub mod homework_file;
36 pub mod homework_result;36 pub mod homework_result;
37 pub mod homework_submission;37 pub mod homework_submission;
38+pub mod instance;
38 pub mod karne;39 pub mod karne;
39 pub mod meal_attendance;40 pub mod meal_attendance;
40 pub mod meal_booking;41 pub mod meal_booking;
@@ -51,7 +52,10 @@ pub mod pool_question;
51 pub mod pool_question_image;52 pub mod pool_question_image;
52 pub mod profile;53 pub mod profile;
53 pub mod question_image;54 pub mod question_image;
55+pub mod rag_message;
54 pub mod rag_output;56 pub mod rag_output;
57+pub mod rag_scope;
58+pub mod rag_thread;
55 pub mod registration;59 pub mod registration;
56 pub mod session;60 pub mod session;
57 pub mod session_attendance;61 pub mod session_attendance;
src/service/rag_message.rsadded+98 -0
@@ -0,0 +1,98 @@
1+//! RAG message workflows: the turns of a thread. Sending is asynchronous by
2+//! design — the send path writes the user's question plus a `pending`
3+//! assistant row and answers at once; the answering task settles that row
4+//! later with [`complete`] or [`fail`], and the read paths present a
5+//! long-stale `pending` as failed via the domain's read-time projection
6+//! (see [`RagMessage::projected`]). The queries live in
7+//! [`crate::db::rag_message`].
8+
9+use crate::database::Database;
10+use crate::db::rag_message;
11+use crate::domain::rag_message::{RagContent, RagMessage, RagMessageId, RagReply};
12+use crate::domain::rag_thread::RagThreadId;
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+use sqlx::types::Json;
16+
17+/// Append the user's question. Nothing is awaited for it, so it is born
18+/// complete.
19+pub async fn append_user(
20+ db: &Database,
21+ thread: &RagThreadId,
22+ user: &UserId,
23+ content: RagContent,
24+) -> Result<RagMessage, AppError> {
25+ rag_message::append_user(db, thread, user, content).await
26+}
27+
28+/// Reserve the assistant's answer *before* the AI call: the row exists,
29+/// empty and `pending`, so a reload finds the turn and can wait on it.
30+pub async fn append_pending_assistant(
31+ db: &Database,
32+ thread: &RagThreadId,
33+ user: &UserId,
34+) -> Result<RagMessage, AppError> {
35+ rag_message::append_pending_assistant(db, thread, user).await
36+}
37+
38+/// The whole thread, oldest first — the order both the UI and the AI
39+/// history payload read in.
40+pub async fn list_for_thread(
41+ db: &Database,
42+ thread: &RagThreadId,
43+ limit: Option<i64>,
44+ offset: i64,
45+) -> Result<(Vec<RagMessage>, i64), AppError> {
46+ rag_message::list_for_thread(db, thread, limit, offset).await
47+}
48+
49+/// The last `limit` *settled* turns that carry text, still oldest-first —
50+/// the tail replayed to the AI service as context.
51+pub async fn list_settled_tail(
52+ db: &Database,
53+ thread: &RagThreadId,
54+ limit: usize,
55+) -> Result<Vec<RagMessage>, AppError> {
56+ rag_message::list_settled_tail(db, thread, limit).await
57+}
58+
59+/// The user turn a reserved answer belongs to, by *identity*: the question
60+/// row of the very POST that reserved it, whose id the answering task
61+/// carries.
62+pub async fn prompt_of(
63+ db: &Database,
64+ id: &RagMessageId,
65+) -> Result<Option<RagMessage>, AppError> {
66+ rag_message::prompt_of(db, id).await
67+}
68+
69+/// Read one turn only if `user` owns it — the poll loop's read.
70+pub async fn read_for(
71+ db: &Database,
72+ id: &RagMessageId,
73+ user: &UserId,
74+) -> Result<Option<RagMessage>, AppError> {
75+ rag_message::read_for(db, id, user).await
76+}
77+
78+/// Land the answer: its text and the service's reply (abstention, reason,
79+/// citations). Gated on `status = 'pending'`, so a late answer can't
80+/// overwrite a row that was already failed.
81+pub async fn complete(
82+ db: &Database,
83+ id: &RagMessageId,
84+ text: RagContent,
85+ reply: Json<RagReply>,
86+) -> Result<RagMessage, AppError> {
87+ rag_message::complete(db, id, text, reply).await
88+}
89+
90+/// Mark the answer failed with a short code (`unavailable`, the service's
91+/// own error code, …). Same pending gate as [`complete`].
92+pub async fn fail(
93+ db: &Database,
94+ id: &RagMessageId,
95+ error_code: &str,
96+) -> Result<RagMessage, AppError> {
97+ rag_message::fail(db, id, error_code).await
98+}
src/service/rag_scope.rsadded+356 -0
@@ -0,0 +1,356 @@
1+//! The `(sınıf, ders)` scope a RAG question is answered from.
2+//!
3+//! The RAG corpus is routed by the **pair** — a grade and a subject list sent
4+//! separately would cross-product into combinations the asker never named
5+//! ([`crate::constant::MAX_RAG_SCOPE_PAIRS`]) — so every question needs the set
6+//! of pairs its asker is allowed to retrieve from, and that set is derived
7+//! *here*, from the asker's own rows, never from the request body: a scope a
8+//! client could name is a scope a client could widen.
9+//!
10+//! The derivation is the school's own visibility rules, not a second copy of
11+//! them. A student's or a teacher's pairs are the courses their
12+//! [`super::instance::visible_instances`] teach them — the very set
13+//! `GET /instances/me` serves — and a club/etüt membership
14+//! ([`crate::db::course_membership`]) adds its subject with no grade, since a
15+//! school-scoped course belongs to no section. A parent has no sections of
16+//! their own, so their scope is their linked children's, read child by child
17+//! through the same reader: what a parent may ask about is exactly what their
18+//! children could be taught.
19+//!
20+//! Two consequences are deliberate. An empty scope is legal and returned as an
21+//! empty list — the service answers an unscopable question by abstaining, and a
22+//! `400` here would refuse questions the asker is entitled to ask. And a union
23+//! over the cap is **refused**, never narrowed: dropping pairs would answer a
24+//! question scoped to corpora the asker did not name, which is worse than no
25+//! answer at all.
26+
27+use std::collections::{HashMap, HashSet};
28+
29+use crate::ai::rag_chat::RagScopePair;
30+use crate::constant::MAX_RAG_SCOPE_PAIRS;
31+use crate::database::Database;
32+use crate::domain::class_course::ClassCourse;
33+use crate::domain::class_group::ClassGroupId;
34+use crate::domain::course::CourseId;
35+use crate::domain::role::Role;
36+use crate::domain::user::User;
37+use crate::error::{AppError, ValidationError};
38+
39+/// The `(sınıf, ders)` pairs `user`'s questions may be scoped to, in
40+/// first-seen order and deduped — one entry per distinct pair.
41+///
42+/// `role` is the caller's **live** session role, the same value the
43+/// `rag.chat` payload carries: the instance arm is the asker's own rows for
44+/// everyone but a parent (a section membership, a homeroom column and a
45+/// teaching assignment are all keyed on live roles anyway), and the parent
46+/// arm is the one that has to be chosen by role, because a parent's own
47+/// sections do not exist.
48+///
49+/// The instance arm reads its rows through [`super::instance::visible_instances`]
50+/// and the two lookup tables (the şubeler the pairs sit in and the titles of
51+/// every course named) in one batch read each — never one query per instance:
52+/// a teacher can be assigned to dozens of sections, and a per-row lookup would
53+/// spend the request's whole budget before the AI service is even called.
54+pub async fn for_user(
55+ db: &Database,
56+ user: &User,
57+ role: Role,
58+) -> Result<Vec<RagScopePair>, AppError> {
59+ let mut instances: Vec<ClassCourse> = Vec::new();
60+ if role == Role::Parent {
61+ // A parent's scope is what their children are taught — read through
62+ // the same visibility rule, one child at a time because the rule
63+ // keys on the person asking. A link whose student side changed role
64+ // is inert by construction: the demotion sweep takes their
65+ // memberships and enrollments with it, so the child simply has
66+ // nothing left to widen the parent into.
67+ for link in crate::db::parent_link::list_for_parent(db, user.get_id()).await? {
68+ let Some(child) = super::user::read(db, link.get_student()).await? else {
69+ continue;
70+ };
71+ instances.extend(
72+ super::instance::visible_instances(&child, db)
73+ .await?
74+ .into_iter()
75+ .map(|(instance, _)| instance),
76+ );
77+ }
78+ } else {
79+ instances.extend(
80+ super::instance::visible_instances(user, db)
81+ .await?
82+ .into_iter()
83+ .map(|(instance, _)| instance),
84+ );
85+ }
86+ // The school-scoped courses the asker joined directly (kulüp, etüt).
87+ // Every role may hold one — the table's own gate is the student role, so
88+ // for staff this read is simply empty.
89+ let memberships =
90+ crate::db::course_membership::list_for_user(db, user.get_id(), None, 0)
91+ .await?
92+ .0;
93+
94+ // One batch read per lookup, over every id the two arms named: the
95+ // şubeler decide each instance's grade, and the courses carry the titles
96+ // every pair is scoped by. Ids repeat freely — a class usually carries
97+ // several instances — and `list_by_ids` answers each row once.
98+ let class_ids: Vec<ClassGroupId> = instances
99+ .iter()
100+ .map(|instance| instance.get_class().clone())
101+ .collect();
102+ let mut course_ids: Vec<CourseId> = instances
103+ .iter()
104+ .map(|instance| instance.get_course().clone())
105+ .collect();
106+ course_ids.extend(
107+ memberships
108+ .iter()
109+ .map(|membership| membership.get_course().clone()),
110+ );
111+ let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?;
112+ let courses = crate::db::course::list_by_ids(db, &course_ids).await?;
113+
114+ // Grade labels, keyed by şube. A class with no grade at all (a
115+ // club-shaped section, and the shape a fixture class carries) simply
116+ // contributes no entry, so its instances scope the subject across every
117+ // grade — the documented meaning of an absent `sinif`.
118+ let grades: HashMap<String, String> = classes
119+ .iter()
120+ .filter_map(|class| {
121+ class
122+ .get_grade()
123+ .map(|grade| (class.get_id().key(), grade.as_str().to_owned()))
124+ })
125+ .collect();
126+ let titles: HashMap<String, String> = courses
127+ .iter()
128+ .map(|course| (course.get_id().key(), course.get_title().as_str().to_owned()))
129+ .collect();
130+
131+ let mut pairs: Vec<RagScopePair> = Vec::new();
132+ let mut seen: HashSet<(Option<String>, String)> = HashSet::new();
133+ for instance in &instances {
134+ // A course row the batch read did not answer is unreachable — the
135+ // instance's key is a foreign key — so the skip is a guard against a
136+ // dangling read, not a rule: a title-less pair could not be routed.
137+ let Some(ders) = titles.get(&instance.get_course().key()) else {
138+ continue;
139+ };
140+ push_pair(
141+ &mut pairs,
142+ &mut seen,
143+ grades.get(&instance.get_class().key()).cloned(),
144+ ders.clone(),
145+ );
146+ }
147+ for membership in &memberships {
148+ let Some(ders) = titles.get(&membership.get_course().key()) else {
149+ continue;
150+ };
151+ push_pair(&mut pairs, &mut seen, None, ders.clone());
152+ }
153+ // The cap is checked on the *union*: the dedup is what one frame would
154+ // carry, and it is exactly the number this refusal is about. Refused,
155+ // never truncated — see the module doc.
156+ if pairs.len() > MAX_RAG_SCOPE_PAIRS {
157+ return Err(AppError::Validation(ValidationError::TooLong {
158+ field: "scope",
159+ max: MAX_RAG_SCOPE_PAIRS,
160+ got: pairs.len(),
161+ }));
162+ }
163+ Ok(pairs)
164+}
165+
166+/// Append `pair` unless the very same pair is already in the list — a scope is
167+/// a set. Two şubeler at one grade teaching one course are one scope, and a
168+/// course attached to a section while also joined as a club contributes both
169+/// of its pairs; a duplicate would spend one of the cap's slots twice and hand
170+/// the service the same corpus under two entries.
171+fn push_pair(
172+ pairs: &mut Vec<RagScopePair>,
173+ seen: &mut HashSet<(Option<String>, String)>,
174+ sinif: Option<String>,
175+ ders: String,
176+) {
177+ if seen.insert((sinif.clone(), ders.clone())) {
178+ pairs.push(RagScopePair { sinif, ders });
179+ }
180+}
181+
182+#[cfg(test)]
183+mod tests {
184+ use super::*;
185+ use crate::domain::class_group::{ClassGrade, ClassGroupId, ClassName};
186+ use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
187+ use crate::domain::user::Username;
188+
189+ /// One scope pair, spelled the way the service reads the wire type.
190+ fn pair(sinif: Option<&str>, ders: &str) -> RagScopePair {
191+ RagScopePair {
192+ sinif: sinif.map(str::to_owned),
193+ ders: ders.to_owned(),
194+ }
195+ }
196+
197+ /// A real account at a role: every arm of the derivation judges the live
198+ /// row (and the membership and parent-link gates judge the exact role), so
199+ /// a fabricated id or the `fixture_user` default would not do.
200+ async fn person(db: &Database, username: &str, role: Role) -> User {
201+ crate::db::user::create_with_role(db, Username::try_new(username).unwrap(), None, role)
202+ .await
203+ .unwrap()
204+ }
205+
206+ /// A şube carrying a grade label — the half of every instance pair, since
207+ /// `a_class` deliberately has none.
208+ async fn graded_class(db: &Database, name: &str, grade: &str) -> ClassGroupId {
209+ let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
210+ crate::service::class_group::create(
211+ db,
212+ &office,
213+ ClassName::try_new(name).unwrap(),
214+ Some(ClassGrade::try_new(grade).unwrap()),
215+ None,
216+ None,
217+ )
218+ .await
219+ .unwrap()
220+ .get_id()
221+ .clone()
222+ }
223+
224+ /// Attach a catalog course to a şube, answering the instance.
225+ async fn attach(
226+ db: &Database,
227+ class: &ClassGroupId,
228+ title: &str,
229+ ) -> crate::domain::class_course::ClassCourse {
230+ let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
231+ let course = crate::db::class_member::tests::a_course(title, db).await;
232+ crate::service::class_course::attach(db, class, &course, &office)
233+ .await
234+ .unwrap()
235+ }
236+
237+ /// A student at a section's roster — the membership the instance half of
238+ /// the scope is read through.
239+ async fn enrolment(db: &Database, class: &ClassGroupId, student: &User) {
240+ let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
241+ crate::service::class_member::add(db, class, student.get_id(), &office)
242+ .await
243+ .unwrap();
244+ }
245+
246+ /// A student's pair is the şube's grade plus the course attached to it —
247+ /// the same set `GET /instances/me` hands them.
248+ #[tokio::test]
249+ async fn a_students_sections_scope_their_subjects() {
250+ let (db, _leases) = crate::database::init_test_db().await;
251+ let student = person(&db, "ragscope-student", Role::Student).await;
252+ let class = graded_class(&db, "5-A", "5").await;
253+ attach(&db, &class, "Matematik").await;
254+ enrolment(&db, &class, &student).await;
255+
256+ let scope = for_user(&db, &student, Role::Student).await.unwrap();
257+ assert_eq!(scope, vec![pair(Some("5"), "Matematik")]);
258+ }
259+
260+ /// A teacher reaches a section through the teaching assignment, not
261+ /// through a roster: the course they run is in scope exactly as it is for
262+ /// the students they teach.
263+ #[tokio::test]
264+ async fn an_assigned_teachers_subject_is_in_scope() {
265+ let (db, _leases) = crate::database::init_test_db().await;
266+ let teacher = person(&db, "ragscope-teacher", Role::Teacher).await;
267+ let class = graded_class(&db, "9-A", "9").await;
268+ let instance = attach(&db, &class, "Fizik").await;
269+ // The office staffing call minus its role gate: what this test reads
270+ // is the scope, not who may write the assignment row.
271+ crate::db::class_course_teacher::assign(&db, instance.get_id(), teacher.get_id())
272+ .await
273+ .unwrap();
274+
275+ let scope = for_user(&db, &teacher, Role::Teacher).await.unwrap();
276+ assert_eq!(scope, vec![pair(Some("9"), "Fizik")]);
277+ }
278+
279+ /// A parent has no sections of their own: their scope is the linked
280+ /// child's, and nobody else's — an unrelated student's section, graded the
281+ /// same or not, never widens it.
282+ #[tokio::test]
283+ async fn a_parents_scope_is_their_linked_childs() {
284+ let (db, _leases) = crate::database::init_test_db().await;
285+ let parent = person(&db, "ragscope-parent", Role::Parent).await;
286+ let child = person(&db, "ragscope-child", Role::Student).await;
287+ let stranger = person(&db, "ragscope-stranger", Role::Student).await;
288+ let child_class = graded_class(&db, "7-A", "7").await;
289+ attach(&db, &child_class, "Türkçe").await;
290+ enrolment(&db, &child_class, &child).await;
291+ let stranger_class = graded_class(&db, "7-B", "7").await;
292+ attach(&db, &stranger_class, "Türkçe").await;
293+ enrolment(&db, &stranger_class, &stranger).await;
294+ let office = crate::db::class_member::tests::fixture_user(&db, "ragscope-office").await;
295+ crate::service::parent_link::link(&db, parent.get_id(), child.get_id(), &office)
296+ .await
297+ .unwrap();
298+
299+ let scope = for_user(&db, &parent, Role::Parent).await.unwrap();
300+ assert_eq!(
301+ scope,
302+ vec![pair(Some("7"), "Türkçe")],
303+ "the linked child's section, and only that one"
304+ );
305+ }
306+
307+ /// A club or etüt is school-scoped: it belongs to no şube, so its subject
308+ /// is scoped with no grade at all.
309+ #[tokio::test]
310+ async fn a_club_membership_scopes_a_subject_with_no_grade() {
311+ let (db, _leases) = crate::database::init_test_db().await;
312+ let student = person(&db, "ragscope-club", Role::Student).await;
313+ let office = crate::db::class_member::tests::fixture_user(&db, "ragscope-office").await;
314+ let club = crate::db::course::create(
315+ &db,
316+ &office,
317+ CourseTitle::try_new("Satranç").unwrap(),
318+ CourseDescription::try_new("").unwrap(),
319+ CourseKind::try_new("club").unwrap(),
320+ )
321+ .await
322+ .unwrap();
323+ crate::db::course_membership::add(&db, club.get_id(), student.get_id(), &office)
324+ .await
325+ .unwrap();
326+
327+ let scope = for_user(&db, &student, Role::Student).await.unwrap();
328+ assert_eq!(scope, vec![pair(None, "Satranç")]);
329+ }
330+
331+ /// The same pair reached twice is one scope: two şubeler at one grade
332+ /// teaching one course are two instances and a single `(sınıf, ders)`,
333+ /// which is what the corpus is routed by.
334+ #[tokio::test]
335+ async fn a_pair_reached_twice_rides_once() {
336+ let (db, _leases) = crate::database::init_test_db().await;
337+ let student = person(&db, "ragscope-twice", Role::Student).await;
338+ let a = graded_class(&db, "6-A", "6").await;
339+ let b = graded_class(&db, "6-B", "6").await;
340+ attach(&db, &a, "Matematik").await;
341+ attach(&db, &b, "Matematik").await;
342+ enrolment(&db, &a, &student).await;
343+ enrolment(&db, &b, &student).await;
344+
345+ // Both sections really are the student's — the pair was reached twice.
346+ assert_eq!(
347+ crate::service::instance::visible_instances(&student, &db)
348+ .await
349+ .unwrap()
350+ .len(),
351+ 2
352+ );
353+ let scope = for_user(&db, &student, Role::Student).await.unwrap();
354+ assert_eq!(scope, vec![pair(Some("6"), "Matematik")]);
355+ }
356+}
src/service/rag_thread.rsadded+60 -0
@@ -0,0 +1,60 @@
1+//! RAG thread workflows: the create, rename and delete paths the RAG
2+//! surface drives, all scoped to the owning user — a foreign id reads as
3+//! absent. The queries live in [`crate::db::rag_thread`].
4+
5+use crate::database::Database;
6+use crate::db::rag_thread;
7+use crate::domain::rag_thread::{RagThread, RagThreadId, RagThreadTitle};
8+use crate::domain::user::UserId;
9+use crate::error::AppError;
10+
11+/// Start a thread unless `user` is already at the school's
12+/// `max_chatbot_threads` (409 at the cap — the cap is storage protection,
13+/// not a usage quota). The cap check and the row write are one atomic
14+/// conditional write, so two requests racing the same user's last slot
15+/// cannot both win. The knob is the chatbot nest's — one AI package, one
16+/// ceiling — while the seats are this nest's own.
17+pub async fn create_capped(
18+ db: &Database,
19+ user: &UserId,
20+ title: Option<RagThreadTitle>,
21+) -> Result<RagThread, AppError> {
22+ rag_thread::create_capped(db, user, title).await
23+}
24+
25+/// The caller's own threads, most recently active first.
26+pub async fn list_for_user(
27+ db: &Database,
28+ user: &UserId,
29+ limit: Option<i64>,
30+ offset: i64,
31+) -> Result<(Vec<RagThread>, i64), AppError> {
32+ rag_thread::list_for_user(db, user, limit, offset).await
33+}
34+
35+/// Read a thread only if `user` owns it — a foreign id reads as absent, so
36+/// the web layer answers 404 rather than leaking that it exists.
37+pub async fn read_for(
38+ db: &Database,
39+ id: &RagThreadId,
40+ user: &UserId,
41+) -> Result<Option<RagThread>, AppError> {
42+ rag_thread::read_for(db, id, user).await
43+}
44+
45+/// Rename the thread (`None` clears the name back to untitled), stamping
46+/// the edit as activity so the thread moves to the top of the list.
47+pub async fn rename(
48+ db: &Database,
49+ thread: &RagThread,
50+ title: Option<RagThreadTitle>,
51+) -> Result<RagThread, AppError> {
52+ rag_thread::rename(db, thread, title).await
53+}
54+
55+/// Delete the thread and every turn in it — one transaction, so a crash
56+/// can't orphan messages under a vanished thread — and give the owner's
57+/// cap slot back in the same transaction.
58+pub async fn delete(db: &Database, thread: RagThread) -> Result<RagThread, AppError> {
59+ rag_thread::delete(db, thread).await
60+}
src/state.rsmodified+5 -0
@@ -35,6 +35,11 @@ pub struct AppState {
35 /// caller is only known after `CurrentUser` has run, so handlers call it35 /// caller is only known after `CurrentUser` has run, so handlers call it
36 /// themselves.36 /// themselves.
37 pub chatbot_limit: UserRateLimiter,37 pub chatbot_limit: UserRateLimiter,
38+ /// Per-user RAG limit (see [`UserRateLimiter`], built from
39+ /// [`crate::config::Config::rag_per_minute`]). Not middleware: the
40+ /// caller is only known after `CurrentUser` has run, so handlers call it
41+ /// themselves.
42+ pub rag_limit: UserRateLimiter,
38 /// Who is inside which exam room right now (see [`ExamPresence`]).43 /// Who is inside which exam room right now (see [`ExamPresence`]).
39 pub exam_presence: ExamPresence,44 pub exam_presence: ExamPresence,
40 /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]).45 /// Live stroke fan-out for the shared whiteboards (see [`BoardHub`]).
src/web/ai.rsmodified+1 -0
@@ -132,6 +132,7 @@ pub struct CapabilityWorkers {
132 get,132 get,
133 path = "/capabilities",133 path = "/capabilities",
134 tag = "ai",134 tag = "ai",
135+ security(("session_cookie" = [])),
135 responses(136 responses(
136 (status = 200, description = "Every capability a connected worker serves, grouped and sorted", body = CapabilitiesResponse),137 (status = 200, description = "Every capability a connected worker serves, grouped and sorted", body = CapabilitiesResponse),
137 (status = 401, description = "No authenticated session", body = ErrorResponse),138 (status = 401, description = "No authenticated session", body = ErrorResponse),
src/web/attendance.rsmodified+1 -1
@@ -28,10 +28,10 @@ use crate::domain::session_attendance::SessionAttendance;
28 use crate::domain::term::Term;28 use crate::domain::term::Term;
29 use crate::domain::user::{User, UserId};29 use crate::domain::user::{User, UserId};
30 use crate::error::{AppError, ErrorResponse};30 use crate::error::{AppError, ErrorResponse};
31+use crate::service::instance::can_manage_instance;
31 use crate::service::parent_link::ensure_can_observe;32 use crate::service::parent_link::ensure_can_observe;
32 use crate::state::AppState;33 use crate::state::AppState;
33 34
34-use super::instances::can_manage_instance;
35 use super::{CourseResponse, CurrentUser, course_people, person_map};35 use super::{CourseResponse, CurrentUser, course_people, person_map};
36 36
37 pub fn routes() -> OpenApiRouter<AppState> {37 pub fn routes() -> OpenApiRouter<AppState> {
src/web/boards.rsmodified+1 -1
@@ -37,11 +37,11 @@ use crate::domain::event::EventId;
37 use crate::domain::role::Role;37 use crate::domain::role::Role;
38 use crate::domain::user::{User, UserId};38 use crate::domain::user::{User, UserId};
39 use crate::error::{AppError, ErrorResponse, ValidationError};39 use crate::error::{AppError, ErrorResponse, ValidationError};
40+use crate::service::course::can_manage_course;
40 use crate::service::{board, board_stroke};41 use crate::service::{board, board_stroke};
41 use crate::state::AppState;42 use crate::state::AppState;
42 use crate::tenant::Slug;43 use crate::tenant::Slug;
43 44
44-use super::courses::can_manage_course;
45 use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};45 use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};
46 46
47 pub fn routes() -> OpenApiRouter<AppState> {47 pub fn routes() -> OpenApiRouter<AppState> {
src/web/chatbot.rsmodified+7 -50
@@ -39,7 +39,7 @@ use utoipa_axum::routes;
39 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};39 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
40 use crate::ai::{AiBridge, AiError};40 use crate::ai::{AiBridge, AiError};
41 use crate::constant::{41 use crate::constant::{
42- AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS,42+ AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, REPLY_CHUNKS,
43 };43 };
44 use crate::database::Database;44 use crate::database::Database;
45 use crate::domain::chatbot_message::{45 use crate::domain::chatbot_message::{
@@ -53,7 +53,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
53 use crate::service;53 use crate::service;
54 use crate::state::{AppState, scoped_key};54 use crate::state::{AppState, scoped_key};
55 55
56-use super::{CurrentUser, Page, PageParams, ai_unavailable};56+use super::{CurrentUser, Page, PageParams, ai_unavailable, slice_reply, sse_error, sse_send};
57 57
58 pub fn routes() -> OpenApiRouter<AppState> {58 pub fn routes() -> OpenApiRouter<AppState> {
59 OpenApiRouter::new()59 OpenApiRouter::new()
@@ -768,12 +768,12 @@ async fn stream_message(
768 Ok(Some(message)) => message,768 Ok(Some(message)) => message,
769 // Deleted mid-stream (the thread went away) — say so and stop.769 // Deleted mid-stream (the thread went away) — say so and stop.
770 Ok(None) => {770 Ok(None) => {
771- send_error(&tx, "not_found", "this message no longer exists").await;771+ sse_error(&tx, "not_found", "this message no longer exists").await;
772 return;772 return;
773 }773 }
774 Err(err) => {774 Err(err) => {
775 tracing::warn!("chat stream read failed: {err}");775 tracing::warn!("chat stream read failed: {err}");
776- send_error(&tx, "internal", "could not read the message").await;776+ sse_error(&tx, "internal", "could not read the message").await;
777 return;777 return;
778 }778 }
779 };779 };
@@ -785,17 +785,17 @@ async fn stream_message(
785 MessageStatus::Pending => continue,785 MessageStatus::Pending => continue,
786 MessageStatus::Complete => {786 MessageStatus::Complete => {
787 for chunk in slice_reply(message.get_content().as_str()) {787 for chunk in slice_reply(message.get_content().as_str()) {
788- if send(&tx, "delta", json!({ "text": chunk })).await.is_err() {788+ if sse_send(&tx, "delta", json!({ "text": chunk })).await.is_err() {
789 return;789 return;
790 }790 }
791 }791 }
792 let done = json!({ "message": ChatbotMessageResponse::new(&message) });792 let done = json!({ "message": ChatbotMessageResponse::new(&message) });
793- let _ = send(&tx, "done", done).await;793+ let _ = sse_send(&tx, "done", done).await;
794 return;794 return;
795 }795 }
796 MessageStatus::Failed => {796 MessageStatus::Failed => {
797 let code = message.get_error_code().unwrap_or("failed");797 let code = message.get_error_code().unwrap_or("failed");
798- send_error(&tx, code, "the assistant could not answer this message").await;798+ sse_error(&tx, code, "the assistant could not answer this message").await;
799 return;799 return;
800 }800 }
801 }801 }
@@ -805,49 +805,6 @@ async fn stream_message(
805 Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default()))805 Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default()))
806 }806 }
807 807
808-type EventSender = mpsc::Sender<Result<Event, axum::Error>>;
809-
810-/// Queue one SSE event. `Err` means the client hung up — stop streaming.
811-async fn send(tx: &EventSender, name: &str, data: serde_json::Value) -> Result<(), ()> {
812- let event = Event::default()
813- .event(name)
814- .json_data(&data)
815- .unwrap_or_else(|err| {
816- tracing::error!("could not encode a chat SSE event: {err}");
817- Event::default()
818- .event("error")
819- .data("{\"code\":\"internal\"}")
820- });
821- tx.send(Ok(event)).await.map_err(|_| ())
822-}
823-
824-async fn send_error(tx: &EventSender, code: &str, message: &str) {
825- let _ = send(tx, "error", json!({ "code": code, "message": message })).await;
826-}
827-
828-/// Cut a finished answer into a handful of `delta` chunks.
829-///
830-/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and
831-/// this only lets the UI paint it progressively instead of in one jump. The
832-/// day the protocol grows chunk frames, this is the single function that goes
833-/// away — nothing else in the stream knows where a chunk came from.
834-///
835-/// Splits on character boundaries (never bytes: a clipped UTF-8 sequence would
836-/// render as garbage), and never returns an empty chunk. Short answers stay
837-/// whole — dribbling "hi" out one letter at a time is worse than not
838-/// pretending to stream at all.
839-fn slice_reply(text: &str) -> Vec<String> {
840- let chars: Vec<char> = text.chars().collect();
841- if chars.is_empty() {
842- return Vec::new();
843- }
844- let size = chars.len().div_ceil(REPLY_CHUNKS).max(MIN_CHUNK_CHARS);
845- chars
846- .chunks(size)
847- .map(|chunk| chunk.iter().collect())
848- .collect()
849-}
850-
851 #[cfg(test)]808 #[cfg(test)]
852 mod tests {809 mod tests {
853 use super::*;810 use super::*;
src/web/classes.rsmodified+1 -1
@@ -25,11 +25,11 @@ use crate::domain::course::CourseId;
25 use crate::domain::role::Role;25 use crate::domain::role::Role;
26 use crate::domain::user::{User, UserId};26 use crate::domain::user::{User, UserId};
27 use crate::error::{AppError, ErrorResponse, ValidationError};27 use crate::error::{AppError, ErrorResponse, ValidationError};
28+use crate::service::course::can_manage_course;
28 use crate::service::parent_link::ensure_can_observe;29 use crate::service::parent_link::ensure_can_observe;
29 use crate::service::{academic_year, class_blueprint, class_course, class_group, class_member};30 use crate::service::{academic_year, class_blueprint, class_course, class_group, class_member};
30 use crate::state::AppState;31 use crate::state::AppState;
31 32
32-use super::courses::can_manage_course;
33 use super::{33 use super::{
34 CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map,34 CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map,
35 remove_blob, set_or_clear, undo_if_demoted,35 remove_blob, set_or_clear, undo_if_demoted,
src/web/course_notes.rsmodified+1 -1
@@ -30,9 +30,9 @@ use crate::domain::rag_output::{RagOutput, RagOutputId};
30 use crate::error::{AppError, ErrorResponse};30 use crate::error::{AppError, ErrorResponse};
31 use crate::module::Module;31 use crate::module::Module;
32 use crate::service;32 use crate::service;
33+use crate::service::course::{can_manage_course, can_view_course};
33 use crate::state::AppState;34 use crate::state::AppState;
34 35
35-use super::courses::{can_manage_course, can_view_course};
36 use super::notes::content_disposition;36 use super::notes::content_disposition;
37 use super::{37 use super::{
38 CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path,38 CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path,
src/web/courses.rsmodified+10 -56
@@ -14,6 +14,7 @@ use crate::domain::subject::{SubjectDescription, SubjectName};
14 use crate::domain::user::{User, UserId};14 use crate::domain::user::{User, UserId};
15 use crate::error::{AppError, ErrorResponse};15 use crate::error::{AppError, ErrorResponse};
16 use crate::service;16 use crate::service;
17+use crate::service::course::{can_manage_course, can_view_course};
17 use crate::state::AppState;18 use crate::state::AppState;
18 19
19 use super::{20 use super::{
@@ -105,72 +106,25 @@ struct UpdateCourse {
105 kind: Option<String>,106 kind: Option<String>,
106 }107 }
107 108
108-/// Who may write the **catalog** row (edit it, delete it, write its
109-/// subjects): its creator, or anyone `manager` and above — and in every case
110-/// only while the caller is *still* `teacher` or above.
111-///
112-/// The `teacher` floor is enforced here rather than left to the callers: half
113-/// of them extract `CurrentUser`, not `RequireTeacher`, so a creator demoted
114-/// to `student` or `parent` would otherwise keep catalog rights forever (the
115-/// `creator` column is a historical fact and is never swept).
116-///
117-/// The teacher *assignment* list is gone from this row (D6): who teaches is
118-/// per instance now, and being assigned to one grants rights inside it — via
119-/// [`super::instances::can_manage_instance`] — never over the catalog.
120-pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool {
121- user.get_role().at_least(Role::Teacher)
122- && (course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager))
123-}
124-
125 /// Who may destroy a catalog row: its creator, or anyone `manager` and above.109 /// Who may destroy a catalog row: its creator, or anyone `manager` and above.
126-/// Carries the same live-`teacher` floor as [`can_manage_course`], and for the110+/// Carries the same live-`teacher` floor as
127-/// same reason: a demoted creator owns nothing.111+/// [`crate::service::course::can_manage_course`], and for the same reason: a
112+/// demoted creator owns nothing.
128 fn owns_course(course: &Course, user: &User) -> bool {113 fn owns_course(course: &Course, user: &User) -> bool {
129 can_manage_course(course, user)114 can_manage_course(course, user)
130 }115 }
131 116
132-/// Who may read a catalog course (its details, its curriculum subjects):
133-/// anyone who can manage it, a teacher assigned to one of its **instances**,
134-/// and anyone the course reaches — a student enrolled in any of its instances,
135-/// or a member of the course itself. Other teachers and unenrolled students see
136-/// nothing.
137-///
138-/// The assigned-teacher arm is what keeps the catalog honest about the
139-/// instance layer: those teachers author homework and exam questions *inside*
140-/// the instance (D10 lets them), and every one of those routes needs a
141-/// `subject_id` belonging to this very course — so a `403` here would hand them
142-/// a picker they cannot fill. At HEAD the assignment list lived on the catalog
143-/// row and the arm came for free; after D6 it is read through the instances
144-/// they teach ([`crate::service::course::list_for_teacher`]).
145-pub(crate) async fn can_view_course(
146- course: &Course,
147- user: &User,
148- db: &Database,
149-) -> Result<bool, AppError> {
150- if can_manage_course(course, user) {
151- return Ok(true);
152- }
153- if user.get_role().at_least(Role::Teacher)
154- && crate::service::course::list_for_teacher(db, user.get_id())
155- .await?
156- .iter()
157- .any(|taught| taught.get_id() == course.get_id())
158- {
159- return Ok(true);
160- }
161- crate::db::enrollment::user_is_in_course(db, course.get_id(), user.get_id()).await
162-}
163-
164 /// The catalog as one user sees it: every course for manager+, otherwise the117 /// The catalog as one user sees it: every course for manager+, otherwise the
165 /// courses they are assigned to teach somewhere plus the ones they're enrolled118 /// courses they are assigned to teach somewhere plus the ones they're enrolled
166 /// in, newest first.119 /// in, newest first.
167 ///120 ///
168 /// The taught half carries the same live-`teacher` floor as121 /// The taught half carries the same live-`teacher` floor as
169-/// [`can_manage_course`], and for the same reason: `creator` is a historical122+/// [`crate::service::course::can_manage_course`], and for the same reason:
170-/// column no demotion sweeps, so without it a demoted creator kept seeing the123+/// `creator` is a historical column no demotion sweeps, so without it a
171-/// course — and, through the `/exams` and `/homework` catalogs that build on124+/// demoted creator kept seeing the course — and, through the `/exams` and
172-/// this list, its published exams and homework. Below `teacher` a course is125+/// `/homework` catalogs that build on this list, its published exams and
173-/// visible only the way it is to any other student: by enrollment.126+/// homework. Below `teacher` a course is visible only the way it is to any
127+/// other student: by enrollment.
174 pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> {128 pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> {
175 if user.get_role().at_least(Role::Manager) {129 if user.get_role().at_least(Role::Manager) {
176 return service::course::list_all(db).await;130 return service::course::list_all(db).await;
src/web/exams/mod.rsmodified+2 -1
@@ -29,10 +29,11 @@ use crate::domain::timestamp::Timestamp;
29 use crate::domain::user::{User, UserId};29 use crate::domain::user::{User, UserId};
30 use crate::error::{AppError, ErrorResponse, ValidationError};30 use crate::error::{AppError, ErrorResponse, ValidationError};
31 use crate::service;31 use crate::service;
32+use crate::service::instance::{can_manage_instance, visible_instances};
32 use crate::state::AppState;33 use crate::state::AppState;
33 34
34 use super::bank_questions::BankQuestionResponse;35 use super::bank_questions::BankQuestionResponse;
35-use super::instances::{can_manage_instance, can_view_instance, visible_instances};36+use super::instances::can_view_instance;
36 use super::{37 use super::{
37 ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef,38 ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef,
38 RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,39 RequireTeacher, Scheduled, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,
src/web/homework.rsmodified+2 -1
@@ -34,10 +34,11 @@ use crate::domain::timestamp::Timestamp;
34 use crate::domain::user::UserId;34 use crate::domain::user::UserId;
35 use crate::error::{AppError, ErrorResponse, ValidationError};35 use crate::error::{AppError, ErrorResponse, ValidationError};
36 use crate::service;36 use crate::service;
37+use crate::service::instance::{can_manage_instance, visible_instances};
37 use crate::service::parent_link::ensure_can_observe;38 use crate::service::parent_link::ensure_can_observe;
38 use crate::state::AppState;39 use crate::state::AppState;
39 40
40-use super::instances::{can_manage_instance, can_view_instance, visible_instances};41+use super::instances::can_view_instance;
41 use super::notes::content_disposition;42 use super::notes::content_disposition;
42 use super::{43 use super::{
43 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,44 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,
src/web/instances.rsmodified+5 -98
@@ -12,7 +12,7 @@
12 //! and are split out per module so each still carries its own gate — see12 //! and are split out per module so each still carries its own gate — see
13 //! [`crate::web::module_gate`].13 //! [`crate::web::module_gate`].
14 14
15-use std::collections::{HashMap, HashSet};15+use std::collections::HashMap;
16 16
17 use crate::web::tenant_state::State;17 use crate::web::tenant_state::State;
18 use axum::Json;18 use axum::Json;
@@ -25,19 +25,18 @@ use utoipa_axum::routes;
25 25
26 use crate::database::Database;26 use crate::database::Database;
27 use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};27 use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati};
28-use crate::domain::class_group::ClassGroupId;
29 use crate::domain::course_session::SessionTopic;28 use crate::domain::course_session::SessionTopic;
30 use crate::domain::enrollment::Enrollment;29 use crate::domain::enrollment::Enrollment;
31 use crate::domain::exam::{30 use crate::domain::exam::{
32 ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle,31 ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle,
33 };32 };
34 use crate::domain::homework::HomeworkTitle;33 use crate::domain::homework::HomeworkTitle;
35-use crate::domain::role::Role;
36 use crate::domain::term::TermId;34 use crate::domain::term::TermId;
37 use crate::domain::timestamp::Timestamp;35 use crate::domain::timestamp::Timestamp;
38 use crate::domain::user::{User, UserId};36 use crate::domain::user::{User, UserId};
39 use crate::error::{AppError, ErrorResponse, ValidationError};37 use crate::error::{AppError, ErrorResponse, ValidationError};
40 use crate::service;38 use crate::service;
39+use crate::service::instance::{can_manage_instance, visible_instances};
41 use crate::state::AppState;40 use crate::state::AppState;
42 41
43 use super::homework::{description_or_none, resolve_assigned};42 use super::homework::{description_or_none, resolve_assigned};
@@ -267,22 +266,6 @@ async fn instance_or_404(key: &ClassCourseId, db: &Database) -> Result<ClassCour
267 .ok_or(AppError::NotFound)266 .ok_or(AppError::NotFound)
268 }267 }
269 268
270-/// Whether `user` may act inside this instance — D10, asked as a boolean so a
271-/// handler can word its own `403` (the one gate every instance-scoped route
272-/// shares; [`service::class_course::ensure_instance_teacher`] is the same rule
273-/// with the refusal in it).
274-pub(crate) async fn can_manage_instance(
275- db: &Database,
276- instance: &ClassCourseId,
277- user: &User,
278-) -> Result<bool, AppError> {
279- Ok(
280- service::class_course::ensure_instance_teacher(db, user, instance)
281- .await
282- .is_ok(),
283- )
284-}
285-
286 /// Who may read inside an instance: anyone who can manage it, plus its269 /// Who may read inside an instance: anyone who can manage it, plus its
287 /// enrolled students. Other teachers and unenrolled students see nothing.270 /// enrolled students. Other teachers and unenrolled students see nothing.
288 pub(crate) async fn can_view_instance(271 pub(crate) async fn can_view_instance(
@@ -300,84 +283,6 @@ pub(crate) async fn can_view_instance(
300 )283 )
301 }284 }
302 285
303-/// The instances a caller may see, each with whether they run it: the
304-/// instances their şubeler carry (a student's roster, and a homeroom
305-/// teacher's), the instances they were assigned to teach (a teacher), and —
306-/// for a homeroom teacher — their own şube's. The per-instance answer is the
307-/// same D10 rule every instance-scoped gate applies, computed once for the
308-/// list.
309-///
310-/// [`my_instances`] serves this set to every caller as `GET /instances/me`;
311-/// the catalog-wide list other instance routes hand a manager+ is
312-/// [`crate::web::courses`]'.
313-///
314-/// Staff are *not* members of the section they run, so the two ways a teacher
315-/// reaches a şube are read separately and unioned: `class_member` (a student's
316-/// live stint) and the homeroom column (`class_group.teacher`, read through
317-/// [`service::class_group::list_for_teacher`]). Leaving the second out dropped
318-/// every row for a homeroom teacher who was neither enrolled nor assigned —
319-/// even though [`service::class_course::ensure_instance_teacher`] lets them act
320-/// on all of them.
321-pub(crate) async fn visible_instances(
322- user: &User,
323- db: &Database,
324-) -> Result<Vec<(ClassCourse, bool)>, AppError> {
325- let mut rows: Vec<(ClassCourse, bool)> = Vec::new();
326- // The şubeler the caller is a live member of, unioned with the ones they
327- // are the homeroom teacher of (an empty second read for a student, and a
328- // cheap one for anyone else — it is keyed on the teacher column).
329- //
330- // The homeroom half carries the live-`teacher` floor the whole gate does
331- // (see [`service::class_course::ensure_instance_teacher`]): the column is
332- // history, a role flip that never ran the cascade leaves it standing, and
333- // an account below `teacher` may not keep reaching its sections — nor have
334- // the `manages` flag that shows them the drafts.
335- let staff = user.get_role().at_least(Role::Teacher);
336- let (members, _) = crate::db::class_member::list_for_user(db, user.get_id(), None, 0).await?;
337- let mut classes: Vec<ClassGroupId> = members
338- .iter()
339- .map(|member| member.get_class().clone())
340- .collect();
341- let homeroom = if staff {
342- service::class_group::list_for_teacher(db, user.get_id()).await?
343- } else {
344- Vec::new()
345- };
346- let homeroom_keys: Vec<String> = homeroom.iter().map(|class| class.get_id().key()).collect();
347- let mut seen: HashSet<String> = classes.iter().map(|class| class.key()).collect();
348- classes.extend(
349- homeroom
350- .iter()
351- .map(|class| class.get_id().clone())
352- .filter(|class| seen.insert(class.key())),
353- );
354- for instance in crate::db::class_course::list_for_class_ids(db, &classes).await? {
355- let manages = homeroom_keys.contains(&instance.get_class().key());
356- rows.push((instance, manages));
357- }
358- // The instances the caller teaches: read through the catalog courses they
359- // are assigned in (the junction has no teacher-keyed read of its own) and
360- // kept only where the assignment actually names them.
361- if user.get_role().at_least(Role::Teacher) {
362- for course in service::course::list_for_teacher(db, user.get_id()).await? {
363- let (taught, _) =
364- crate::db::class_course::list_for_course(db, course.get_id(), None, 0).await?;
365- for instance in taught {
366- if rows
367- .iter()
368- .any(|(row, _)| row.get_id() == instance.get_id())
369- {
370- continue;
371- }
372- if can_manage_instance(db, instance.get_id(), user).await? {
373- rows.push((instance, true));
374- }
375- }
376- }
377- }
378- Ok(rows)
379-}
380-
381 /// Join the people a page of instances names (their assigned teachers) in one286 /// Join the people a page of instances names (their assigned teachers) in one
382 /// batch read — the lookup shrinks with the window, never the whole table.287 /// batch read — the lookup shrinks with the window, never the whole table.
383 pub(crate) async fn instance_people(288 pub(crate) async fn instance_people(
@@ -397,7 +302,8 @@ pub(crate) async fn instance_people(
397 /// `{items, total, limit, offset}` envelope. The route a student reads to find302 /// `{items, total, limit, offset}` envelope. The route a student reads to find
398 /// the courses their section is being taught, and a teacher the ones they run.303 /// the courses their section is being taught, and a teacher the ones they run.
399 ///304 ///
400-/// The set is exactly [`visible_instances`]'s — the caller's şubeler (a305+/// The set is exactly
306+/// [`crate::service::instance::visible_instances`]'s — the caller's şubeler (a
401 /// student's live membership, a homeroom teacher's) unioned with the instances307 /// student's live membership, a homeroom teacher's) unioned with the instances
402 /// they were assigned to teach, deduped by instance. One rule for what the308 /// they were assigned to teach, deduped by instance. One rule for what the
403 /// caller may see, so this list and every instance-scoped gate can never309 /// caller may see, so this list and every instance-scoped gate can never
@@ -1067,6 +973,7 @@ async fn list_instance_sessions(
1067 #[cfg(test)]973 #[cfg(test)]
1068 mod tests {974 mod tests {
1069 use super::*;975 use super::*;
976+ use crate::domain::class_group::ClassGroupId;
1070 977
1071 /// The read path behind `GET /instances/me` is `class_member` → the şubeler978 /// The read path behind `GET /instances/me` is `class_member` → the şubeler
1072 /// → their instances. A student enrolled by a şube sees exactly that979 /// → their instances. A student enrolled by a şube sees exactly that
src/web/limits.rsmodified+58 -0
@@ -354,6 +354,43 @@ struct ChatbotLimits {
354 default_max_threads: i64,354 default_max_threads: i64,
355 }355 }
356 356
357+/// The RAG nest: a tier of its own — every message spends a retrieval over the
358+/// whole course-note corpus before it generates anything — plus the school
359+/// knobs it reuses from the chatbot. One `rag.chat` message is a chat message
360+/// in every way the newtypes check, so message length, thread titles, history
361+/// depth and the thread cap come from the same `/settings` fields; their fixed
362+/// ranges are published here a second time so a RAG client need not read the
363+/// chatbot group to bound its input.
364+#[derive(Serialize, ToSchema)]
365+struct RagLimits {
366+ /// Hard ceiling on the `(sınıf, ders)` scope pairs one ask may carry. The
367+ /// corpus is routed by the pair, so this bounds what one question can ask
368+ /// a retrieval to sweep.
369+ max_scope_pairs: usize,
370+ /// Hard ceiling on the citations one answer may store in its message row.
371+ max_citations: usize,
372+ /// Pages one citation may span. A citation names a page range, and an
373+ /// answer that could name every page of every document would be a copy of
374+ /// the corpus, not a citation.
375+ max_citation_pages: usize,
376+ /// The chatbot's message bound, reused.
377+ max_message_len: usize,
378+ /// The chatbot's thread-title bound, reused.
379+ max_thread_title_len: usize,
380+ /// The school-owned message-length setting's fixed range, reused.
381+ min_max_message_len: i64,
382+ max_max_message_len: i64,
383+ default_max_message_len: i64,
384+ /// The school-owned history-depth setting's fixed range, reused.
385+ min_history_turns: i64,
386+ max_history_turns: i64,
387+ default_history_turns: i64,
388+ /// The school-owned thread-cap setting's fixed range, reused.
389+ min_max_threads: i64,
390+ max_max_threads: i64,
391+ default_max_threads: i64,
392+}
393+
357 /// What a finished pomodoro stint must be to *count* — to move the lifetime394 /// What a finished pomodoro stint must be to *count* — to move the lifetime
358 /// counters the badges and the study streak read. Not a validation bound:395 /// counters the badges and the study streak read. Not a validation bound:
359 /// `POST /pomodoro/finish` never refuses a stint over these, it records it and396 /// `POST /pomodoro/finish` never refuses a stint over these, it records it and
@@ -441,6 +478,9 @@ struct RateLimits {
441 /// address, so it survives a changing IP).478 /// address, so it survives a changing IP).
442 #[schema(example = 20)]479 #[schema(example = 20)]
443 chatbot_per_minute: u32,480 chatbot_per_minute: u32,
481+ /// Per-*user* budget for sending RAG messages, keyed the same way.
482+ #[schema(example = 6)]
483+ rag_per_minute: u32,
444 }484 }
445 485
446 /// Rules that hold across every endpoint.486 /// Rules that hold across every endpoint.
@@ -477,6 +517,7 @@ struct LimitsResponse {
477 meal: MealLimits,517 meal: MealLimits,
478 payment: PaymentLimits,518 payment: PaymentLimits,
479 chatbot: ChatbotLimits,519 chatbot: ChatbotLimits,
520+ rag: RagLimits,
480 pomodoro: PomodoroLimits,521 pomodoro: PomodoroLimits,
481 board: BoardLimits,522 board: BoardLimits,
482 settings: SettingsLimits,523 settings: SettingsLimits,
@@ -643,6 +684,22 @@ impl LimitsResponse {
643 max_max_threads: MAX_MAX_CHATBOT_THREADS,684 max_max_threads: MAX_MAX_CHATBOT_THREADS,
644 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,685 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
645 },686 },
687+ rag: RagLimits {
688+ max_scope_pairs: MAX_RAG_SCOPE_PAIRS,
689+ max_citations: MAX_RAG_CITATIONS,
690+ max_citation_pages: MAX_RAG_CITATION_PAGES,
691+ max_message_len: MAX_CHATBOT_MESSAGE_LEN,
692+ max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,
693+ min_max_message_len: MIN_MAX_CHATBOT_MESSAGE_LEN,
694+ max_max_message_len: MAX_MAX_CHATBOT_MESSAGE_LEN,
695+ default_max_message_len: DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
696+ min_history_turns: MIN_CHATBOT_HISTORY_TURNS,
697+ max_history_turns: MAX_CHATBOT_HISTORY_TURNS,
698+ default_history_turns: DEFAULT_CHATBOT_HISTORY_TURNS,
699+ min_max_threads: MIN_MAX_CHATBOT_THREADS,
700+ max_max_threads: MAX_MAX_CHATBOT_THREADS,
701+ default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
702+ },
646 pomodoro: PomodoroLimits {703 pomodoro: PomodoroLimits {
647 min_counted_ms: MIN_COUNTED_POMODORO_MS,704 min_counted_ms: MIN_COUNTED_POMODORO_MS,
648 max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY,705 max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY,
@@ -673,6 +730,7 @@ impl LimitsResponse {
673 auth_per_minute: st.rate_limit.auth_per_minute,730 auth_per_minute: st.rate_limit.auth_per_minute,
674 api_per_minute: st.rate_limit.api_per_minute,731 api_per_minute: st.rate_limit.api_per_minute,
675 chatbot_per_minute: st.chatbot_limit.max_per_window(),732 chatbot_per_minute: st.chatbot_limit.max_per_window(),
733+ rag_per_minute: st.rag_limit.max_per_window(),
676 },734 },
677 request: RequestLimits {735 request: RequestLimits {
678 max_page_limit: MAX_PAGE_LIMIT,736 max_page_limit: MAX_PAGE_LIMIT,
src/web/marks.rsmodified+1 -1
@@ -30,11 +30,11 @@ use crate::domain::term::TermId;
30 use crate::domain::user::{User, UserId};30 use crate::domain::user::{User, UserId};
31 use crate::error::{AppError, ErrorResponse};31 use crate::error::{AppError, ErrorResponse};
32 use crate::service;32 use crate::service;
33+use crate::service::instance::can_manage_instance;
33 use crate::service::karne::KarneReport;34 use crate::service::karne::KarneReport;
34 use crate::service::parent_link::ensure_can_observe;35 use crate::service::parent_link::ensure_can_observe;
35 use crate::state::AppState;36 use crate::state::AppState;
36 37
37-use super::instances::can_manage_instance;
38 use super::{CourseResponse, CurrentUser, course_people, person_map};38 use super::{CourseResponse, CurrentUser, course_people, person_map};
39 39
40 pub fn routes() -> OpenApiRouter<AppState> {40 pub fn routes() -> OpenApiRouter<AppState> {
src/web/mod.rsmodified+61 -0
@@ -32,6 +32,7 @@ pub mod notes;
32 pub mod payments;32 pub mod payments;
33 pub mod pomodoro;33 pub mod pomodoro;
34 pub mod questions;34 pub mod questions;
35+pub mod rag;
35 pub mod room;36 pub mod room;
36 pub mod sessions;37 pub mod sessions;
37 pub mod settings;38 pub mod settings;
@@ -100,6 +101,66 @@ use crate::error::{AppError, ValidationError};
100 /// the caller's own: a demoted account may hold neither, and the row this101 /// the caller's own: a demoted account may hold neither, and the row this
101 /// request did not write is exactly the one a lost sweep left behind.102 /// request did not write is exactly the one a lost sweep left behind.
102 ///103 ///
104+/// The Sender half of one SSE turn stream. Shared by the chatbot and RAG
105+/// nests, which stream a finished answer identically.
106+pub(crate) type EventSender =
107+ tokio::sync::mpsc::Sender<Result<axum::response::sse::Event, axum::Error>>;
108+
109+/// Queue one SSE event. `Err` means the client hung up — stop streaming.
110+pub(crate) async fn sse_send(
111+ tx: &EventSender,
112+ name: &str,
113+ data: serde_json::Value,
114+) -> Result<(), ()> {
115+ let event = axum::response::sse::Event::default()
116+ .event(name)
117+ .json_data(&data)
118+ .unwrap_or_else(|err| {
119+ tracing::error!("could not encode an SSE event: {err}");
120+ axum::response::sse::Event::default()
121+ .event("error")
122+ .data("{\"code\":\"internal\"}")
123+ });
124+ tx.send(Ok(event)).await.map_err(|_| ())
125+}
126+
127+/// Queue the terminal `error` event, with a stable code the frontend branches
128+/// on and a human-readable message.
129+pub(crate) async fn sse_error(tx: &EventSender, code: &str, message: &str) {
130+ let _ = sse_send(
131+ tx,
132+ "error",
133+ serde_json::json!({ "code": code, "message": message }),
134+ )
135+ .await;
136+}
137+
138+/// Cut a finished answer into a handful of `delta` chunks.
139+///
140+/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and
141+/// this only lets the UI paint it progressively instead of in one jump. The
142+/// day the protocol grows chunk frames, this is the single function that goes
143+/// away — nothing else in the stream knows where a chunk came from.
144+///
145+/// Splits on character boundaries (never bytes: a clipped UTF-8 sequence would
146+/// render as garbage), and never returns an empty chunk. Short answers stay
147+/// whole — dribbling "hi" out one letter at a time is worse than not
148+/// pretending to stream at all.
149+pub(crate) fn slice_reply(text: &str) -> Vec<String> {
150+ let chars: Vec<char> = text.chars().collect();
151+ if chars.is_empty() {
152+ return Vec::new();
153+ }
154+ let size = chars
155+ .len()
156+ .div_ceil(crate::constant::REPLY_CHUNKS)
157+ .max(crate::constant::MIN_CHUNK_CHARS);
158+ chars
159+ .chunks(size)
160+ .map(|chunk| chunk.iter().collect())
161+ .collect()
162+}
163+
103 /// A missing user counts as demoted. The ordinary path is one extra read and no164 /// A missing user counts as demoted. The ordinary path is one extra read and no
104 /// write at all.165 /// write at all.
105 pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> {166 pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> {
src/web/rag.rsadded+860 -0
@@ -0,0 +1,860 @@
1+//! The RAG nest: browser ⇄ backend ⇄ AI service (over the QUIC bridge),
2+//! scoped to a school's course-note corpus.
3+//!
4+//! The relay contract is [`super::chatbot`]'s, shape for shape: the backend
5+//! owns everything except the answer — auth, the per-user rate limit, the
6+//! thread, the payload format, and the last look at the reply before it is
7+//! stored. There are no intent or rule tables, and every thread is private to
8+//! its owner. What differs is the **scope**: every question carries the
9+//! `(sınıf, ders)` pairs the corpus is routed by, derived server-side from the
10+//! asker's own memberships ([`crate::service::rag_scope`]) and never from the
11+//! request body, and every citation the service returns is resolved here to
12+//! the course-note file that owns the cited document — the `doc_id` only the
13+//! backend can turn into something a reader can open.
14+//!
15+//! The school's existing AI caps govern both nests: a RAG thread is reserved
16+//! against the same `max_chatbot_threads` seat count, a prompt and its answer
17+//! are bounded by the same `max_chatbot_message_len`, and the history replayed
18+//! to the service is the same `chatbot_history_turns` window. Only the
19+//! per-minute tier is RAG's own (`DEFAULT_RAG_RATE_LIMIT`), because every
20+//! message here spends a retrieval over the whole corpus before it generates
21+//! anything.
22+//!
23+//! Sending is asynchronous by design. `POST .../messages` writes the user's
24+//! turn plus an empty `pending` assistant row and answers `202` immediately;
25+//! a retrieval-then-answer round trip can outlast the request-timeout layer
26+//! that guards every HTTP handler, so nothing is awaited on the request path.
27+//! The client then either polls `GET .../messages/{mid}` or opens its SSE
28+//! stream — both read the same row, so they can never disagree.
29+//!
30+//! The bridge round trip runs in a `tokio::spawn` the POST leaves behind. A
31+//! restart therefore orphans a turn in flight: its row stays `pending` until a
32+//! reader projects it failed, and the boot sweep stamps that verdict durably
33+//! ([`crate::constant::RAG_PENDING_STALE_SECS`]).
34+
35+use std::time::Duration;
36+
37+use crate::tenant::ResolvedTenant;
38+use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
39+use axum::Json;
40+use axum::extract::{Path, Query};
41+use axum::http::StatusCode;
42+use axum::response::sse::{Event, KeepAlive, Sse};
43+use axum::response::{IntoResponse, Response};
44+use serde::{Deserialize, Serialize};
45+use serde_json::json;
46+use sqlx::types::Json as SqlJson;
47+use tokio::sync::mpsc;
48+use tokio_stream::Stream;
49+use tokio_stream::wrappers::ReceiverStream;
50+use utoipa::ToSchema;
51+use utoipa_axum::router::OpenApiRouter;
52+use utoipa_axum::routes;
53+
54+use crate::ai::chat::ChatRole;
55+use crate::ai::rag_chat::RagScopePair;
56+use crate::ai::AiBridge;
57+use crate::constant::{
58+ AI_RAG_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, REPLY_CHUNKS,
59+};
60+use crate::database::Database;
61+use crate::domain::rag_message::{
62+ RagCitedFile, RagContent, RagMessage, RagMessageId, RagMessageRole, RagMessageStatus,
63+};
64+use crate::domain::rag_thread::{RagThread, RagThreadId, RagThreadTitle};
65+use crate::domain::role::Role;
66+use crate::domain::settings::Settings;
67+use crate::domain::user::UserId;
68+use crate::error::{AppError, ErrorResponse, ValidationError};
69+use crate::service;
70+use crate::state::{AppState, scoped_key};
71+
72+use super::{CurrentUser, Page, PageParams, ai_unavailable, slice_reply, sse_error, sse_send};
73+
74+pub fn routes() -> OpenApiRouter<AppState> {
75+ OpenApiRouter::new()
76+ .routes(routes!(create_thread, list_threads))
77+ .routes(routes!(rename_thread, delete_thread))
78+ .routes(routes!(list_messages, send_message))
79+ .routes(routes!(read_message))
80+ .routes(routes!(stream_message))
81+}
82+
83+// ---- threads ----------------------------------------------------------
84+
85+#[derive(Deserialize, ToSchema)]
86+struct CreateRagThread {
87+ /// Optional thread name, up to 200 characters. Blank counts as absent —
88+ /// an untitled thread is normal (the UI labels it from its first turn).
89+ #[schema(max_length = 200, example = "Fizik ödevi")]
90+ title: Option<String>,
91+}
92+
93+/// One RAG thread. `updated_at` moves on every turn, and the list is sorted by
94+/// it, so the thread just written to is always first.
95+#[derive(Serialize, ToSchema)]
96+struct RagThreadResponse {
97+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
98+ id: String,
99+ #[schema(example = "Fizik ödevi")]
100+ title: Option<String>,
101+ /// UTC unix-milliseconds, server-stamped.
102+ created_at: i64,
103+ /// UTC unix-milliseconds of the last turn, server-stamped.
104+ updated_at: i64,
105+}
106+
107+impl RagThreadResponse {
108+ fn new(thread: &RagThread) -> Self {
109+ Self {
110+ id: thread.get_id().key().to_string(),
111+ title: thread.get_title().map(|title| title.as_str().to_string()),
112+ created_at: thread.get_created_at().as_millis(),
113+ updated_at: thread.get_updated_at().as_millis(),
114+ }
115+ }
116+}
117+
118+/// Start a new RAG thread, optionally named. Every authenticated role may ask
119+/// — parents included. A user may keep up to the school's
120+/// `max_chatbot_threads` threads *across both AI nests*; at the cap the
121+/// request is refused (409) until an old thread is deleted — the cap is
122+/// storage protection, not a usage quota (that is the per-minute message
123+/// limit).
124+#[utoipa::path(
125+ post,
126+ path = "/threads",
127+ tag = "rag",
128+ security(("session_cookie" = [])),
129+ request_body = CreateRagThread,
130+ responses(
131+ (status = 201, description = "The new thread", body = RagThreadResponse),
132+ (status = 400, description = "Invalid title", body = ErrorResponse),
133+ (status = 401, description = "Not authenticated", body = ErrorResponse),
134+ (status = 409, description = "At the school's thread cap", body = ErrorResponse),
135+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
136+ ),
137+)]
138+async fn create_thread(
139+ State(st): State<AppState>,
140+ CurrentUser(user): CurrentUser,
141+ Json(req): Json<CreateRagThread>,
142+) -> Result<(StatusCode, Json<RagThreadResponse>), AppError> {
143+ // Blank is "untitled", not an error — the same rule the chatbot nest
144+ // applies to a thread name.
145+ let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
146+ "" => None,
147+ value => Some(RagThreadTitle::try_new(value)?),
148+ };
149+
150+ // The cap is checked and the row written as one critical section in the
151+ // domain: counting here and creating after would over-admit under
152+ // concurrency (the database does not serialize a count against inserts).
153+ let thread = service::rag_thread::create_capped(&st.db, user.get_id(), title).await?;
154+ Ok((
155+ StatusCode::CREATED,
156+ Json(RagThreadResponse::new(&thread)),
157+ ))
158+}
159+
160+/// The caller's own threads, most recently active first. Paged via
161+/// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.
162+#[utoipa::path(
163+ get,
164+ path = "/threads",
165+ tag = "rag",
166+ security(("session_cookie" = [])),
167+ params(PageParams),
168+ responses(
169+ (status = 200, description = "A page of the caller's threads", body = Page<RagThreadResponse>),
170+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
171+ (status = 401, description = "Not authenticated", body = ErrorResponse),
172+ ),
173+)]
174+async fn list_threads(
175+ State(st): State<AppState>,
176+ CurrentUser(user): CurrentUser,
177+ Query(page): Query<PageParams>,
178+) -> Result<Json<Page<RagThreadResponse>>, AppError> {
179+ let (limit, offset) = page.resolve()?;
180+ let (threads, total) =
181+ service::rag_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?;
182+ let items = threads.iter().map(RagThreadResponse::new).collect();
183+ Ok(Json(Page::new(items, total, limit, offset)))
184+}
185+
186+#[derive(Deserialize, ToSchema)]
187+struct RenameRagThread {
188+ /// The new name, up to 200 characters. `null` — or blank — clears it back
189+ /// to untitled, the same rule the create route applies.
190+ #[schema(max_length = 200, example = "Fizik ödevi")]
191+ title: Option<String>,
192+}
193+
194+/// Rename a thread, or clear its name (`title: null`). Owner only; someone
195+/// else's thread is a `404`, never a `403`. The edit counts as activity, so the
196+/// thread moves to the top of the list.
197+///
198+/// Nothing names a thread automatically: the first message is not turned into
199+/// a title, and the AI service is never asked for one.
200+#[utoipa::path(
201+ patch,
202+ path = "/threads/{id}",
203+ tag = "rag",
204+ security(("session_cookie" = [])),
205+ params(("id" = String, Path, description = "RagThread id")),
206+ request_body = RenameRagThread,
207+ responses(
208+ (status = 200, description = "The renamed thread", body = RagThreadResponse),
209+ (status = 400, description = "Invalid title", body = ErrorResponse),
210+ (status = 401, description = "Not authenticated", body = ErrorResponse),
211+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
212+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
213+ ),
214+)]
215+async fn rename_thread(
216+ State(st): State<AppState>,
217+ CurrentUser(user): CurrentUser,
218+ Path(id): Path<String>,
219+ Json(req): Json<RenameRagThread>,
220+) -> Result<Json<RagThreadResponse>, AppError> {
221+ let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
222+ "" => None,
223+ value => Some(RagThreadTitle::try_new(value)?),
224+ };
225+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
226+ let renamed = service::rag_thread::rename(&st.db, &thread, title).await?;
227+ Ok(Json(RagThreadResponse::new(&renamed)))
228+}
229+
230+/// Delete a thread and every turn in it, permanently. Owner only; someone
231+/// else's thread is a `404`, never a `403` (its existence is not leaked).
232+#[utoipa::path(
233+ delete,
234+ path = "/threads/{id}",
235+ tag = "rag",
236+ security(("session_cookie" = [])),
237+ params(("id" = String, Path, description = "RagThread id")),
238+ responses(
239+ (status = 204, description = "Deleted, with its messages"),
240+ (status = 401, description = "Not authenticated", body = ErrorResponse),
241+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
242+ ),
243+)]
244+async fn delete_thread(
245+ State(st): State<AppState>,
246+ CurrentUser(user): CurrentUser,
247+ Path(id): Path<String>,
248+) -> Result<StatusCode, AppError> {
249+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
250+ service::rag_thread::delete(&st.db, thread).await?;
251+ Ok(StatusCode::NO_CONTENT)
252+}
253+
254+/// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
255+/// from a missing one.
256+async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<RagThread, AppError> {
257+ service::rag_thread::read_for(db, &RagThreadId::from_key(id), user)
258+ .await?
259+ .ok_or(AppError::NotFound)
260+}
261+
262+// ---- turns ------------------------------------------------------------------
263+
264+#[derive(Deserialize, ToSchema)]
265+struct SendRagMessage {
266+ /// What to ask. Required. `maxLength` here is the server's hard ceiling;
267+ /// the live cap is the school's `max_chatbot_message_len` (`GET /settings`),
268+ /// which is always at or below it — the same knob the chatbot nest uses.
269+ #[schema(
270+ example = "Newton'un ikinci yasasını açıklar mısın?",
271+ max_length = 8_000
272+ )]
273+ content: String,
274+}
275+
276+/// The receipt for an accepted turn. The answer is *not* here: it is being
277+/// retrieved and generated. Poll `GET /rag/threads/{id}/messages/{mid}` or
278+/// open its `/stream`.
279+#[derive(Serialize, ToSchema)]
280+struct AcceptedResponse {
281+ /// The assistant row reserved for the answer.
282+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
283+ message_id: String,
284+ /// Always `pending` — that is what "accepted" means here.
285+ #[schema(example = "pending")]
286+ status: String,
287+}
288+
289+/// One citation behind an answer, already resolved to something openable.
290+#[derive(Serialize, ToSchema)]
291+struct RagCitationResponse {
292+ /// The marker the answer text points at: `[N]` in `content` resolves to
293+ /// the citation whose `n` is `N`.
294+ #[schema(example = 1)]
295+ n: u32,
296+ /// The `course_note_file` record key the service's corpus `doc_id` was
297+ /// resolved through — fetch the file from
298+ /// `/course-note-files/{id}/content`. `null` while no file the asker may
299+ /// view claims that document (identical PDF bytes resolve to the same
300+ /// `doc_id`, so a citation may point at a file in a course this asker
301+ /// cannot read); the passage is still citable, just not openable.
302+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
303+ file: Option<String>,
304+ /// The page numbers within the document the passage spans.
305+ #[schema(example = json!([3, 4]))]
306+ pages: Vec<i64>,
307+ /// Opaque retrieval span ids within the document, for a client that
308+ /// highlights the exact passage.
309+ span_ids: Vec<String>,
310+ /// The subject the passage belongs to, when the corpus records one.
311+ #[schema(example = "Fizik")]
312+ ders: Option<String>,
313+}
314+
315+impl From<&RagCitedFile> for RagCitationResponse {
316+ fn from(citation: &RagCitedFile) -> Self {
317+ Self {
318+ n: citation.n,
319+ file: citation.file.clone(),
320+ pages: citation.pages.clone(),
321+ span_ids: citation.span_ids.clone(),
322+ ders: citation.ders.clone(),
323+ }
324+ }
325+}
326+
327+/// One turn. `content` is empty while `status` is `pending`; `error_code` is
328+/// set only when `status` is `failed`.
329+#[derive(Serialize, ToSchema)]
330+struct RagMessageResponse {
331+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
332+ id: String,
333+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
334+ thread_id: String,
335+ /// `user` or `assistant`.
336+ #[schema(example = "assistant")]
337+ role: String,
338+ /// `pending`, `complete`, or `failed`. A user turn is always `complete`.
339+ #[schema(example = "complete")]
340+ status: String,
341+ content: String,
342+ /// `true` when the service declined to answer — a complete, successful
343+ /// turn, not a failure. `reason` says why (`guard_*`, `insufficient_data`,
344+ /// `model_abstained`, …).
345+ #[schema(example = false)]
346+ abstained: bool,
347+ /// The abstention's short machine code; `""` on an ordinary answer and on
348+ /// every user turn.
349+ #[schema(example = "insufficient_data")]
350+ reason: String,
351+ /// The passages the answer drew on, oldest first. Empty on a user turn,
352+ /// on a pending one and on a failed one.
353+ citations: Vec<RagCitationResponse>,
354+ /// Short machine-readable reason when `status` is `failed`:
355+ /// `unavailable`, `busy`, `timed_out`, `transport`, `protocol`,
356+ /// `bad_reply`, `empty_reply`, `interrupted`, or a code the AI service
357+ /// itself returned.
358+ #[schema(example = "timed_out")]
359+ error_code: Option<String>,
360+ /// UTC unix-milliseconds, server-stamped.
361+ created_at: i64,
362+ /// When the turn settled (complete or failed); `null` while pending.
363+ completed_at: Option<i64>,
364+}
365+
366+impl RagMessageResponse {
367+ fn new(message: &RagMessage) -> Self {
368+ let reply = message.get_reply();
369+ Self {
370+ id: message.get_id().key().to_string(),
371+ thread_id: message.get_thread_id().key().to_string(),
372+ role: message.get_role().as_str().to_string(),
373+ status: message.get_status().as_str().to_string(),
374+ content: message.get_content().as_str().to_string(),
375+ abstained: reply.is_some_and(|reply| reply.abstained),
376+ reason: reply.map(|reply| reply.reason.clone()).unwrap_or_default(),
377+ citations: reply
378+ .map(|reply| reply.citations.iter().map(Into::into).collect())
379+ .unwrap_or_default(),
380+ error_code: message.get_error_code().map(str::to_string),
381+ created_at: message.get_created_at().as_millis(),
382+ completed_at: message.get_completed_at().map(|at| at.as_millis()),
383+ }
384+ }
385+}
386+
387+/// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.
388+#[utoipa::path(
389+ get,
390+ path = "/threads/{id}/messages",
391+ tag = "rag",
392+ security(("session_cookie" = [])),
393+ params(("id" = String, Path, description = "RagThread id"), PageParams),
394+ responses(
395+ (status = 200, description = "A page of the thread's turns", body = Page<RagMessageResponse>),
396+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
397+ (status = 401, description = "Not authenticated", body = ErrorResponse),
398+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
399+ ),
400+)]
401+async fn list_messages(
402+ State(st): State<AppState>,
403+ CurrentUser(user): CurrentUser,
404+ Path(id): Path<String>,
405+ Query(page): Query<PageParams>,
406+) -> Result<Json<Page<RagMessageResponse>>, AppError> {
407+ let (limit, offset) = page.resolve()?;
408+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
409+ let (messages, total) =
410+ service::rag_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?;
411+ let items = messages.iter().map(RagMessageResponse::new).collect();
412+ Ok(Json(Page::new(items, total, limit, offset)))
413+}
414+
415+/// Ask the corpus a question: `{content}`, at most the school's
416+/// `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the
417+/// moment both rows are written — the answer itself lands later, in the
418+/// reserved assistant row. `503` when no AI service offers `rag.chat`, and
419+/// nothing is written; `429` + `Retry-After` over the per-user send limit.
420+///
421+/// Order matters and is deliberate: ownership is settled first (a foreign
422+/// thread is a `404` and is never charged), then the per-user rate limit (a
423+/// refused turn leaves no trace), then availability (so an unavailable service
424+/// produces a `503` and no dead pending row), then the scope the question is
425+/// asked under — derived from the asker's own memberships, never from the
426+/// body. Once the rows are written the turn always settles: the answering task
427+/// stamps `complete`/`failed`, a reader projects a long-stale `pending` as
428+/// failed, and the boot sweep repairs whatever a process death left behind.
429+#[utoipa::path(
430+ post,
431+ path = "/threads/{id}/messages",
432+ tag = "rag",
433+ security(("session_cookie" = [])),
434+ params(("id" = String, Path, description = "RagThread id")),
435+ request_body = SendRagMessage,
436+ responses(
437+ (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse),
438+ (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`, or a scope past `MAX_RAG_SCOPE_PAIRS`", body = ErrorResponse),
439+ (status = 401, description = "Not authenticated", body = ErrorResponse),
440+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
441+ (status = 429, description = "Over the per-user send limit; retry after the advertised delay", body = ErrorResponse),
442+ (status = 503, description = "No AI service offers `rag.chat` right now; nothing was written", body = ErrorResponse),
443+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
444+ ),
445+)]
446+async fn send_message(
447+ State(st): State<AppState>,
448+ SchoolSlug(slug): SchoolSlug,
449+ tenant: ResolvedTenant,
450+ CurrentUser(user): CurrentUser,
451+ Path(id): Path<String>,
452+ Json(req): Json<SendRagMessage>,
453+) -> Result<Response, AppError> {
454+ // Ownership first: a foreign thread is a 404, never a 403 — and a 404 must
455+ // not spend the asker's minute.
456+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
457+
458+ // Then the tier. Charged before anything is written, so a refused turn
459+ // leaves no row behind.
460+ st.rag_limit
461+ .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?;
462+
463+ let settings = service::settings::load(&st.db).await?;
464+ let reply_cap = content_cap(&settings);
465+ let length = req.content.chars().count();
466+ if length > reply_cap {
467+ return Err(AppError::Validation(ValidationError::TooLong {
468+ field: "content",
469+ max: reply_cap,
470+ got: length,
471+ }));
472+ }
473+ let content = RagContent::try_new(&req.content)?;
474+
475+ // The 503 gate, and the only place it is evaluated. `has_capability` is
476+ // documented racy — that is fine here: it never guards a write, it only
477+ // spares the user a thread full of rows nothing could ever answer.
478+ let Some(bridge) = st.ai.clone() else {
479+ return Ok(ai_unavailable(
480+ "the AI service is not enabled on this deployment",
481+ ));
482+ };
483+ if !bridge.has_capability(AI_RAG_CHAT_CAPABILITY) {
484+ return Ok(ai_unavailable("no AI service is connected right now"));
485+ }
486+
487+ // The scope the corpus is routed by, derived from the asker's own
488+ // memberships on every question — never from the body, so a student cannot
489+ // widen their own retrieval, and never from a stored copy, so a
490+ // membership change takes effect on the next question. An empty scope is
491+ // legal and is sent as-is: the service abstains rather than the backend
492+ // refusing a question it cannot know is answerable.
493+ let scope = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
494+
495+ // Each create rides the thread's own row — it moves `updated_at` (the
496+ // list's sort key, so this is also the activity stamp) inside its own
497+ // transaction. That is what serializes a turn against `DELETE
498+ // /rag/threads/{id}`: the read above cannot, since reads do not conflict,
499+ // and a row written into the delete's window survived it as a turn under a
500+ // thread that is gone.
501+ let prompt =
502+ service::rag_message::append_user(&st.db, thread.get_id(), user.get_id(), content).await?;
503+ let answer =
504+ service::rag_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id())
505+ .await?;
506+
507+ let message_id = answer.get_id().key().to_string();
508+ // Never awaited inline: the retrieval-then-answer round trip can outlast
509+ // the request timeout that guards every handler, and the POST must return
510+ // now. The settings snapshot goes with it, so the whole turn is judged by
511+ // the policy that was live when it was accepted.
512+ // The prompt travels by id, not by write order: two POSTs on one thread
513+ // interleave across the two creates above, and picking "the newest user
514+ // row before this answer" out of the thread then answers the *other*
515+ // request's question twice.
516+ tokio::spawn(answer_turn(
517+ // The school and its database travel together — the same pair the
518+ // request was already resolved into, and one without the other is how
519+ // an answer lands in the wrong school.
520+ TenantExt {
521+ slug,
522+ db: st.db.clone(),
523+ modules: tenant.modules,
524+ },
525+ bridge,
526+ prompt.get_id().clone(),
527+ answer,
528+ *user.get_id(),
529+ user.get_role(),
530+ scope,
531+ settings.get_chatbot_history_turns().max(0) as usize,
532+ reply_cap,
533+ ));
534+
535+ Ok((
536+ StatusCode::ACCEPTED,
537+ Json(AcceptedResponse {
538+ message_id,
539+ status: RagMessageStatus::Pending.as_str().to_string(),
540+ }),
541+ )
542+ .into_response())
543+}
544+
545+/// The school's per-message character cap, never above the domain's hard
546+/// ceiling. Applied to what the user sends *and* to what the service answers —
547+/// the same knob the chatbot nest reads.
548+fn content_cap(settings: &Settings) -> usize {
549+ (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)
550+}
551+
552+/// Fetch one turn's answer and settle its row. Runs detached from the request.
553+///
554+/// Every path settles: a row left `pending` would show as a spinner forever.
555+#[allow(clippy::too_many_arguments)] // the whole turn, handed to the detached task as one
556+async fn answer_turn(
557+ tenant: TenantExt,
558+ bridge: AiBridge,
559+ prompt_id: RagMessageId,
560+ answer: RagMessage,
561+ asker: UserId,
562+ asker_role: Role,
563+ scope: Vec<RagScopePair>,
564+ history_turns: usize,
565+ reply_cap: usize,
566+) {
567+ let db = tenant.db.clone();
568+ let answer_id = answer.get_id().clone();
569+ let thread = answer.get_thread_id().clone();
570+ // This request's own question, read back by id — the text is already
571+ // stored, so carrying the id rather than the string keeps the prompt and
572+ // its answer paired however two POSTs on one thread interleave.
573+ let prompt = match service::rag_message::prompt_of(&db, &prompt_id).await {
574+ Ok(Some(prompt)) => prompt,
575+ Ok(None) => {
576+ // The prompt row is gone — only reachable if the thread was deleted
577+ // out from under this task. There is nothing to ask, so settle.
578+ tracing::warn!("rag answer {} has no prompt to send", answer_id.key());
579+ let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
580+ return;
581+ }
582+ Err(err) => {
583+ // Nothing to ask, and nothing will ask again: an unsettled row
584+ // would be a spinner until the staleness horizon. Settle it here.
585+ tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
586+ let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
587+ return;
588+ }
589+ };
590+ let fresh = [prompt.get_id().clone(), answer_id.clone()];
591+ let history = match history_for(&db, &thread, &fresh, history_turns).await {
592+ Ok(history) => history,
593+ Err(err) => {
594+ tracing::warn!("could not load rag history: {err}");
595+ let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
596+ return;
597+ }
598+ };
599+ let settled = match crate::ai::rag_chat::answer(
600+ &db,
601+ &bridge,
602+ &tenant.slug,
603+ &thread,
604+ &fresh,
605+ prompt.get_content().as_str().to_string(),
606+ &asker,
607+ asker_role,
608+ scope,
609+ history,
610+ )
611+ .await
612+ {
613+ Ok((text, reply)) => {
614+ // The service is a trust boundary: cap what it wrote before it
615+ // reaches a row (or a browser). Truncation over rejection — a
616+ // clipped answer still helps, a discarded one does not.
617+ let clipped: String = text.chars().take(reply_cap).collect();
618+ if clipped.chars().count() < text.chars().count() {
619+ tracing::warn!(
620+ "clipped an AI RAG reply to the school's {reply_cap}-character limit"
621+ );
622+ }
623+ match RagContent::try_new(&clipped) {
624+ Ok(content) => {
625+ service::rag_message::complete(&db, &answer_id, content, SqlJson(reply)).await
626+ }
627+ Err(err) => {
628+ // Nothing to show, and `RagContent` would refuse it anyway.
629+ // A blank bubble is indistinguishable from a bug, so it is
630+ // reported as one.
631+ tracing::error!("a clipped AI RAG reply was still not storable: {err}");
632+ service::rag_message::fail(&db, &answer_id, "bad_reply").await
633+ }
634+ }
635+ }
636+ Err(code) => {
637+ tracing::warn!("rag answer {} failed: {code}", answer_id.key());
638+ service::rag_message::fail(&db, &answer_id, &code).await
639+ }
640+ };
641+ match settled {
642+ Ok(_) => {}
643+ // The row was no longer `pending`: the boot sweep or a stale-timeout
644+ // already spoke for it, or the thread was deleted mid-flight. Benign —
645+ // the user is not waiting on this row any more.
646+ Err(AppError::NotFound) => {
647+ tracing::info!("rag answer {} was already settled", answer_id.key());
648+ }
649+ Err(err) => tracing::error!("could not settle rag answer {}: {err}", answer_id.key()),
650+ }
651+}
652+
653+/// The tail of the thread replayed to the service: oldest first, only settled
654+/// turns with text, and never the two rows this turn just wrote (the new
655+/// prompt rides in `message`, the answer does not exist yet).
656+async fn history_for(
657+ db: &Database,
658+ thread: &RagThreadId,
659+ fresh: &[RagMessageId; 2],
660+ turns: usize,
661+) -> Result<Vec<crate::ai::rag_chat::RagTurn>, AppError> {
662+ // The query counts only settled rows with text, so a run of failed answers
663+ // makes the window reach *further back* instead of shrinking it — that is
664+ // what "the last `chatbot_history_turns` settled turns" means. +2 so
665+ // dropping this turn's own two rows cannot shorten it either (only the
666+ // user one can match: the assistant row is still `pending`).
667+ let tail =
668+ service::rag_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?;
669+ let mut history: Vec<crate::ai::rag_chat::RagTurn> = tail
670+ .iter()
671+ .filter(|message| !fresh.contains(message.get_id()))
672+ .map(|message| crate::ai::rag_chat::RagTurn {
673+ role: match message.get_role() {
674+ RagMessageRole::User => ChatRole::User,
675+ RagMessageRole::Assistant => ChatRole::Assistant,
676+ },
677+ content: message.get_content().as_str().to_string(),
678+ })
679+ .collect();
680+ if history.len() > turns {
681+ history.drain(..history.len() - turns);
682+ }
683+ Ok(history)
684+}
685+
686+/// Poll one turn. The non-SSE fallback for `/stream`, reading the same row —
687+/// including the projection that presents a long-stale `pending` as `failed`,
688+/// so the two can never disagree about a turn's state.
689+#[utoipa::path(
690+ get,
691+ path = "/threads/{id}/messages/{mid}",
692+ tag = "rag",
693+ security(("session_cookie" = [])),
694+ params(
695+ ("id" = String, Path, description = "RagThread id"),
696+ ("mid" = String, Path, description = "Message id"),
697+ ),
698+ responses(
699+ (status = 200, description = "The turn, in whatever state it is", body = RagMessageResponse),
700+ (status = 401, description = "Not authenticated", body = ErrorResponse),
701+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
702+ ),
703+)]
704+async fn read_message(
705+ State(st): State<AppState>,
706+ CurrentUser(user): CurrentUser,
707+ Path((id, mid)): Path<(String, String)>,
708+) -> Result<Json<RagMessageResponse>, AppError> {
709+ let message = own_message(&id, &mid, user.get_id(), &st.db).await?;
710+ Ok(Json(RagMessageResponse::new(&message)))
711+}
712+
713+/// Read one turn only if the caller owns it *and* it belongs to the named
714+/// thread — a mismatched pair is a `404`, like a foreign one.
715+///
716+/// The thread is re-read rather than inferred from the message's `thread_id`,
717+/// so a turn whose thread was deleted reads as gone through these two routes
718+/// too — the same defence in depth [`super::chatbot`]'s twin carries.
719+async fn own_message(
720+ thread: &str,
721+ message: &str,
722+ user: &UserId,
723+ db: &Database,
724+) -> Result<RagMessage, AppError> {
725+ own_thread(thread, user, db).await?;
726+ service::rag_message::read_for(db, &RagMessageId::from_key(message), user)
727+ .await?
728+ .filter(|message| message.get_thread_id().key() == thread)
729+ .ok_or(AppError::NotFound)
730+}
731+
732+/// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a
733+/// single `done` carrying the finished message, or one `error`. The stream
734+/// closes after `done`/`error` — one stream per turn, not per thread.
735+///
736+/// Works whatever state the turn is in when the stream opens: an answer that
737+/// already landed replays as `delta`s and a `done` straight away, so a client
738+/// that reconnects late is never left hanging. Consume with `EventSource`
739+/// (cookies ride along on same-site / credentialed requests). The `done`
740+/// payload carries the whole settled turn — text, abstention, citations — so a
741+/// late reader gets the citations too, not only the deltas.
742+#[utoipa::path(
743+ get,
744+ path = "/threads/{id}/messages/{mid}/stream",
745+ tag = "rag",
746+ security(("session_cookie" = [])),
747+ params(
748+ ("id" = String, Path, description = "RagThread id"),
749+ ("mid" = String, Path, description = "Message id"),
750+ ),
751+ responses(
752+ (status = 200, description = "SSE: `delta` (`{text}`) chunks, then `done` (`{message}`) or `error` (`{code, message}`)", content_type = "text/event-stream"),
753+ (status = 401, description = "Not authenticated", body = ErrorResponse),
754+ (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
755+ ),
756+)]
757+async fn stream_message(
758+ State(st): State<AppState>,
759+ CurrentUser(user): CurrentUser,
760+ Path((id, mid)): Path<(String, String)>,
761+) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> {
762+ // Ownership is settled before the response becomes a stream — after this
763+ // point the only way to say "no" is an `error` event.
764+ own_message(&id, &mid, user.get_id(), &st.db).await?;
765+
766+ let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);
767+ let (message_id, user_id, db) = (
768+ RagMessageId::from_key(&mid),
769+ *user.get_id(),
770+ st.db.clone(),
771+ );
772+ tokio::spawn(async move {
773+ let mut ticker = tokio::time::interval(Duration::from_millis(CHAT_STREAM_POLL_MS));
774+ loop {
775+ // The first tick fires immediately: an already-finished turn is
776+ // delivered on connect rather than one poll interval later.
777+ //
778+ // The wait also watches the receiver, because a `pending` turn
779+ // sends nothing and would otherwise never learn that the client
780+ // hung up: axum drops the response body — and with it this
781+ // channel's receiver — the moment the connection dies, so this is
782+ // where an abandoned stream stops polling the database.
783+ tokio::select! {
784+ _ = ticker.tick() => {}
785+ _ = tx.closed() => return,
786+ }
787+ let message = match service::rag_message::read_for(&db, &message_id, &user_id).await {
788+ Ok(Some(message)) => message,
789+ // Deleted mid-stream (the thread went away) — say so and stop.
790+ Ok(None) => {
791+ sse_error(&tx, "not_found", "this message no longer exists").await;
792+ return;
793+ }
794+ Err(err) => {
795+ tracing::warn!("rag stream read failed: {err}");
796+ sse_error(&tx, "internal", "could not read the message").await;
797+ return;
798+ }
799+ };
800+
801+ match message.get_status() {
802+ // Includes the read-time projection: a `pending` row past its
803+ // staleness window arrives here as `failed`, so this loop
804+ // always terminates.
805+ RagMessageStatus::Pending => continue,
806+ RagMessageStatus::Complete => {
807+ for chunk in slice_reply(message.get_content().as_str()) {
808+ if sse_send(&tx, "delta", json!({ "text": chunk }))
809+ .await
810+ .is_err()
811+ {
812+ return;
813+ }
814+ }
815+ let done = json!({ "message": RagMessageResponse::new(&message) });
816+ let _ = sse_send(&tx, "done", done).await;
817+ return;
818+ }
819+ RagMessageStatus::Failed => {
820+ let code = message.get_error_code().unwrap_or("failed");
821+ sse_error(&tx, code, "the assistant could not answer this message").await;
822+ return;
823+ }
824+ }
825+ }
826+ });
827+
828+ Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default()))
829+}
830+
831+#[cfg(test)]
832+mod tests {
833+ use super::*;
834+
835+ #[test]
836+ fn a_citation_reply_maps_every_field_into_the_wire_shape() {
837+ let stored = RagCitedFile {
838+ n: 2,
839+ file: Some("0197-file".into()),
840+ pages: vec![3, 4],
841+ span_ids: vec!["s-1".into()],
842+ ders: Some("Fizik".into()),
843+ };
844+ let wire = RagCitationResponse::from(&stored);
845+ assert_eq!(wire.n, 2);
846+ assert_eq!(wire.file.as_deref(), Some("0197-file"));
847+ assert_eq!(wire.pages, vec![3, 4]);
848+ assert_eq!(wire.span_ids, vec!["s-1"]);
849+ assert_eq!(wire.ders.as_deref(), Some("Fizik"));
850+
851+ // An unresolved citation keeps every other field — the passage is
852+ // still citable, only not openable.
853+ let unresolved = RagCitationResponse::from(&RagCitedFile {
854+ file: None,
855+ ..stored
856+ });
857+ assert_eq!(unresolved.file, None);
858+ assert_eq!(unresolved.pages, vec![3, 4]);
859+ }
860+}
src/web/sessions.rsmodified+2 -1
@@ -20,9 +20,10 @@ use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::{User, UserId};20 use crate::domain::user::{User, UserId};
21 use crate::error::{AppError, ErrorResponse};21 use crate::error::{AppError, ErrorResponse};
22 use crate::service;22 use crate::service;
23+use crate::service::instance::can_manage_instance;
23 use crate::state::AppState;24 use crate::state::AppState;
24 25
25-use super::instances::{can_manage_instance, can_view_instance};26+use super::instances::can_view_instance;
26 use super::{27 use super::{
27 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,28 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,
28 check_time_range, person_map, set_or_clear,29 check_time_range, person_map, set_or_clear,
src/web/subjects.rsmodified+1 -1
@@ -11,10 +11,10 @@ use crate::database::Database;
11 use crate::domain::course::Course;11 use crate::domain::course::Course;
12 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};12 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
13 use crate::error::{AppError, ErrorResponse};13 use crate::error::{AppError, ErrorResponse};
14+use crate::service::course::{can_manage_course, can_view_course};
14 use crate::service::subject;15 use crate::service::subject;
15 use crate::state::AppState;16 use crate::state::AppState;
16 17
17-use super::courses::{can_manage_course, can_view_course};
18 use super::{CurrentUser, RequireTeacher, SubjectResponse};18 use super::{CurrentUser, RequireTeacher, SubjectResponse};
19 19
20 pub fn routes() -> OpenApiRouter<AppState> {20 pub fn routes() -> OpenApiRouter<AppState> {
src/web/tenant_state.rsmodified+2 -0
@@ -221,6 +221,7 @@ mod tests {
221 cookie_secure: false,221 cookie_secure: false,
222 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),222 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
223 chatbot_limit: Default::default(),223 chatbot_limit: Default::default(),
224+ rag_limit: Default::default(),
224 exam_presence: Default::default(),225 exam_presence: Default::default(),
225 board_hub: Default::default(),226 board_hub: Default::default(),
226 ai: None,227 ai: None,
@@ -332,6 +333,7 @@ mod tests {
332 cookie_secure: false,333 cookie_secure: false,
333 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),334 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
334 chatbot_limit: Default::default(),335 chatbot_limit: Default::default(),
336+ rag_limit: Default::default(),
335 exam_presence: Default::default(),337 exam_presence: Default::default(),
336 board_hub: Default::default(),338 board_hub: Default::default(),
337 ai: None,339 ai: None,
tests/ai_bridge.rsmodified+317 -1
@@ -863,6 +863,7 @@ async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Val
863 cookie_secure: false,863 cookie_secure: false,
864 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),864 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
865 chatbot_limit: Default::default(),865 chatbot_limit: Default::default(),
866+ rag_limit: Default::default(),
866 exam_presence: Default::default(),867 exam_presence: Default::default(),
867 board_hub: Default::default(),868 board_hub: Default::default(),
868 ai,869 ai,
@@ -982,7 +983,7 @@ fn payloads_are_opaque(v: Value) -> Value {
982 983
983 use axum::Router;984 use axum::Router;
984 use axum::http::StatusCode;985 use axum::http::StatusCode;
985-use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN};986+use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN};
986 use hezarfen_backend::database::Database;987 use hezarfen_backend::database::Database;
987 use uuid::Uuid;988 use uuid::Uuid;
988 989
@@ -996,6 +997,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) {
996 cookie_secure: false,997 cookie_secure: false,
997 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),998 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
998 chatbot_limit: Default::default(),999 chatbot_limit: Default::default(),
1000+ rag_limit: Default::default(),
999 exam_presence: Default::default(),1001 exam_presence: Default::default(),
1000 board_hub: Default::default(),1002 board_hub: Default::default(),
1001 ai: Some(bridge.clone()),1003 ai: Some(bridge.clone()),
@@ -2743,3 +2745,317 @@ async fn a_dispatch_is_traced_by_capability_and_a_refused_handshake_is_counted()
2743 "the refused handshake must be counted under reason=bad_token"2745 "the refused handshake must be counted under reason=bad_token"
2744 );2746 );
2745 }2747 }
2748+
2749+
2750+// ---------------------------------------------------------------- rag -----
2751+
2752+/// Open a RAG thread for a fresh user. Returns (session cookie, thread id).
2753+async fn rag_user(app: &Router, name: &str) -> (String, String) {
2754+ let cookie = common::login(app, name).await;
2755+ let res = common::send(app, "POST", "/rag/threads", Some(&cookie), Some(json!({}))).await;
2756+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
2757+ (cookie, common::id_of(&res.body))
2758+}
2759+
2760+/// Ask the corpus one question (asserts `202`) and return the reserved
2761+/// assistant row's id.
2762+async fn rag_ask(app: &Router, cookie: &str, thread: &str, text: &str) -> String {
2763+ let res = common::send(
2764+ app,
2765+ "POST",
2766+ &format!("/rag/threads/{thread}/messages"),
2767+ Some(cookie),
2768+ Some(json!({ "content": text })),
2769+ )
2770+ .await;
2771+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
2772+ res.body["message_id"]
2773+ .as_str()
2774+ .expect("message_id")
2775+ .to_string()
2776+}
2777+
2778+/// Poll a RAG turn until it leaves `pending`.
2779+async fn rag_settled(app: &Router, cookie: &str, thread: &str, mid: &str) -> Value {
2780+ for _ in 0..500 {
2781+ let res = common::send(
2782+ app,
2783+ "GET",
2784+ &format!("/rag/threads/{thread}/messages/{mid}"),
2785+ Some(cookie),
2786+ None,
2787+ )
2788+ .await;
2789+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
2790+ if res.body["status"] != "pending" {
2791+ return res.body;
2792+ }
2793+ tokio::time::sleep(Duration::from_millis(10)).await;
2794+ }
2795+ panic!("the RAG turn never settled");
2796+}
2797+
2798+/// The RAG wire contract: the scope is derived server-side from the asker's
2799+/// live memberships — a club/etüt membership is the `sinif: null` pair, since
2800+/// such a corpus is school-wide — and the asker's role rides the request,
2801+/// read from the session, never from the body.
2802+#[tokio::test]
2803+async fn the_rag_request_carries_the_askers_scope_and_role() {
2804+ let bridge = bridge().await;
2805+ let service = connect_service(
2806+ &bridge,
2807+ hello("rag", &[AI_RAG_CHAT_CAPABILITY]),
2808+ Behaviour::Answer(json!({ "text": "cevap", "abstained": false, "reason": "", "citations": [] })),
2809+ )
2810+ .await;
2811+ await_workers(&bridge, 1).await;
2812+ let (app, db) = chat_app(&bridge).await;
2813+
2814+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
2815+ let res = common::send(
2816+ &app,
2817+ "POST",
2818+ "/courses",
2819+ Some(&staff),
2820+ Some(json!({ "title": "Satranç Kulübü", "kind": "club" })),
2821+ )
2822+ .await;
2823+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
2824+ let club = common::id_of(&res.body);
2825+
2826+ let (cookie, thread) = rag_user(&app, "ali").await;
2827+ let ali = common::me_id(&app, &cookie).await;
2828+ let res = common::send(
2829+ &app,
2830+ "POST",
2831+ &format!("/courses/{club}/members"),
2832+ Some(&staff),
2833+ Some(json!({ "user_id": ali })),
2834+ )
2835+ .await;
2836+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
2837+
2838+ let mid = rag_ask(&app, &cookie, &thread, "ikinci yasa nedir?").await;
2839+ assert_eq!(
2840+ rag_settled(&app, &cookie, &thread, &mid).await["status"],
2841+ "complete"
2842+ );
2843+
2844+ let seen = service.seen();
2845+ assert_eq!(seen.len(), 1, "one dispatch per turn, never a re-send");
2846+ assert_eq!(seen[0].capability, AI_RAG_CHAT_CAPABILITY);
2847+ let payload = &seen[0].payload;
2848+ assert_eq!(payload["message"], "ikinci yasa nedir?");
2849+ assert_eq!(payload["asker"], ali);
2850+ assert_eq!(payload["asker_role"], "student");
2851+ assert_eq!(
2852+ payload["scope"],
2853+ json!([{ "sinif": null, "ders": "Satranç Kulübü" }]),
2854+ "a club is school-wide, so its pair names no grade"
2855+ );
2856+ assert_eq!(payload["history"], json!([]));
2857+}
2858+
2859+/// An abstention is a complete turn, not an error: the service's `reason` and
2860+/// `citations` land on the row (and therefore in both the polling read and the
2861+/// SSE `done` payload, which are built from the same row).
2862+#[tokio::test]
2863+async fn an_abstained_rag_answer_keeps_its_reason_and_citations() {
2864+ let bridge = bridge().await;
2865+ let _service = connect_service(
2866+ &bridge,
2867+ hello("rag", &[AI_RAG_CHAT_CAPABILITY]),
2868+ Behaviour::Answer(json!({
2869+ "text": "Bu soruyu yanıtlayamam.",
2870+ "abstained": true,
2871+ "reason": "insufficient_data",
2872+ "citations": [{
2873+ "n": 1,
2874+ "doc_id": "01DOC",
2875+ "pages": [3, 4],
2876+ "span_ids": ["s-7"],
2877+ "ders": "Fizik",
2878+ }],
2879+ })),
2880+ )
2881+ .await;
2882+ await_workers(&bridge, 1).await;
2883+ let (app, _db) = chat_app(&bridge).await;
2884+ let (cookie, thread) = rag_user(&app, "ali").await;
2885+
2886+ let mid = rag_ask(&app, &cookie, &thread, "optik nedir?").await;
2887+ let turn = rag_settled(&app, &cookie, &thread, &mid).await;
2888+ assert_eq!(turn["status"], "complete", "{turn}");
2889+ assert_eq!(turn["content"], "Bu soruyu yanıtlayamam.");
2890+ assert_eq!(turn["abstained"], true);
2891+ assert_eq!(turn["reason"], "insufficient_data");
2892+ assert!(turn["error_code"].is_null(), "{turn}");
2893+ let citation = &turn["citations"][0];
2894+ assert_eq!(citation["n"], 1);
2895+ assert_eq!(citation["pages"], json!([3, 4]));
2896+ assert_eq!(citation["span_ids"], json!(["s-7"]));
2897+ assert_eq!(citation["ders"], "Fizik");
2898+ assert!(
2899+ citation["file"].is_null(),
2900+ "no course-note file claims the document yet: {turn}"
2901+ );
2902+}
2903+
2904+/// A citation's corpus `doc_id` resolves to a course-note file only when the
2905+/// **asker** may view that file's course: identical PDF bytes make one document
2906+/// claimable from several courses, so the per-candidate visibility check is the
2907+/// whole point. A passage whose file the asker cannot open stays citable, with
2908+/// `file: null`.
2909+#[tokio::test]
2910+async fn a_citation_resolves_only_to_a_file_the_asker_may_view() {
2911+ let bridge = bridge().await;
2912+ let _service = connect_service(
2913+ &bridge,
2914+ hello("rag", &[AI_RAG_CHAT_CAPABILITY]),
2915+ Behaviour::Answer(json!({
2916+ "text": "F = m·a [1]",
2917+ "abstained": false,
2918+ "reason": "",
2919+ "citations": [{ "n": 1, "doc_id": "01DOC", "pages": [7], "span_ids": [], "ders": "Fizik" }],
2920+ })),
2921+ )
2922+ .await;
2923+ await_workers(&bridge, 1).await;
2924+ let (app, db) = chat_app(&bridge).await;
2925+
2926+ let staff = common::login_as(&app, &db, "mudur", "manager").await;
2927+ let course = common::create_course(&app, &staff, "Fizik").await;
2928+ let author = common::me_id(&app, &staff).await;
2929+ let note = Uuid::now_v7();
2930+ let file = Uuid::now_v7();
2931+ sqlx::query(
2932+ "INSERT INTO course_note (id, course, author, title, content, file_count) \
2933+ VALUES ($1, $2, $3, 'Notlar', 'Newton', 1)",
2934+ )
2935+ .bind(note)
2936+ .bind(Uuid::parse_str(&course).expect("course id"))
2937+ .bind(Uuid::parse_str(&author).expect("author id"))
2938+ .execute(&db)
2939+ .await
2940+ .expect("seed course note");
2941+ sqlx::query(
2942+ "INSERT INTO course_note_file (id, course_note, name, content_type, size, rag_doc_id) \
2943+ VALUES ($1, $2, 'recap.pdf', 'application/pdf', 12, '01DOC')",
2944+ )
2945+ .bind(file)
2946+ .bind(note)
2947+ .execute(&db)
2948+ .await
2949+ .expect("seed course note file");
2950+
2951+ // The manager sees the course, so the citation opens the file.
2952+ let res = common::send(&app, "POST", "/rag/threads", Some(&staff), Some(json!({}))).await;
2953+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
2954+ let staff_thread = common::id_of(&res.body);
2955+ let mid = rag_ask(&app, &staff, &staff_thread, "kütle nedir?").await;
2956+ let turn = rag_settled(&app, &staff, &staff_thread, &mid).await;
2957+ assert_eq!(
2958+ turn["citations"][0]["file"],
2959+ file.to_string(),
2960+ "the viewer's citation must open the file: {turn}"
2961+ );
2962+
2963+ // A student with no tie to the course gets the same citation unresolved.
2964+ let (cookie, thread) = rag_user(&app, "ali").await;
2965+ let mid = rag_ask(&app, &cookie, &thread, "kütle nedir?").await;
2966+ let turn = rag_settled(&app, &cookie, &thread, &mid).await;
2967+ assert!(
2968+ turn["citations"][0]["file"].is_null(),
2969+ "a citation a student cannot open stays unresolved: {turn}"
2970+ );
2971+ assert_eq!(turn["citations"][0]["n"], 1, "nothing else is dropped");
2972+}
2973+
2974+/// No service offering `rag.chat`: a `503`, and nothing is written — no
2975+/// half-thread to poll forever.
2976+#[tokio::test]
2977+async fn no_rag_worker_means_503_and_no_rows() {
2978+ let bridge = bridge().await;
2979+ let (app, db) = chat_app(&bridge).await;
2980+ let (cookie, thread) = rag_user(&app, "ali").await;
2981+
2982+ let res = common::send(
2983+ &app,
2984+ "POST",
2985+ &format!("/rag/threads/{thread}/messages"),
2986+ Some(&cookie),
2987+ Some(json!({ "content": "soru" })),
2988+ )
2989+ .await;
2990+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
2991+
2992+ let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM rag_message")
2993+ .fetch_one(&db)
2994+ .await
2995+ .expect("count rag messages");
2996+ assert_eq!(rows, 0, "a refused turn leaves no trace");
2997+}
2998+
2999+/// The nest is gated by the school's `chatbot` module, exactly like
3000+/// `/chatbot`: with the module off the whole URL space answers the disabled
3001+/// refusal (the codebase's contract for a gated nest — see integration's
3002+/// meals test), never a handler.
3003+#[tokio::test]
3004+async fn a_school_without_the_chatbot_module_has_no_rag_nest() {
3005+ let (app, db, tenants) = common::app_and_tenants().await;
3006+ let slug = Slug::try_new(DEMO_SLUG).unwrap();
3007+ let cookie = common::login_as(&app, &db, "ada", "admin").await;
3008+
3009+ let res = common::send(&app, "GET", "/rag/threads", Some(&cookie), None).await;
3010+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3011+
3012+ let mut without_chatbot = ModuleSet::all();
3013+ without_chatbot.remove(Module::Chatbot);
3014+ tenants
3015+ .set_modules(&slug, &without_chatbot)
3016+ .await
3017+ .expect("take the chatbot module back");
3018+
3019+ for route in ["/rag/threads", "/chatbot/threads"] {
3020+ let res = common::send(&app, "GET", route, Some(&cookie), None).await;
3021+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{route}: {}", res.body);
3022+ assert_eq!(
3023+ res.body,
3024+ json!({ "error": "module disabled", "module": "chatbot" }),
3025+ "one gate governs both nests"
3026+ );
3027+ }
3028+ let res = common::send(&app, "POST", "/rag/threads", Some(&cookie), Some(json!({}))).await;
3029+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
3030+}
3031+
3032+/// The service is a trust boundary: a reply carrying more citations (or more
3033+/// pages per citation) than a row may hold is refused whole — the turn fails
3034+/// rather than storing a clipped answer that reads as a complete one.
3035+#[tokio::test]
3036+async fn a_rag_reply_past_the_citation_caps_fails_the_turn() {
3037+ let bridge = bridge().await;
3038+ let citations: Vec<Value> = (0..51)
3039+ .map(|n| json!({ "n": n, "doc_id": "d", "pages": [], "span_ids": [], "ders": null }))
3040+ .collect();
3041+ let _service = connect_service(
3042+ &bridge,
3043+ hello("rag", &[AI_RAG_CHAT_CAPABILITY]),
3044+ Behaviour::Answer(json!({
3045+ "text": "cevap",
3046+ "abstained": false,
3047+ "reason": "",
3048+ "citations": citations,
3049+ })),
3050+ )
3051+ .await;
3052+ await_workers(&bridge, 1).await;
3053+ let (app, _db) = chat_app(&bridge).await;
3054+ let (cookie, thread) = rag_user(&app, "ali").await;
3055+
3056+ let mid = rag_ask(&app, &cookie, &thread, "soru").await;
3057+ let turn = rag_settled(&app, &cookie, &thread, &mid).await;
3058+ assert_eq!(turn["status"], "failed", "{turn}");
3059+ assert_eq!(turn["error_code"], "bad_reply", "{turn}");
3060+ assert_eq!(turn["content"], "", "nothing of the over-cap answer is stored");
3061+}
tests/ai_protocol.rsmodified+1 -0
@@ -966,6 +966,7 @@ async fn a_chat_request_names_the_askers_school_role() {
966 cookie_secure: false,966 cookie_secure: false,
967 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),967 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
968 chatbot_limit: Default::default(),968 chatbot_limit: Default::default(),
969+ rag_limit: Default::default(),
969 exam_presence: Default::default(),970 exam_presence: Default::default(),
970 board_hub: Default::default(),971 board_hub: Default::default(),
971 ai: Some(bridge.clone()),972 ai: Some(bridge.clone()),
tests/common/mod.rsmodified+2 -0
@@ -131,6 +131,7 @@ async fn app_parts(ai: Option<AiBridge>, metrics: Metrics) -> (Router, Database,
131 // `rate_limit` test binary opts into tight configs on purpose.131 // `rate_limit` test binary opts into tight configs on purpose.
132 rate_limit: RateLimitConfig::unlimited(),132 rate_limit: RateLimitConfig::unlimited(),
133 chatbot_limit: Default::default(),133 chatbot_limit: Default::default(),
134+ rag_limit: Default::default(),
134 exam_presence: Default::default(),135 exam_presence: Default::default(),
135 board_hub: Default::default(),136 board_hub: Default::default(),
136 ai,137 ai,
@@ -872,6 +873,7 @@ pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment {
872 cookie_secure: false,873 cookie_secure: false,
873 rate_limit: RateLimitConfig::unlimited(),874 rate_limit: RateLimitConfig::unlimited(),
874 chatbot_limit: Default::default(),875 chatbot_limit: Default::default(),
876+ rag_limit: Default::default(),
875 exam_presence: Default::default(),877 exam_presence: Default::default(),
876 board_hub: Default::default(),878 board_hub: Default::default(),
877 ai: None,879 ai: None,
tests/e2e.rsmodified+1 -0
@@ -47,6 +47,7 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St
47 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.47 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
48 rate_limit: RateLimitConfig::unlimited(),48 rate_limit: RateLimitConfig::unlimited(),
49 chatbot_limit: Default::default(),49 chatbot_limit: Default::default(),
50+ rag_limit: Default::default(),
50 exam_presence: Default::default(),51 exam_presence: Default::default(),
51 board_hub: Default::default(),52 board_hub: Default::default(),
52 ai,53 ai,
tests/integration.rsmodified+5 -1
@@ -199,6 +199,7 @@ async fn limits_still_answers_while_the_database_is_down() {
199 cookie_secure: false,199 cookie_secure: false,
200 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),200 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
201 chatbot_limit: Default::default(),201 chatbot_limit: Default::default(),
202+ rag_limit: Default::default(),
202 exam_presence: Default::default(),203 exam_presence: Default::default(),
203 board_hub: Default::default(),204 board_hub: Default::default(),
204 ai: None,205 ai: None,
@@ -433,7 +434,7 @@ async fn protected_routes_require_session() {
433 /// Floor on the number of protected operations swept. It only ever goes434 /// Floor on the number of protected operations swept. It only ever goes
434 /// up: raise it when routes are added. Without it, deleting a route family435 /// up: raise it when routes are added. Without it, deleting a route family
435 /// would delete its own coverage and still pass.436 /// would delete its own coverage and still pass.
436- const MIN_PROTECTED: usize = 269;437+ const MIN_PROTECTED: usize = 318;
437 438
438 let app = mem_app().await;439 let app = mem_app().await;
439 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
@@ -6541,6 +6542,7 @@ async fn session_cookie_secure_attribute_follows_config() {
6541 cookie_secure: true,6542 cookie_secure: true,
6542 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),6543 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
6543 chatbot_limit: Default::default(),6544 chatbot_limit: Default::default(),
6545+ rag_limit: Default::default(),
6544 exam_presence: Default::default(),6546 exam_presence: Default::default(),
6545 board_hub: Default::default(),6547 board_hub: Default::default(),
6546 ai: None,6548 ai: None,
@@ -6581,6 +6583,7 @@ async fn db_down_refuses_before_touching_the_database() {
6581 cookie_secure: false,6583 cookie_secure: false,
6582 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),6584 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
6583 chatbot_limit: Default::default(),6585 chatbot_limit: Default::default(),
6586+ rag_limit: Default::default(),
6584 exam_presence: Default::default(),6587 exam_presence: Default::default(),
6585 board_hub: Default::default(),6588 board_hub: Default::default(),
6586 ai: None,6589 ai: None,
@@ -16924,6 +16927,7 @@ async fn chat_app_limited(
16924 cookie_secure: false,16927 cookie_secure: false,
16925 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),16928 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
16926 chatbot_limit,16929 chatbot_limit,
16930+ rag_limit: Default::default(),
16927 exam_presence: Default::default(),16931 exam_presence: Default::default(),
16928 board_hub: Default::default(),16932 board_hub: Default::default(),
16929 ai,16933 ai,
tests/limits_completeness.rsmodified+17 -0
@@ -113,6 +113,15 @@ const EXCLUDED: &[(&str, &str)] = &[
113 "deadline on a background course-note indexing round trip; no client \113 "deadline on a background course-note indexing round trip; no client \
114 waits on it",114 waits on it",
115 ),115 ),
116+ (
117+ "AI_RAG_CHAT_CAPABILITY",
118+ "capability string an AI service declares",
119+ ),
120+ (
121+ "AI_RAG_CHAT_TIMEOUT_SECS",
122+ "deadline on one RAG ask round trip; the browser waits on its message \
123+ stream, never on this number",
124+ ),
116 (125 (
117 "CHAT_STREAM_POLL_MS",126 "CHAT_STREAM_POLL_MS",
118 "server-side poll cadence behind the SSE stream",127 "server-side poll cadence behind the SSE stream",
@@ -121,6 +130,10 @@ const EXCLUDED: &[(&str, &str)] = &[
121 "CHATBOT_PENDING_STALE_SECS",130 "CHATBOT_PENDING_STALE_SECS",
122 "when a stuck answer is declared failed",131 "when a stuck answer is declared failed",
123 ),132 ),
133+ (
134+ "RAG_PENDING_STALE_SECS",
135+ "when a stuck answer is declared failed",
136+ ),
124 // Seed data for the settings singleton, not a bound. The live list is on137 // Seed data for the settings singleton, not a bound. The live list is on
125 // `GET /settings`, which is where a client must read it — publishing the138 // `GET /settings`, which is where a client must read it — publishing the
126 // default too would invite rendering it instead of the school's actual one.139 // default too would invite rendering it instead of the school's actual one.
@@ -204,6 +217,10 @@ const EXCLUDED: &[(&str, &str)] = &[
204 "DEFAULT_CHATBOT_RATE_LIMIT",217 "DEFAULT_CHATBOT_RATE_LIMIT",
205 "env-tunable; live value served in /limits `rate`",218 "env-tunable; live value served in /limits `rate`",
206 ),219 ),
220+ (
221+ "DEFAULT_RAG_RATE_LIMIT",
222+ "env-tunable; live value served in /limits `rate`",
223+ ),
207 ("MILLIS_PER_DAY", "unit conversion, not a limit"),224 ("MILLIS_PER_DAY", "unit conversion, not a limit"),
208 ("MILLIS_PER_WEEK", "unit conversion, not a limit"),225 ("MILLIS_PER_WEEK", "unit conversion, not a limit"),
209 (226 (
tests/persistence.rsmodified+1 -0
@@ -30,6 +30,7 @@ async fn reboot(db: &Database, tenants: &Tenants) -> Router {
30 cookie_secure: false,30 cookie_secure: false,
31 rate_limit: RateLimitConfig::unlimited(),31 rate_limit: RateLimitConfig::unlimited(),
32 chatbot_limit: Default::default(),32 chatbot_limit: Default::default(),
33+ rag_limit: Default::default(),
33 exam_presence: Default::default(),34 exam_presence: Default::default(),
34 board_hub: Default::default(),35 board_hub: Default::default(),
35 ai: None,36 ai: None,
tests/rate_limit.rsmodified+2 -0
@@ -26,6 +26,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
26 cookie_secure: false,26 cookie_secure: false,
27 rate_limit,27 rate_limit,
28 chatbot_limit: Default::default(),28 chatbot_limit: Default::default(),
29+ rag_limit: Default::default(),
29 exam_presence: Default::default(),30 exam_presence: Default::default(),
30 board_hub: Default::default(),31 board_hub: Default::default(),
31 ai: None,32 ai: None,
@@ -584,6 +585,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
584 cookie_secure: false,585 cookie_secure: false,
585 rate_limit,586 rate_limit,
586 chatbot_limit: Default::default(),587 chatbot_limit: Default::default(),
588+ rag_limit: Default::default(),
587 exam_presence: Default::default(),589 exam_presence: Default::default(),
588 board_hub: Default::default(),590 board_hub: Default::default(),
589 ai: None,591 ai: None,
tests/regress_bank_images.rsmodified+1 -0
@@ -53,6 +53,7 @@ async fn mem_app() -> (Router, Database, TempDir) {
53 cookie_secure: false,53 cookie_secure: false,
54 rate_limit: RateLimitConfig::unlimited(),54 rate_limit: RateLimitConfig::unlimited(),
55 chatbot_limit: Default::default(),55 chatbot_limit: Default::default(),
56+ rag_limit: Default::default(),
56 exam_presence: Default::default(),57 exam_presence: Default::default(),
57 board_hub: Default::default(),58 board_hub: Default::default(),
58 ai: None,59 ai: None,
tests/spec_bounds.rsmodified+21 -0
@@ -32,6 +32,7 @@ async fn spec() -> Value {
32 cookie_secure: false,32 cookie_secure: false,
33 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),33 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
34 chatbot_limit: Default::default(),34 chatbot_limit: Default::default(),
35+ rag_limit: Default::default(),
35 exam_presence: Default::default(),36 exam_presence: Default::default(),
36 board_hub: Default::default(),37 board_hub: Default::default(),
37 ai: None,38 ai: None,
@@ -1068,6 +1069,26 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
1068 "maxLength",1069 "maxLength",
1069 MAX_CHATBOT_THREAD_TITLE_LEN as i64,1070 MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1070 ),1071 ),
1072+ // --- the RAG nest reuses the chatbot's shapes and its school knobs:
1073+ // the same title cap and the same per-message character cap ---
1074+ (
1075+ "CreateRagThread",
1076+ "title",
1077+ "maxLength",
1078+ MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1079+ ),
1080+ (
1081+ "RenameRagThread",
1082+ "title",
1083+ "maxLength",
1084+ MAX_CHATBOT_THREAD_TITLE_LEN as i64,
1085+ ),
1086+ (
1087+ "SendRagMessage",
1088+ "content",
1089+ "maxLength",
1090+ MAX_CHATBOT_MESSAGE_LEN as i64,
1091+ ),
1071 // --- whiteboards ---1092 // --- whiteboards ---
1072 (1093 (
1073 "CreateBoard",1094 "CreateBoard",