{"record":{"id":"6f5b149f722d1074","repo":"odysseus-dev/odysseus","slug":"ai-tidy-failed-e","errorCode":null,"errorMessage":"AI tidy failed: {e}","messagePattern":"AI tidy failed: (.+?)","errorType":"http","errorClass":"HTTPException","httpStatus":500,"severity":"error","filePath":"routes/document/document_routes.py","lineNumber":1059,"sourceCode":"                    db.delete(doc)\n                    deleted += 1\n                else:\n                    doc.tidy_verdict = \"keep\"\n                reviewed += 1\n\n            db.commit()\n            return {\n                \"deleted\": deleted,\n                \"reviewed\": reviewed,\n                \"remaining\": len(to_review) - len(batch),\n                \"message\": f\"Reviewed {reviewed}, removed {deleted} junk document{'s' if deleted != 1 else ''}\",\n            }\n        except HTTPException:\n            raise\n        except Exception as e:\n            db.rollback()\n            logger.error(f\"AI tidy failed: {e}\")\n            raise HTTPException(500, f\"AI tidy failed: {e}\")\n        finally:\n            db.close()\n\n    # ---- POST /api/document/{doc_id}/export-pdf/preview ----\n    @router.post(\"/api/document/{doc_id}/export-pdf/preview\")\n    async def export_pdf_preview(doc_id: str, request: Request) -> Dict[str, Any]:\n        \"\"\"Return the field-value mapping that would be written to the PDF.\n\n        Frontend shows this in a confirmation modal so the user can spot/fix\n        any wrong values before triggering the actual download.\n        \"\"\"\n        from src.pdf_form_doc import find_source_upload_id, parse_markdown_to_values, load_field_sidecar\n\n        user = get_current_user(request)\n        db = SessionLocal()\n        try:\n            doc = db.query(Document).filter(Document.id == doc_id).first()\n            if not doc:","sourceCodeStart":1041,"sourceCodeEnd":1077,"githubUrl":"https://github.com/odysseus-dev/odysseus/blob/f9235ebbf13f693a6fd29ce70b097f6ec83705bf/routes/document/document_routes.py#L1041-L1077","documentation":"The catch-all 500 handler for POST /api/documents/ai-tidy. Non-HTTPException errors during candidate selection, LLM calls, verdict parsing, or the delete/commit phase are rolled back, logged as 'AI tidy failed: {e}', and surfaced as HTTPException(500, f\"AI tidy failed: {e}\"). Note HTTPExceptions (like the invalid-response error) are re-raised unchanged; this handler covers everything else, including network failures to the LLM endpoint.","triggerScenarios":"llm_call_async raising on connection timeout (30s limit) or auth failure; JSON parse errors if the extracted bracket text is not valid JSON; DB lock during the commit that deletes junk docs.","commonSituations":"LLM provider unreachable from the server (egress blocked, wrong URL); expired API key headers; slow provider exceeding the 30-second timeout on a large batch.","solutions":["Read the '{e}' detail — timeout errors point at the provider, JSONDecodeError at the model output, lock errors at the DB.","Verify the endpoint URL and headers returned by resolve_task_endpoint actually work (curl the provider).","Shrink the batch to keep the LLM call under the 30s timeout.","Retry later; verdicts are cached, so completed batches are skipped on the next run."],"exampleFix":"# before\nresp = requests.post(f\"{base}/api/documents/ai-tidy\", timeout=120)\nresp.raise_for_status()\n\n# after\nfor attempt in range(3):\n    resp = requests.post(f\"{base}/api/documents/ai-tidy\", timeout=120)\n    if resp.status_code != 500: break\n    time.sleep(2 ** attempt)  # transient LLM/DB failures; cached verdicts make retry cheap","handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    r = requests.post(f\"{base}/api/documents/ai-tidy\", timeout=120)\nexcept requests.HTTPError as e:\n    detail = e.response.json().get(\"detail\", \"\")\n    if e.response.status_code == 500 and (\"timeout\" in detail or \"connection\" in detail):\n        time.sleep(5); r = retry_ai_tidy()  # cached verdicts make retries cheap\n    else:\n        raise","preventionTips":["Verify the LLM endpoint URL and auth headers before scheduling ai-tidy.","Keep batches under the 30s LLM timeout.","Rely on verdict caching — interrupted runs resume where they left off."],"tags":["fastapi","llm","http-500","retry","maintenance"],"backgroundTag":null,"analyzedSha":"f9235ebbf13f693a6fd29ce70b097f6ec83705bf","analyzedAt":"2026-08-14T21:47:48.359Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}