diff --git a/backend/README.md b/backend/README.md index e607722..2a5ef33 100644 --- a/backend/README.md +++ b/backend/README.md @@ -84,13 +84,17 @@ tests/ 入库 ──► 观察中 ──(次日复核做对)──► 粗心小记(不进队列) │ └─(复核做错)──► 待复习 ──(做对 1 次)──► 已对 1 次 ──(再对)──► 待讲清 - ▲ │ - │ 讲清通过 │ + ▲ │ │ + │ └─(当天错了又对)──► 会但不稳 ──(次日再对)──┘ + │ │ └──────── 答错/讲不清:间隔归零,明天 ────────┴──► 已毕业 ``` - **只错三次才入库**:第 1 次进「观察中」,第 2 次仍观察,第 3 次才进复习队列(`scheduler.on_import`)。 - **粗心隔离**:24 小时内还能做对 → 判为执行失误,进「粗心小记」,不做重做训练。 +- **会但不稳(第三态)**:同一道题当天先错、看完解析当场又做对 → 不算连对一次,进 `unstable`,明天从头再来; + 做对一次才回到 `passed_once`。理由是「听完会了」不等于「明天还记得」,也是家长最常问的「怎么又错了」的解释。 + `mistakes.unstable_count` 记次数,周报里单独显示「会但不稳 N 道」。 - **连对两次才到「讲清」**:同题第二次靠记忆,所以第二档之后必须讲一遍。 - **间隔**:1 → 3 → 7 → 15 → 30 天;答错或讲不清 → 归零,明天再来。 - **每天最多 5 道**:`DAILY_CAP=5`,服务端截断,第 5 道之后不再追加。 @@ -502,3 +506,22 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务 顺带记两个坑:`_LINE_NO` 少写 `(?!\d)` 会把 `1.8+0.6` 的 `1.` 当题号(算成 8.6); `safe_eval` 曾走 `normalize`,那里的 `strip_punct` 会把括号剥掉,`34×(90-46)` 静默变成 `34*90-46`。(见四点二十一) + +### 四点二十三、会但不稳:当天错了又对,不算连对 + +原来的规则是「做对就往前推一档」,于是课堂/家庭场景里最常见的一幕被记成了掌握: +孩子做错 → 看解析 → 当场再写一遍,对了。但那只是「听完会了」,明天还记不记得,没验过。 + +- 新增状态 `unstable`(界面文案「会但不稳」):`mistakes.unstable_count` 记次数,`stage` 不动, + `next_due` = 明天,`is_due` 认它,所以明天还会出现在队列里 +- 判定发生在 `services.attempt()` / `self_judge()`:做题前查 + `attempts` 里有没有**今天**这条错题的错答;有才传 `same_day_wrong=True` +- 次日再做对 → 正常进 `passed_once`,间隔从 1 天重新开始(不是接着原来的 3/7 天) +- 周报 `numbers.unstable_total`、首页「错题消灭率」小字、错题本筛选与橙色状态标签都把它显示出来: + 它既不是「已毕业」,也不是「没懂」,家长需要这个中间答案 +- `dev_advance()` 现在同时挪 `attempts` / `explain_attempts` 的 `created_at`—— + 否则演示脚本里「今天错了今天又对」永远成立,第二天做对也判不成连对(踩过一次) + +初中版(`junior/`)暂不套用这条规则:它用「做对一道变式」替代第二次连对, +「当天再对一次」在那边本来就不算过关,语义已经不同。 + diff --git a/backend/db.py b/backend/db.py index 2797046..db96358 100644 --- a/backend/db.py +++ b/backend/db.py @@ -100,6 +100,7 @@ CREATE TABLE IF NOT EXISTS mistakes ( interval_days INTEGER NOT NULL DEFAULT 1, next_due TEXT, explain_fails INTEGER NOT NULL DEFAULT 0, + unstable_count INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, graduated_at TEXT ); @@ -270,10 +271,15 @@ def init_db(conn: sqlite3.Connection) -> None: def _migrate(conn: sqlite3.Connection) -> None: """老库补列(CREATE TABLE IF NOT EXISTS 不会改已存在的表)。""" - want = {"questions": ["options", "kp"], "mistakes": ["options", "kp"], - "guardians": ["phone"], "papers": ["clean_path", "image_path"]} + want = { + "questions": {"options": "TEXT", "kp": "TEXT"}, + "mistakes": {"options": "TEXT", "kp": "TEXT", + "unstable_count": "INTEGER NOT NULL DEFAULT 0"}, + "guardians": {"phone": "TEXT"}, + "papers": {"clean_path": "TEXT", "image_path": "TEXT"}, + } for table, cols in want.items(): - ensure_columns(conn, table, {c: "TEXT" for c in cols}) + ensure_columns(conn, table, cols) def reset_db(conn: sqlite3.Connection) -> None: diff --git a/backend/scheduler.py b/backend/scheduler.py index 2084b72..dc98053 100644 --- a/backend/scheduler.py +++ b/backend/scheduler.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- """错题状态机与复习调度(SM-2 简化版)。 -状态(6 个): +状态(7 个): observing 观察中 刚入库,错因暂定 E4;不进队列 queued 待复习 到期了就进今日队列 + unstable 会但不稳 今天错过、当天又做对了——不算数,明天从头再来 passed_once 已对 1 次 再做对一次就进「待讲清」 to_explain 待讲清 等孩子讲一遍(不进刷题队列) graduated 已毕业 讲清通过 → 进「已消灭」档案,永不再推 @@ -24,6 +25,7 @@ CLEAR_CARELESS_WINDOW_HOURS = 24 STATUS_ZH = { "observing": "观察中", "queued": "待复习", + "unstable": "会但不稳", "passed_once": "已对 1 次", "to_explain": "待讲清", "graduated": "已毕业", @@ -44,8 +46,9 @@ def is_due(mistake: dict, on: str | None = None) -> bool: """到期 = 该出现在今天列表里。 观察中的题也会在次日回来「复核」一次:做对就是粗心,做错才确认没懂。 + 不稳的题同样回到队列:今天错、今天对的,明天必须再做对一次才算过。 """ - if mistake.get("status") not in ("observing", "queued", "passed_once"): + if mistake.get("status") not in ("observing", "queued", "unstable", "passed_once"): return False due = mistake.get("next_due") return bool(due) and due <= (on or today()) @@ -58,8 +61,14 @@ def due_today(mistakes: list[dict], on: str | None = None, cap: int = DAILY_CAP) return items[:cap] -def on_attempt(mistake: dict, correct: bool, created_at: str | None = None) -> dict: - """做了一次(重做/口答)。返回要写回 mistakes 的字段。""" +def on_attempt(mistake: dict, correct: bool, *, created_at: str | None = None, + same_day_wrong: bool = False) -> dict: + """做了一次(重做/口答)。返回要写回 mistakes 的字段。 + + :param same_day_wrong: 这道题「今天」已经错过一次。看完解析当场再做对, + 只能说明「听完会了」,说明不了「记住了」——所以不推进档位, + 只记一道「会但不稳」,明天再从头做对一次才算第一次。 + """ ts = created_at or now() stage = int(mistake.get("stage") or 0) wrong_count = int(mistake.get("wrong_count") or 1) @@ -74,6 +83,16 @@ def on_attempt(mistake: dict, correct: bool, created_at: str | None = None) -> d # 隔了更久还能做对 → 不是没懂,是「会但不熟」,拉开间隔进队列 return {"status": "queued", "stage": 1, "interval_days": 3, "next_due": add_days(3, base=_date_of(ts)), "wrong_code": "E3"} + if same_day_wrong: + # 当天错了又对:不算数,明天重来;连错两次以上的是「没懂」,不是「不稳」 + return { + "status": "unstable", + "stage": 0, + "interval_days": 1, + "next_due": add_days(1, base=_date_of(ts)), + "unstable_count": int(mistake.get("unstable_count") or 0) + 1, + "wrong_code": mistake.get("wrong_code") or "E4", + } stage += 1 interval = INTERVALS[min(stage - 1, len(INTERVALS) - 1)] if stage >= 2: diff --git a/backend/services.py b/backend/services.py index 598398d..eeace54 100644 --- a/backend/services.py +++ b/backend/services.py @@ -917,7 +917,11 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | if correct is None: return {"mistake_id": mid, "correct": None, "detail": detail, "refused": True, "hint": "机器不判这类题,标给家长/老师"} - state = scheduler.on_attempt(mdict, correct) + # 今天已经错过一次?那这次做对只能证明「看完解析会了」,不能算连对一次 + same_day_wrong = conn.execute( + "SELECT 1 FROM attempts WHERE mistake_id=? AND is_correct=0" + " AND substr(created_at,1,10)=? LIMIT 1", (mid, today())).fetchone() is not None + state = scheduler.on_attempt(mdict, correct, same_day_wrong=same_day_wrong) with tx(conn): conn.execute("INSERT INTO attempts (id, mistake_id, child_id, answer_text, is_correct, cost_ms, created_at)" " VALUES (?,?,?,?,?,?,?)", @@ -938,6 +942,10 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | "stage": state.get("stage", mdict["stage"]), "next_due": state.get("next_due"), "need_explain": state["status"] == "to_explain", + # 会但不稳:当天错了又对。前端要明说「这次不算」,否则孩子以为过关了 + "unstable": state["status"] == "unstable", + "unstable_hint": ("这次算「会但不稳」——明天同一道题再做对一次,才往前算。" + if state["status"] == "unstable" else None), } @@ -1062,6 +1070,8 @@ def weekly_report(conn, gid: str, cid: str, week_of: str | None = None) -> dict: total_mistakes = conn.execute("SELECT COUNT(*) c FROM mistakes WHERE child_id=?", (cid,)).fetchone()["c"] graduated = conn.execute( "SELECT COUNT(*) c FROM mistakes WHERE child_id=? AND status='graduated'", (cid,)).fetchone()["c"] + unstable = conn.execute( + "SELECT COUNT(*) c FROM mistakes WHERE child_id=? AND status='unstable'", (cid,)).fetchone()["c"] return { "child": {"id": cid, "nickname": child["nickname"], "grade": child["grade"]}, "week": {"start": start, "end": end}, @@ -1071,6 +1081,7 @@ def weekly_report(conn, gid: str, cid: str, week_of: str | None = None) -> dict: "attempts_this_week": len(attempts), "review_days": len(daily), "graduated_total": graduated, + "unstable_total": unstable, "active_total": total_mistakes - graduated, "kill_rate": round(graduated / total_mistakes * 100, 1) if total_mistakes else 0.0, }, @@ -1275,6 +1286,8 @@ def stats(conn, gid: str, cid: str) -> dict: "mistakes_total": total, "by_status": by_status, "graduated": graduated, + # 会但不稳:介于「已毕业」和「没懂」之间的第三态,家长看得懂,也解释了「怎么又错了」 + "unstable": by_status.get("unstable", 0), "kill_rate": round(graduated / total * 100, 1) if total else 0.0, "attempts_last7d": last7, "north_star": "月消灭率 ≥ 40%(已毕业 / 全部错题)", @@ -1282,9 +1295,15 @@ def stats(conn, gid: str, cid: str) -> dict: def dev_advance(conn, days: int = 1) -> dict: - """演示用:把「明天到期」提前到今天,方便一条命令看到完整生命周期。""" - conn.execute("UPDATE mistakes SET next_due = date(next_due, ?) WHERE next_due IS NOT NULL", - (f"-{int(days)} days",)) + """演示用:把「明天到期」提前到今天,方便一条命令看到完整生命周期。 + + 做题记录也一起往前挪:不然「今天错了、今天又对了」这条规则在演示里 + 永远成立,孩子第二天做对也判不成「连对一次」。 + """ + shift = f"-{int(days)} days" + conn.execute("UPDATE mistakes SET next_due = date(next_due, ?) WHERE next_due IS NOT NULL", (shift,)) + conn.execute("UPDATE attempts SET created_at = datetime(created_at, ?)", (shift,)) + conn.execute("UPDATE explain_attempts SET created_at = datetime(created_at, ?)", (shift,)) return {"advanced_days": days, "due_now": conn.execute( "SELECT COUNT(*) c FROM mistakes WHERE next_due<=?", (today(),)).fetchone()["c"]} @@ -1562,7 +1581,10 @@ def self_judge(conn, gid: str, cid: str, mid: str, correct: bool, note: str = "" mdict = dict(m) if mdict["status"] in ("graduated", "careless"): raise ApiError(409, "NOT_IN_QUEUE", "这道题已经不在队列里了(已毕业或在粗心小记)") - state = scheduler.on_attempt(mdict, bool(correct)) + same_day_wrong = conn.execute( + "SELECT 1 FROM attempts WHERE mistake_id=? AND is_correct=0" + " AND substr(created_at,1,10)=? LIMIT 1", (mid, today())).fetchone() is not None + state = scheduler.on_attempt(mdict, bool(correct), same_day_wrong=same_day_wrong) with tx(conn): conn.execute( "INSERT INTO attempts (id, mistake_id, child_id, answer_text, is_correct, cost_ms, source, created_at)" @@ -1580,6 +1602,7 @@ def self_judge(conn, gid: str, cid: str, mid: str, correct: bool, note: str = "" "stage": state.get("stage", mdict["stage"]), "next_due": state.get("next_due"), "need_explain": state["status"] == "to_explain", + "unstable": state["status"] == "unstable", } diff --git a/data/_ocrcache_test/4efb2f53091b018c12143673b069c4213e9642ce.json b/data/_ocrcache_test/4efb2f53091b018c12143673b069c4213e9642ce.json deleted file mode 100644 index 69a3dd5..0000000 --- a/data/_ocrcache_test/4efb2f53091b018c12143673b069c4213e9642ce.json +++ /dev/null @@ -1 +0,0 @@ -{"ok": true, "data": {}} \ No newline at end of file diff --git a/prototype/workbench/README.md b/prototype/workbench/README.md index 56bf6d2..2bdd329 100644 --- a/prototype/workbench/README.md +++ b/prototype/workbench/README.md @@ -31,7 +31,7 @@ prototype/workbench/index.html ← 全部代码都在这一个文件里 |---|---|---| | 工作台 | `#home` | 今天几道 / 本周毕业 / 消灭率 + 今日队列 + 这周那张纸 | | 今日训练 | `#train` | 一屏一道 → 判对错 → 解析三 tab → 举一反三 → 答题卡 | -| 错题本 | `#wrong` | 全部错题,按状态筛(待复习 / 待讲清 / 已毕业 / 粗心) | +| 错题本 | `#wrong` | 全部错题,按状态筛(待复习 / 会但不稳 / 待讲清 / 已毕业 / 粗心) | | 复习计划 | `#plan` | 未来 7 天每天要复习几道 | | 学情分析 | `#analysis` | 错因分布(E1–E6)+ 薄弱知识点 + 一周趋势 | | 周报与打印 | `#weekly` | 本周四个数字 + A5 预览 + 打印 | diff --git a/prototype/workbench/index.html b/prototype/workbench/index.html index 5b681eb..c07cbb5 100644 --- a/prototype/workbench/index.html +++ b/prototype/workbench/index.html @@ -112,6 +112,7 @@ h1{font-size:22px;margin:0 0 4px} .pill.c{background:var(--brand-soft);color:var(--brand-d)} .pill.g{background:var(--green-soft);color:var(--green)} .pill.b{background:var(--blue-soft);color:var(--blue)} +.pill.o{background:var(--ochre-soft);color:var(--ochre)} .pill.gray{background:#F2EDE4;color:#7C7166} /* ---------- 训练页 ---------- */ @@ -170,6 +171,7 @@ h1{font-size:22px;margin:0 0 4px} .result{margin-top:16px;border-radius:12px;padding:14px 16px;font-size:14px;line-height:1.7;display:none} .result.ok{display:block;background:var(--green-soft);border:1px solid #CFE3D6;color:#245744} +.result.mid{display:block;background:var(--ochre-soft);border:1px solid #EFDCAE;color:#7A5410} .result.no{display:block;background:var(--red-soft);border:1px solid #F2D3CD;color:#8E2B23} .result b{font-size:15px} @@ -531,7 +533,7 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
错题消灭率
36.4%
-
目标 40% · 按已毕业 / 全部错题
+
目标 40% · 按已毕业 / 全部错题
@@ -714,6 +716,7 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px} + @@ -906,8 +909,10 @@ const DEMO = { { id: "m7", stem: "600 - 247 =", subject: "math", status: "graduated", status_zh: "已毕业", wrong_code: "E4", next_due: "—" }, { id: "m8", stem: "填量词:一( )书", subject: "chinese", status: "careless", status_zh: "粗心小记", wrong_code: "E4", next_due: "—" }, { id: "m9", stem: "128 + 275 =", subject: "math", status: "observing", status_zh: "观察中", wrong_code: "E4", next_due: "明天" }, + { id: "m10", stem: "72 ÷ 8 =", subject: "math", status: "unstable", status_zh: "会但不稳", wrong_code: "E2", next_due: "明天" }, + { id: "m11", stem: "看拼音写词:chūn tiān", subject: "chinese", status: "unstable", status_zh: "会但不稳", wrong_code: "E2", next_due: "明天" }, ], - weekly: { numbers: { new_this_week: 9, graduated_this_week: 4, attempts_this_week: 21, review_days: 6, kill_rate: 36.4 }, + weekly: { numbers: { new_this_week: 9, graduated_this_week: 4, attempts_this_week: 21, review_days: 6, kill_rate: 36.4, unstable_total: 3 }, weakest: ["E3 会但不熟", "E4 会但做错", "E2 概念没懂"], one_line: "本周新增 9 道,消灭 4 道,还有 5 道在队列里;最弱的是「会但不熟」,建议把间隔拉开到 3 天。", guardian_note: "孩子做错的题,先别讲,让他明天再做一遍。" }, @@ -1104,7 +1109,7 @@ async function refresh() { const GRADE = ["一", "二", "三", "四", "五", "六"]; const SUBJ = { math: "数学", chinese: "语文" }; const JTYPE = { calc: "计算题", text: "填空题", choice: "选择题", manual: "自评题" }; -const STATUS_CLS = { graduated: "g", to_explain: "c", careless: "gray", queued: "", observing: "b", recalled: "b" }; +const STATUS_CLS = { graduated: "g", to_explain: "c", unstable: "o", careless: "gray", queued: "", observing: "b", recalled: "b" }; function renderAll() { setTimeout(() => petRender(), 0); @@ -1118,6 +1123,11 @@ function renderAll() { const n = w.numbers || {}; document.getElementById("sGrad").innerHTML = (n.graduated_this_week || 0) + "道"; document.getElementById("sKill").innerHTML = (n.kill_rate || 0) + "%"; + // 会但不稳:第三态写在这块小字里,不新开卡片(首页只放三个数) + const un = n.unstable_total || 0; + document.getElementById("sKillNote").textContent = un + ? `目标 40% · 另有 ${un} 道会但不稳` + : "目标 40% · 按已毕业 / 全部错题"; renderHomeQueue(); renderHomeWeekly(); renderTrain(); renderSheet(); renderWrong(); renderPlan(); renderAnalysis(); renderWeekly(); renderGrad(); renderCareless(); renderKids(); } @@ -1594,7 +1604,7 @@ async function submit() { else document.getElementById("qInput").focus(); return; } - let correct = null, detail = ""; + let correct = null, detail = "", unstableHint = null; if (S.demo) { if (isChoice) { correct = String(q.answer || "").toUpperCase() === val; @@ -1607,6 +1617,7 @@ async function submit() { try { const r = await api(`/api/mistakes/${q.id}/attempt`, { method: "POST", body: { child_id: S.cid, answer: val } }); correct = r.correct; detail = r.detail || ""; + unstableHint = r.unstable_hint || null; q.status_zh = r.status_zh; if (r.answer != null) q.answer = String(r.answer); if (r.judge_type) q.judge_type = r.judge_type; @@ -1626,7 +1637,13 @@ async function submit() { box.innerHTML = `这次不判
${esc(detail || "这题机器没有把握,标给家长。")}`; } else if (correct) { box.className = "result ok"; - box.innerHTML = `对了
${esc(detail || "连续两次做对,就进「讲清」。")}`; + if (unstableHint) { + // 当天错了又对:不装作过了,也不打击——说清楚「明天再来一次」 + box.className = "result mid"; + box.innerHTML = `会了,但还不稳
${esc(unstableHint)}`; + } else { + box.innerHTML = `对了
${esc(detail || "连续两次做对,就进「讲清」。")}`; + } S.results[S.idx] = true; } else { box.className = "result no"; diff --git a/report/预览-会但不稳-错题本.png b/report/预览-会但不稳-错题本.png new file mode 100644 index 0000000..0fd6ae2 Binary files /dev/null and b/report/预览-会但不稳-错题本.png differ diff --git a/report/预览-会但不稳-首页.png b/report/预览-会但不稳-首页.png new file mode 100644 index 0000000..a79dae4 Binary files /dev/null and b/report/预览-会但不稳-首页.png differ diff --git a/tests/smoke_http.py b/tests/smoke_http.py index 2f2a219..e6894dd 100644 --- a/tests/smoke_http.py +++ b/tests/smoke_http.py @@ -130,10 +130,17 @@ def main(): "text": "我先算了个位,忘了进位,所以少了十。下次先看有没有进位。"}, token) check("还没连对两次就讲清 → 409", st == 409 and d["error"]["code"] == "NOT_TO_EXPLAIN", d) - # 连对两次 → 待讲清 → 讲清通过 → 毕业 + # 当天错了又对 → 会但不稳 → 隔天再做对 → 已对 1 次 → 再隔天 → 待讲清 → 讲清毕业 mid3 = items[2]["id"] call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": "999"}, token) - call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token) + st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", + {"child_id": cid, "answer": items[2]["answer"]}, token) + check("当天错了又对 → 会但不稳", st == 200 and d["data"]["status"] == "unstable" + and d["data"]["unstable"] is True, d) + call(base, "POST", "/api/dev/advance", {"days": 1}) + st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", + {"child_id": cid, "answer": items[2]["answer"]}, token) + check("隔天做对 → 已对 1 次", st == 200 and d["data"]["status"] == "passed_once", d) call(base, "POST", "/api/dev/advance", {"days": 1}) st, d = call(base, "POST", f"/api/mistakes/{mid3}/attempt", {"child_id": cid, "answer": items[2]["answer"]}, token) diff --git a/tests/test_backend.py b/tests/test_backend.py index 06938cc..f5755b5 100644 --- a/tests/test_backend.py +++ b/tests/test_backend.py @@ -189,7 +189,12 @@ class ServiceFlowTest(unittest.TestCase): item = svc.today_queue(self.conn, gid, cid)["items"][0] svc.attempt(self.conn, gid, cid, item["id"], "999") # 错 → queued r = svc.attempt(self.conn, gid, cid, item["id"], item["answer"]) - self.assertEqual(r["status"], "passed_once") + # 当天错了又对:只算「会但不稳」,明天从头再来(不推进档位) + self.assertEqual(r["status"], "unstable") + self.assertTrue(r["unstable"]) + svc.dev_advance(self.conn, 1) # 时间快进(做题记录也一起挪) + r = svc.attempt(self.conn, gid, cid, item["id"], item["answer"]) + self.assertEqual(r["status"], "passed_once") # 隔天做对,才算连对一次 svc.dev_advance(self.conn, 1) r = svc.attempt(self.conn, gid, cid, item["id"], item["answer"]) self.assertTrue(r["need_explain"]) diff --git a/tests/test_unstable.py b/tests/test_unstable.py new file mode 100644 index 0000000..3bb22a0 --- /dev/null +++ b/tests/test_unstable.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +"""会但不稳:当天错了、当天又做对,不算连对一次。 + +背景:原来「第一次错、第二次对」直接算 stage+1。可孩子往往是看完解析 +当场再做一遍——那只证明「听完会了」,没证明「明天还记得」。这一档单列出来, +家长在周报里也能看到「X 道会但不稳」,而不是只有「已毕业 / 没懂」两个极端。 + +跑:python -m unittest tests.test_unstable -v +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from _tmpdir import workdir as _workdir # noqa: E402 + +from backend import db as dbm # noqa: E402 +from backend import scheduler # noqa: E402 +from backend import services as svc # noqa: E402 + + +def _base(**kw): + d = {"status": "queued", "stage": 0, "wrong_count": 2, "wrong_code": "E2", + "created_at": dbm.now(), "explain_fails": 0, "unstable_count": 0} + d.update(kw) + return d + + +class UnstableRuleTest(unittest.TestCase): + """纯状态机:不碰库。""" + + def test_same_day_right_does_not_advance(self): + s = scheduler.on_attempt(_base(), True, same_day_wrong=True) + self.assertEqual(s["status"], "unstable") + self.assertEqual(s["stage"], 0) # 档位一格都不前移 + self.assertEqual(s["unstable_count"], 1) + self.assertEqual(s["next_due"], dbm.add_days(1)) # 明天再来 + + def test_next_day_right_advances(self): + s = scheduler.on_attempt(_base(), True, same_day_wrong=False) + self.assertEqual(s["status"], "passed_once") + self.assertEqual(s["stage"], 1) + self.assertEqual(s["interval_days"], 1) # 3 → 7 天之间先过 1 天 + + def test_unstable_then_next_day_right_advances(self): + m = _base(status="unstable", stage=0, unstable_count=1) + s = scheduler.on_attempt(m, True, same_day_wrong=False) + self.assertEqual((s["status"], s["stage"]), ("passed_once", 1)) + + def test_unstable_then_wrong_again(self): + m = _base(status="unstable", stage=0, wrong_count=2, unstable_count=1) + s = scheduler.on_attempt(m, False, same_day_wrong=False) + self.assertEqual(s["status"], "queued") + self.assertEqual(s["wrong_count"], 3) + self.assertEqual(s["next_due"], dbm.add_days(1)) + + def test_unstable_is_due_tomorrow(self): + m = _base(status="unstable", next_due=dbm.today()) + self.assertTrue(scheduler.is_due(m)) + + def test_unstable_not_in_status_zh_missing(self): + self.assertEqual(scheduler.STATUS_ZH["unstable"], "会但不稳") + + +class UnstableServiceTest(unittest.TestCase): + """走真实入库 + 真实做题,确认当天二次做对不进档。""" + + def setUp(self): + self.tmpdir = _workdir("shared") + self.tmpdir.mkdir(exist_ok=True) + self.path = self.tmpdir / f"unstable_{id(self)}.db" + self.conn = dbm.connect(self.path) + dbm.init_db(self.conn) + self.gid = svc.login(self.conn, "demo")["guardian_id"] + svc.give_consent(self.conn, self.gid) + self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"] + + def tearDown(self): + self.conn.close() + for suffix in ("", "-wal", "-shm"): + f = Path(str(self.path) + suffix) + if f.exists(): + try: + f.unlink() + except OSError: + pass + + def _in_queue(self, stem="36 + 47 =", answer="83"): + """连错三次 → 进队列,返回 mistake_id。 + + 第 2、3 次是「同一道题又错」,走的是 updated 分支,所以从库里取 id。 + """ + for _ in range(3): + svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, answer) + row = self.conn.execute( + "SELECT * FROM mistakes WHERE child_id=? AND stem=?", (self.cid, stem)).fetchone() + self.assertEqual(row["status"], "queued") + return row["id"] + + def test_wrong_then_right_same_day_is_unstable(self): + mid = self._in_queue() + first = svc.attempt(self.conn, self.gid, self.cid, mid, "38") + self.assertFalse(first["correct"]) + second = svc.attempt(self.conn, self.gid, self.cid, mid, "83") + self.assertTrue(second["correct"]) + self.assertEqual(second["status"], "unstable") + self.assertTrue(second["unstable"]) + self.assertIn("明天", second["unstable_hint"]) + row = self.conn.execute("SELECT * FROM mistakes WHERE id=?", (mid,)).fetchone() + self.assertEqual((row["status"], row["stage"], row["unstable_count"]), ("unstable", 0, 1)) + # 明天还在队列里,不是「过了」 + self.assertTrue(scheduler.is_due(dict(row), on=dbm.add_days(1))) + + def test_right_next_day_advances(self): + mid = self._in_queue() + svc.attempt(self.conn, self.gid, self.cid, mid, "38") + # 把今天的错记到「昨天」,模拟第二天再来 + self.conn.execute("UPDATE attempts SET created_at=? WHERE mistake_id=?", + (dbm.add_days(-1) + "T20:10:00", mid)) + r = svc.attempt(self.conn, self.gid, self.cid, mid, "83") + self.assertEqual(r["status"], "passed_once") + self.assertFalse(r["unstable"]) + + def test_stats_counts_unstable(self): + mid = self._in_queue() + svc.attempt(self.conn, self.gid, self.cid, mid, "38") + svc.attempt(self.conn, self.gid, self.cid, mid, "83") + st = svc.stats(self.conn, self.gid, self.cid) + self.assertEqual(st["unstable"], 1) + self.assertEqual(st["by_status"].get("unstable"), 1) + rep = svc.weekly_report(self.conn, self.gid, self.cid) + self.assertEqual(rep["numbers"]["unstable_total"], 1) + + +if __name__ == "__main__": + unittest.main(verbosity=2) +