diff --git a/dzen-assistant/docs/superpowers/plans/2026-08-11-llm-json-retry.md b/dzen-assistant/docs/superpowers/plans/2026-08-11-llm-json-retry.md new file mode 100644 index 0000000..48e1bcb --- /dev/null +++ b/dzen-assistant/docs/superpowers/plans/2026-08-11-llm-json-retry.md @@ -0,0 +1,215 @@ +# LLM JSON Retry Fix Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make malformed LLM JSON enter the existing three-attempt quality retry loop instead of failing after the first response. + +**Architecture:** Keep the current article-generation pipeline and exception types. Expand the existing `try` boundary by one statement so both payload generation/parsing and article validation share the same quality-retry handler; verify the control flow with an isolated stdlib `unittest` using mocks. + +**Tech Stack:** Python 3.11+, stdlib `unittest` and `unittest.mock`, Celery worker, SQLAlchemy, Docker Compose, Forgejo Actions. + +--- + +## File Structure + +- Create `tests/__init__.py` so the focused test module can be addressed directly by `unittest`. +- Create `tests/test_worker_llm_retry.py` for deterministic retry-control-flow coverage without a real LLM or database. +- Modify `app/worker.py:693-695` only to move payload generation inside the existing exception boundary. + +### Task 1: Add a failing regression test + +**Files:** +- Create: `tests/__init__.py` +- Create: `tests/test_worker_llm_retry.py` +- Test: `tests/test_worker_llm_retry.py` + +- [ ] **Step 1: Create the test package marker** + +Create an empty `tests/__init__.py`. + +- [ ] **Step 2: Write the retry regression test** + +Create `tests/test_worker_llm_retry.py` with: + +```python +import unittest +from unittest.mock import call, patch + +from app.models import Video +from app.worker import generate_articles_with_quality_retries + + +class GenerateArticlesWithQualityRetriesTest(unittest.TestCase): + @patch("app.worker.append_progress") + @patch("app.worker.articles_from_payload") + @patch("app.worker.generate_article_payload") + def test_retries_invalid_json_and_passes_feedback( + self, + generate_article_payload_mock, + articles_from_payload_mock, + append_progress_mock, + ): + error = "LLM вернул невалидный JSON: Expecting ',' delimiter в строке 11, колонке 17." + valid_payload = {"articles": [{"title": "Готовая статья"}]} + expected_articles = [object()] + generate_article_payload_mock.side_effect = [RuntimeError(error), valid_payload] + articles_from_payload_mock.return_value = expected_articles + video = Video(id=213, title="Тест", description="", external_id="test", source_url="") + + result = generate_articles_with_quality_retries(video, "Текст", []) + + self.assertEqual(result, expected_articles) + self.assertEqual(generate_article_payload_mock.call_count, 2) + self.assertEqual( + generate_article_payload_mock.call_args_list, + [ + call(video, "Текст", chapter=None, quality_feedback=""), + call(video, "Текст", chapter=None, quality_feedback=error), + ], + ) + append_progress_mock.assert_called_once() + articles_from_payload_mock.assert_called_once_with(video, valid_payload, []) + + +if __name__ == "__main__": + unittest.main() +``` + +- [ ] **Step 3: Run the test and verify the current bug** + +Run: + +```bash +python -m unittest tests.test_worker_llm_retry -v +``` + +Expected: `ERROR`; the first `RuntimeError` escapes from `generate_article_payload()` and `generate_article_payload_mock.call_count` never reaches two. + +### Task 2: Move payload generation into the retry boundary + +**Files:** +- Modify: `app/worker.py:693-695` +- Test: `tests/test_worker_llm_retry.py` + +- [ ] **Step 1: Apply the minimal control-flow change** + +Change the loop body from: + +```python + payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback) + try: + articles = articles_from_payload(video, payload, frames) +``` + +to: + +```python + try: + payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback) + articles = articles_from_payload(video, payload, frames) +``` + +- [ ] **Step 2: Run the focused test** + +Run: + +```bash +python -m unittest tests.test_worker_llm_retry -v +``` + +Expected: one test passes and output ends with `OK`. + +- [ ] **Step 3: Run syntax and diff checks** + +Run: + +```bash +python -m compileall -q app tests +git diff --check -- app/worker.py tests +``` + +Expected: both commands exit with status 0 and print no errors. + +- [ ] **Step 4: Commit only implementation files** + +Run: + +```bash +git add app/worker.py tests/__init__.py tests/test_worker_llm_retry.py +git commit -m "fix: retry malformed LLM JSON responses" +``` + +Expected: the commit contains exactly the worker change and two test files; unrelated passkey/admin work remains unstaged. + +### Task 3: Push and verify the Forgejo deployment + +**Files:** +- No additional file changes. + +- [ ] **Step 1: Push `main`** + +Run: + +```bash +git push origin main +``` + +Expected: Forgejo accepts the new implementation commit on `main`. + +- [ ] **Step 2: Wait for the workflow and verify public health** + +Poll the Forgejo workflow until it completes, then run: + +```bash +curl --fail --silent --show-error https://dzen.nstarikov.ru/health +``` + +Expected: HTTP success with the application's healthy response. + +- [ ] **Step 3: Verify the running worker contains the fix** + +Run: + +```bash +ssh -o BatchMode=yes nstarikov "cd /var/www/dzen.nstarikov.ru && docker compose ps && docker compose exec -T worker sed -n '685,705p' /app/app/worker.py" +``` + +Expected: `api`, `worker`, `beat`, and `redis` are running; the displayed worker code has `payload = generate_article_payload(...)` below `try:`. + +### Task 4: Reprocess production video 213 and verify the user-visible result + +**Files:** +- No source changes. + +- [ ] **Step 1: Record the production baseline** + +Run a read-only query in the worker container for video status, frame count, and non-rejected article count: + +```bash +ssh -o BatchMode=yes nstarikov 'cd /var/www/dzen.nstarikov.ru && docker compose exec -T worker python -c '\''import sqlite3; c=sqlite3.connect("/app/data/dzen.sqlite3"); print(c.execute("select status, progress_stage, error_message from videos where id=213").fetchone()); print("frames", c.execute("select count(*) from frames where video_id=213").fetchone()[0]); print("articles", c.execute("select count(*) from articles where video_id=213 and status != \\"rejected\\"").fetchone()[0])'\''' +``` + +Expected: status is currently `error`; save the printed frame/article counts for comparison. + +- [ ] **Step 2: Queue the same description-selected chapters** + +Run inside the production worker container: + +```bash +ssh -o BatchMode=yes nstarikov 'cd /var/www/dzen.nstarikov.ru && docker compose exec -T worker python -c '\''from app.chapters import chapter_to_payload, parse_video_chapters; from app.database import SessionLocal; from app.models import Video; from app.worker import process_video; s=SessionLocal(); v=s.get(Video, 213); chapters=[chapter_to_payload(c) for c in parse_video_chapters(v.description, v.duration_seconds)]; selected=[c for c in chapters if c["selected"]]; print("selected chapters", len(selected)); print("task", process_video.delay(213, selected).id); s.close()'\''' +``` + +Expected: `selected chapters 9` and a Celery task id are printed. + +- [ ] **Step 3: Monitor the real production job** + +Poll the same video row and progress log at intervals no longer than 30 seconds. Continue until status becomes `drafted` or `error`. + +Expected success: status becomes `drafted`, progress reaches 100, and the log says how many articles were created. If malformed JSON recurs, the log must show `Повторная редактура 2/3` before another model attempt; if all attempts fail, it must also show `3/3` before the final error. + +- [ ] **Step 4: Verify articles and frame-count impact** + +Run a final read-only query listing non-rejected article ids/titles/statuses and the frame count for video `213`. + +Expected: at least one non-rejected draft article exists for the selected chapters. Report the before/after frame counts explicitly because reprocessing currently appends frame records and frame lifecycle is outside this fix. +