DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(api): add question-bank listing filters and an entries probe
Bingxi Zhao (Frank)83b5db6cbbdb
diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.pyindex 4190b3cd2..ac045a0cd 100644--- a/deeptutor/api/routers/question_notebook.py+++ b/deeptutor/api/routers/question_notebook.py@@ -35,6 +35,13 @@ class AnswerImageItem(BaseModel):mime_type: str = ""+class CategoryItem(BaseModel):+ id: int+ name: str+ created_at: float = 0+ entry_count: int = 0++class NotebookEntryItem(BaseModel):id: intsession_id: str@@ -69,13 +76,6 @@ class EntryUpdateRequest(BaseModel):ai_judgment: str | None = None-class CategoryItem(BaseModel):- id: int- name: str- created_at: float = 0- entry_count: int = 0--class CategoryCreateRequest(BaseModel):name: str = Field(..., min_length=1, max_length=100)@@ -88,6 +88,25 @@ class CategoryAddRequest(BaseModel):category_id: int+class BulkCategoryRequest(BaseModel):+ """File (or unfile) many entries at once.++ One round-trip per bulk action keeps the list view consistent: the+ client re-reads once instead of racing N per-entry writes.+ """++ entry_ids: list[int] = Field(..., min_length=1, max_length=500)+ category_id: int+ link: bool = True+++class QuestionBankStats(BaseModel):+ total: int = 0+ wrong: int = 0+ bookmarked: int = 0+ uncategorized: int = 0++class AnswerImageUpload(BaseModel):"""One image attached to the learner's answer.@@ -205,16 +224,26 @@ async def upsert_single_entry(payload: UpsertEntryRequest):@router.get("/entries", response_model=NotebookEntryListResponse)async def list_entries(category_id: int | None = Query(default=None),+ uncategorized: bool = Query(+ default=False,+ description="Only entries filed under no category — the triage inbox. "+ "Ignored when category_id is set.",+ ),bookmarked: bool | None = Query(default=None),is_correct: bool | None = Query(default=None),+ search: str = Query(default="", max_length=200),+ sort: str = Query(default="recent", pattern="^(recent|oldest)$"),limit: int = Query(default=50, ge=1, le=200),offset: int = Query(default=0, ge=0),) -> NotebookEntryListResponse:store = get_sqlite_session_store()result = await store.list_notebook_entries(category_id=category_id,+ uncategorized=uncategorized,bookmarked=bookmarked,is_correct=is_correct,+ search=search,+ sort=sort,limit=limit,offset=offset,)@@ -278,6 +307,20 @@ async def delete_entry(entry_id: int):# ── Entry ↔ Category linking ────────────────────────────────────[email protected]("/entries/categories/bulk")+async def bulk_link_entries(payload: BulkCategoryRequest):+ store = get_sqlite_session_store()+ changed = await store.link_entries_to_category(+ payload.entry_ids, payload.category_id, link=payload.link+ )+ return {+ "changed": changed,+ "requested": len(payload.entry_ids),+ "category_id": payload.category_id,+ "link": payload.link,+ }++@router.post("/entries/{entry_id}/categories")async def add_entry_to_category(entry_id: int, payload: CategoryAddRequest):store = get_sqlite_session_store()@@ -299,6 +342,16 @@ async def remove_entry_from_category(entry_id: int, category_id: int):return {"removed": True, "entry_id": entry_id, "category_id": category_id}+# ── Overview ─────────────────────────────────────────────────────++[email protected]("/stats", response_model=QuestionBankStats)+async def question_bank_stats() -> QuestionBankStats:+ """Counts behind the filter chips; also the agent's one-call overview."""+ store = get_sqlite_session_store()+ return QuestionBankStats(**await store.question_bank_stats())++# ── Category CRUD ────────────────────────────────────────────────@@ -313,14 +366,17 @@ async def create_category(payload: CategoryCreateRequest):store = get_sqlite_session_store()try:return await store.create_category(payload.name)- except Exception:- raise HTTPException(status_code=409, detail="Category name already exists")+ except ValueError as exc:+ raise HTTPException(status_code=409, detail=str(exc))@router.patch("/categories/{category_id}")async def rename_category(category_id: int, payload: CategoryRenameRequest):store = get_sqlite_session_store()- updated = await store.rename_category(category_id, payload.name)+ try:+ updated = await store.rename_category(category_id, payload.name)+ except ValueError as exc:+ raise HTTPException(status_code=409, detail=str(exc))if not updated:raise HTTPException(status_code=404, detail="Category not found")return {"updated": True, "id": category_id, "name": payload.name}diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex daf8e30c4..555147d91 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -27,6 +27,11 @@ def _json_dumps(value: Any) -> str:return json.dumps(value, ensure_ascii=False, default=str)+def _escape_like(value: str) -> str:+ """Escape LIKE wildcards so a search term matches itself literally."""+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")++# Sentinel so ``add_message`` can distinguish "caller wants the legacy# auto-pick-latest-message default" from "caller explicitly wants the# message attached at the session root (parent = NULL)". Both surface as@@ -93,6 +98,45 @@ class TurnRecord:}+@dataclass(frozen=True)+class QuestionBankQuery:+ """One question-bank listing request.++ A value object instead of a widening positional signature: the store's+ ``_run`` helper only forwards positional args, so every new filter used+ to mean another parameter threaded through three layers. Callers build+ a query, the store reads it — adding a filter never changes an arity.++ ``category_id`` and ``uncategorized`` are mutually exclusive views of the+ same axis; when both are supplied the explicit category wins, because a+ caller asking for one category always means "show me that category".+ """++ category_id: int | None = None+ uncategorized: bool = False+ bookmarked: bool | None = None+ is_correct: bool | None = None+ search: str = ""+ session_id: str | None = None+ sort: str = "recent"+ limit: int = 50+ offset: int = 0++ def normalized(self) -> "QuestionBankQuery":+ """Clamp untrusted inputs into the ranges the SQL below assumes."""+ return QuestionBankQuery(+ category_id=self.category_id,+ uncategorized=self.uncategorized and self.category_id is None,+ bookmarked=self.bookmarked,+ is_correct=self.is_correct,+ search=(self.search or "").strip()[:200],+ session_id=self.session_id,+ sort="oldest" if self.sort == "oldest" else "recent",+ limit=max(1, min(int(self.limit), 500)),+ offset=max(0, int(self.offset)),+ )++class SQLiteSessionStore:"""Persist unified chat sessions and messages in a SQLite database."""@@ -1626,16 +1670,81 @@ class SQLiteSessionStore:"updated_at": float(row["updated_at"]),}- def _list_notebook_entries_sync(- self,- category_id: int | None,- bookmarked: bool | None,- is_correct: bool | None,- limit: int,- offset: int,- session_id: str | None = None,- ) -> dict[str, Any]:- base = """+ # ---- question bank (notebook_entries) queries -----------------------++ @staticmethod+ def _question_bank_filters(query: QuestionBankQuery) -> tuple[str, str, list[Any]]:+ """Build the ``(join, where, params)`` triple shared by list + count.++ Kept apart from the SELECT so the row query and the COUNT query can+ never drift into filtering different sets — the bug that makes a+ paginated list report a total it does not contain.+ """+ joins: list[str] = []+ conditions: list[str] = []+ params: list[Any] = []++ if query.category_id is not None:+ joins.append(" INNER JOIN notebook_entry_categories ec ON ec.entry_id = n.id")+ conditions.append("ec.category_id = ?")+ params.append(query.category_id)+ elif query.uncategorized:+ conditions.append(+ "NOT EXISTS (SELECT 1 FROM notebook_entry_categories ec WHERE ec.entry_id = n.id)"+ )+ if query.bookmarked is not None:+ conditions.append("n.bookmarked = ?")+ params.append(1 if query.bookmarked else 0)+ if query.is_correct is not None:+ conditions.append("n.is_correct = ?")+ params.append(1 if query.is_correct else 0)+ if query.session_id is not None:+ conditions.append("n.session_id = ?")+ params.append(query.session_id)+ if query.search:+ # ESCAPE so a learner searching for "50%" or "a_b" gets literal+ # matches instead of the wildcards those characters would be.+ needle = f"%{_escape_like(query.search)}%"+ conditions.append(+ "(n.question LIKE ? ESCAPE '\\' OR n.user_answer LIKE ? ESCAPE '\\' "+ "OR n.correct_answer LIKE ? ESCAPE '\\' OR n.explanation LIKE ? ESCAPE '\\')"+ )+ params.extend([needle] * 4)++ join_sql = "".join(joins)+ where_sql = (" WHERE " + " AND ".join(conditions)) if conditions else ""+ return join_sql, where_sql, params++ @staticmethod+ def _load_categories_for(+ conn: sqlite3.Connection, entry_ids: list[int]+ ) -> dict[int, list[dict[str, Any]]]:+ """Fetch every entry's categories in one query (never N+1)."""+ if not entry_ids:+ return {}+ placeholders = ",".join("?" * len(entry_ids))+ rows = conn.execute(+ f"""+ SELECT ec.entry_id, c.id, c.name+ FROM notebook_entry_categories ec+ INNER JOIN notebook_categories c ON c.id = ec.category_id+ WHERE ec.entry_id IN ({placeholders})+ ORDER BY c.name+ """,+ tuple(entry_ids),+ ).fetchall()+ grouped: dict[int, list[dict[str, Any]]] = {}+ for row in rows:+ grouped.setdefault(int(row["entry_id"]), []).append(+ {"id": row["id"], "name": row["name"]}+ )+ return grouped++ def _list_notebook_entries_sync(self, query: QuestionBankQuery) -> dict[str, Any]:+ query = query.normalized()+ join_sql, where_sql, params = self._question_bank_filters(query)+ order = "ASC" if query.sort == "oldest" else "DESC"+ base = f"""SELECTn.id, n.session_id, COALESCE(s.title, '') AS session_title,n.turn_id, n.question_id, n.question, n.question_type, n.options_json,@@ -1643,35 +1752,24 @@ class SQLiteSessionStore:n.user_answer, n.user_answer_images_json, n.is_correct, n.bookmarked,n.followup_session_id, n.ai_judgment, n.created_at, n.updated_atFROM notebook_entries n- LEFT JOIN sessions s ON s.id = n.session_id+ LEFT JOIN sessions s ON s.id = n.session_id{join_sql}"""- count_base = "SELECT COUNT(*) AS cnt FROM notebook_entries n"- conditions: list[str] = []- params: list[Any] = []- if category_id is not None:- join = " INNER JOIN notebook_entry_categories ec ON ec.entry_id = n.id"- base += join- count_base += join- conditions.append("ec.category_id = ?")- params.append(category_id)- if bookmarked is not None:- conditions.append("n.bookmarked = ?")- params.append(1 if bookmarked else 0)- if is_correct is not None:- conditions.append("n.is_correct = ?")- params.append(1 if is_correct else 0)- if session_id is not None:- conditions.append("n.session_id = ?")- params.append(session_id)- where = (" WHERE " + " AND ".join(conditions)) if conditions else ""+ count_sql = f"SELECT COUNT(*) AS cnt FROM notebook_entries n{join_sql}{where_sql}"with self._connect() as conn:- total_row = conn.execute(count_base + where, tuple(params)).fetchone()+ total_row = conn.execute(count_sql, tuple(params)).fetchone()total = int(total_row["cnt"]) if total_row else 0rows = conn.execute(- base + where + " ORDER BY n.created_at DESC LIMIT ? OFFSET ?",- tuple(params) + (limit, offset),+ base+ + where_sql+ # ``n.id`` breaks ties: a batch upserted in one call shares a+ # created_at, and an unstable order duplicates/drops rows across pages.+ + f" ORDER BY n.created_at {order}, n.id {order} LIMIT ? OFFSET ?",+ tuple(params) + (query.limit, query.offset),).fetchall()- items = [self._serialize_notebook_entry(r) for r in rows]+ items = [self._serialize_notebook_entry(r) for r in rows]+ grouped = self._load_categories_for(conn, [int(i["id"]) for i in items])+ for item in items:+ item["categories"] = grouped.get(int(item["id"]), [])return {"items": items, "total": total}async def list_notebook_entries(@@ -1683,17 +1781,70 @@ class SQLiteSessionStore:offset: int = 0,*,session_id: str | None = None,+ search: str = "",+ uncategorized: bool = False,+ sort: str = "recent",) -> dict[str, Any]:+ """List question-bank entries. Every row carries its categories."""return await self._run(self._list_notebook_entries_sync,- category_id,- bookmarked,- is_correct,- limit,- offset,- session_id,+ QuestionBankQuery(+ category_id=category_id,+ uncategorized=uncategorized,+ bookmarked=bookmarked,+ is_correct=is_correct,+ search=search,+ session_id=session_id,+ sort=sort,+ limit=limit,+ offset=offset,+ ),)+ def _question_bank_stats_sync(self) -> dict[str, int]:+ with self._connect() as conn:+ row = conn.execute(+ """+ SELECT+ COUNT(*) AS total,+ COALESCE(SUM(CASE WHEN is_correct = 0 THEN 1 ELSE 0 END), 0) AS wrong,+ COALESCE(SUM(CASE WHEN bookmarked = 1 THEN 1 ELSE 0 END), 0) AS bookmarked,+ COALESCE(SUM(+ CASE WHEN NOT EXISTS (+ SELECT 1 FROM notebook_entry_categories ec+ WHERE ec.entry_id = notebook_entries.id+ ) THEN 1 ELSE 0 END+ ), 0) AS uncategorized+ FROM notebook_entries+ """+ ).fetchone()+ if row is None:+ return {"total": 0, "wrong": 0, "bookmarked": 0, "uncategorized": 0}+ return {+ "total": int(row["total"]),+ "wrong": int(row["wrong"]),+ "bookmarked": int(row["bookmarked"]),+ "uncategorized": int(row["uncategorized"]),+ }++ def has_question_bank_entries(self) -> bool:+ """Whether the bank holds anything at all — the tool's mount gate.++ Deliberately synchronous: tool composition runs inside a sync+ policy function, and a bool probe is one indexed row read. Fails+ closed so a missing/locked db never mounts a tool with no data.+ """+ try:+ with self._connect() as conn:+ row = conn.execute("SELECT 1 FROM notebook_entries LIMIT 1").fetchone()+ return row is not None+ except Exception:+ return False++ async def question_bank_stats(self) -> dict[str, int]:+ """Counts behind the bank's filter chips (and the agent's overview)."""+ return await self._run(self._question_bank_stats_sync)+def _get_notebook_entry_sync(self, entry_id: int) -> dict[str, Any] | None:with self._connect() as conn:row = conn.execute(@@ -1801,15 +1952,33 @@ class SQLiteSessionStore:# ── Notebook categories ────────────────────────────────────────+ @staticmethod+ def _name_taken(conn: sqlite3.Connection, name: str, *, excluding: int | None = None) -> bool:+ """Whether a category already claims this name, ignoring case.++ The table's UNIQUE index is case-sensitive, so "Math" and "math"+ both fit — but they read as one pile to a learner, and the agent+ resolves names case-insensitively, so it would file into the first+ and report a name the learner sees twice in the rail.+ """+ row = conn.execute(+ "SELECT id FROM notebook_categories WHERE name = ? COLLATE NOCASE",+ (name.strip(),),+ ).fetchone()+ return row is not None and (excluding is None or int(row["id"]) != excluding)+def _create_category_sync(self, name: str) -> dict[str, Any]:now = time.time()+ cleaned = name.strip()with self._connect() as conn:+ if self._name_taken(conn, cleaned):+ raise ValueError(f"A category named {cleaned!r} already exists.")cur = conn.execute("INSERT INTO notebook_categories (name, created_at) VALUES (?, ?)",- (name.strip(), now),+ (cleaned, now),)conn.commit()- return {"id": int(cur.lastrowid), "name": name.strip(), "created_at": now}+ return {"id": int(cur.lastrowid), "name": cleaned, "created_at": now}async def create_category(self, name: str) -> dict[str, Any]:return await self._run(self._create_category_sync, name)@@ -1840,10 +2009,15 @@ class SQLiteSessionStore:return await self._run(self._list_categories_sync)def _rename_category_sync(self, category_id: int, name: str) -> bool:+ cleaned = name.strip()with self._connect() as conn:+ # Without this the UNIQUE index raises straight through the+ # router as a 500; a name clash is a request problem, not a bug.+ if self._name_taken(conn, cleaned, excluding=category_id):+ raise ValueError(f"A category named {cleaned!r} already exists.")cur = conn.execute("UPDATE notebook_categories SET name = ? WHERE id = ?",- (name.strip(), category_id),+ (cleaned, category_id),)conn.commit()return cur.rowcount > 0@@ -1903,6 +2077,70 @@ class SQLiteSessionStore:async def get_entry_categories(self, entry_id: int) -> list[dict[str, Any]]:return await self._run(self._get_entry_categories_sync, entry_id)+ def _link_entries_to_category_sync(+ self, entry_ids: list[int], category_id: int, link: bool+ ) -> int:+ """Add/remove many entries to one category in a single transaction.++ Returns the number of links actually changed, so a caller that asked+ to file 20 questions can tell the learner "18 filed, 2 already there"+ instead of claiming a no-op succeeded.+ """+ if not entry_ids:+ return 0+ with self._connect() as conn:+ exists = conn.execute(+ "SELECT 1 FROM notebook_categories WHERE id = ?", (category_id,)+ ).fetchone()+ if exists is None:+ return 0+ placeholders = ",".join("?" * len(entry_ids))+ # Filter to entries that really exist: a stale id from the agent+ # or a concurrently-deleted row must not abort the whole batch.+ known = [+ int(r["id"])+ for r in conn.execute(+ f"SELECT id FROM notebook_entries WHERE id IN ({placeholders})",+ tuple(entry_ids),+ ).fetchall()+ ]+ if not known:+ return 0+ if link:+ cur = conn.executemany(+ "INSERT OR IGNORE INTO notebook_entry_categories "+ "(entry_id, category_id) VALUES (?, ?)",+ [(eid, category_id) for eid in known],+ )+ else:+ cur = conn.executemany(+ "DELETE FROM notebook_entry_categories WHERE entry_id = ? AND category_id = ?",+ [(eid, category_id) for eid in known],+ )+ return int(cur.rowcount or 0)++ async def link_entries_to_category(+ self, entry_ids: list[int], category_id: int, *, link: bool = True+ ) -> int:+ return await self._run(+ self._link_entries_to_category_sync, list(entry_ids), category_id, link+ )++ def _find_category_by_name_sync(self, name: str) -> dict[str, Any] | None:+ with self._connect() as conn:+ row = conn.execute(+ "SELECT id, name, created_at FROM notebook_categories "+ "WHERE name = ? COLLATE NOCASE ORDER BY id LIMIT 1",+ (name.strip(),),+ ).fetchone()+ if row is None:+ return None+ return {"id": int(row["id"]), "name": row["name"], "created_at": float(row["created_at"])}++ async def find_category_by_name(self, name: str) -> dict[str, Any] | None:+ """Look a category up by display name — the only handle an agent has."""+ return await self._run(self._find_category_by_name_sync, name)+_instances: dict[str, SQLiteSessionStore] = {}@@ -1915,4 +2153,9 @@ def get_sqlite_session_store() -> SQLiteSessionStore:return _instances[key]-__all__ = ["SQLiteSessionStore", "get_sqlite_session_store", "make_imported_session_id"]+__all__ = [+ "QuestionBankQuery",+ "SQLiteSessionStore",+ "get_sqlite_session_store",+ "make_imported_session_id",+]diff --git a/tests/api/test_question_bank_api.py b/tests/api/test_question_bank_api.pynew file mode 100644index 000000000..38ec405e0--- /dev/null+++ b/tests/api/test_question_bank_api.py@@ -0,0 +1,205 @@+"""Question-bank API surface added for triage: search, sort, inbox, bulk, stats."""++from __future__ import annotations++import asyncio+import importlib+from pathlib import Path++import pytest++pytest.importorskip("fastapi")++FastAPI = pytest.importorskip("fastapi").FastAPI+TestClient = pytest.importorskip("fastapi.testclient").TestClient+notebook_router = importlib.import_module("deeptutor.api.routers.question_notebook").router++from deeptutor.services.session.sqlite_store import SQLiteSessionStore++PREFIX = "/api/v1/question-notebook"+++def client(tmp_path: Path, monkeypatch):+ store = SQLiteSessionStore(db_path=tmp_path / "bank.db")+ monkeypatch.setattr(+ "deeptutor.api.routers.question_notebook.get_sqlite_session_store",+ lambda: store,+ )+ app = FastAPI()+ app.include_router(notebook_router, prefix=PREFIX)+ with TestClient(app) as test_client:+ test_client.store = store # type: ignore[attr-defined]+ yield test_client+++def _seed(client) -> list[int]:+ store: SQLiteSessionStore = client.store++ async def run() -> list[int]:+ session_id = (await store.create_session(title="Drill"))["id"]+ await store.upsert_notebook_entries(+ session_id,+ [+ {+ "turn_id": "t1",+ "question_id": "q1",+ "question": "What is 50% of 8?",+ "correct_answer": "4",+ "user_answer": "5",+ "is_correct": False,+ },+ {+ "turn_id": "t1",+ "question_id": "q2",+ "question": "Name the a_b convention",+ "correct_answer": "snake_case",+ "user_answer": "snake_case",+ "is_correct": True,+ },+ ],+ )+ listing = await store.list_notebook_entries()+ return [int(i["id"]) for i in listing["items"]]++ return asyncio.run(run())+++def test_stats_reports_the_triage_counts(client):+ _seed(client)+ body = client.get(f"{PREFIX}/stats").json()+ assert body == {"total": 2, "wrong": 1, "bookmarked": 0, "uncategorized": 2}+++def test_listing_carries_each_entry_categories(client):+ ids = _seed(client)+ category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]+ client.post(f"{PREFIX}/entries/{ids[0]}/categories", json={"category_id": category_id})++ items = client.get(f"{PREFIX}/entries").json()["items"]+ by_id = {item["id"]: item for item in items}+ assert [c["name"] for c in by_id[ids[0]]["categories"]] == ["Set A"]+ assert by_id[ids[1]]["categories"] == []+++def test_search_treats_wildcards_literally(client):+ _seed(client)+ hits = client.get(f"{PREFIX}/entries", params={"search": "50%"}).json()+ assert hits["total"] == 1+ assert "50%" in hits["items"][0]["question"]++ underscore = client.get(f"{PREFIX}/entries", params={"search": "a_b"}).json()+ assert underscore["total"] == 1+++def test_uncategorized_filter_is_the_inbox(client):+ ids = _seed(client)+ category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]+ client.post(f"{PREFIX}/entries/{ids[0]}/categories", json={"category_id": category_id})++ inbox = client.get(f"{PREFIX}/entries", params={"uncategorized": True}).json()+ assert [item["id"] for item in inbox["items"]] == [ids[1]]+++def test_explicit_category_wins_over_uncategorized(client):+ ids = _seed(client)+ category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]+ client.post(f"{PREFIX}/entries/{ids[0]}/categories", json={"category_id": category_id})++ both = client.get(+ f"{PREFIX}/entries", params={"uncategorized": True, "category_id": category_id}+ ).json()+ assert [item["id"] for item in both["items"]] == [ids[0]]+++def test_sort_is_stable_across_a_same_timestamp_batch(client):+ _seed(client)+ recent = [+ i["id"] for i in client.get(f"{PREFIX}/entries", params={"sort": "recent"}).json()["items"]+ ]+ oldest = [+ i["id"] for i in client.get(f"{PREFIX}/entries", params={"sort": "oldest"}).json()["items"]+ ]+ assert recent == list(reversed(oldest))+++def test_bulk_link_and_unlink(client):+ ids = _seed(client)+ category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]++ added = client.post(+ f"{PREFIX}/entries/categories/bulk",+ json={"entry_ids": ids, "category_id": category_id},+ ).json()+ assert added["changed"] == len(ids)++ repeat = client.post(+ f"{PREFIX}/entries/categories/bulk",+ json={"entry_ids": ids, "category_id": category_id},+ ).json()+ assert repeat["changed"] == 0++ removed = client.post(+ f"{PREFIX}/entries/categories/bulk",+ json={"entry_ids": ids, "category_id": category_id, "link": False},+ ).json()+ assert removed["changed"] == len(ids)+++def test_bulk_route_is_not_shadowed_by_the_per_entry_route(client):+ ids = _seed(client)+ category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]+ response = client.post(+ f"{PREFIX}/entries/categories/bulk",+ json={"entry_ids": ids, "category_id": category_id},+ )+ # A shadowed literal path would try to parse "categories" as an int id.+ assert response.status_code == 200+++def test_bulk_rejects_an_empty_batch(client):+ _seed(client)+ response = client.post(+ f"{PREFIX}/entries/categories/bulk", json={"entry_ids": [], "category_id": 1}+ )+ assert response.status_code == 422+++def test_invalid_sort_is_rejected(client):+ _seed(client)+ assert client.get(f"{PREFIX}/entries", params={"sort": "sideways"}).status_code == 422+++def test_case_only_duplicate_category_is_rejected(client):+ assert client.post(f"{PREFIX}/categories", json={"name": "Math"}).status_code == 201+ clash = client.post(f"{PREFIX}/categories", json={"name": " math "})+ # "Math" and "math" read as one pile to a learner, and the agent resolves+ # names case-insensitively — allowing both makes the two disagree.+ assert clash.status_code == 409+ assert "already exists" in clash.json()["detail"]+ assert len(client.get(f"{PREFIX}/categories").json()) == 1+++def test_rename_onto_an_existing_name_is_a_conflict_not_a_crash(client):+ first = client.post(f"{PREFIX}/categories", json={"name": "Math"}).json()+ second = client.post(f"{PREFIX}/categories", json={"name": "Physics"}).json()++ clash = client.patch(f"{PREFIX}/categories/{second['id']}", json={"name": "Math"})+ # The UNIQUE index used to raise straight through as a 500.+ assert clash.status_code == 409+ assert "already exists" in clash.json()["detail"]++ # Renaming a category to the name it already has is not a clash.+ same = client.patch(f"{PREFIX}/categories/{first['id']}", json={"name": "Math"})+ assert same.status_code == 200++ moved = client.patch(f"{PREFIX}/categories/{first['id']}", json={"name": "Calculus"})+ assert moved.status_code == 200+ assert sorted(c["name"] for c in client.get(f"{PREFIX}/categories").json()) == [+ "Calculus",+ "Physics",+ ]+++def test_renaming_a_missing_category_is_404(client):+ assert client.patch(f"{PREFIX}/categories/9999", json={"name": "Ghost"}).status_code == 404