Compare commits

..

2 commits

Author SHA1 Message Date
1dcbfdf823 accept VK ID user identity fields 2026-08-11 13:21:20 +03:00
7575cd6dee docs: design Timeweb inspection retry 2026-08-11 13:20:24 +03:00
3 changed files with 121 additions and 5 deletions

View file

@ -149,11 +149,20 @@ async def verify_vk_access_token(access_token: str, settings: Settings) -> None:
payload = response.json() payload = response.json()
except (httpx.HTTPError, ValueError) as exc: except (httpx.HTTPError, ValueError) as exc:
raise HTTPException(status_code=401, detail="Не удалось проверить VK ID.") from exc raise HTTPException(status_code=401, detail="Не удалось проверить VK ID.") from exc
user_id = payload.get("user_id") or payload.get("user", {}).get("user_id") nested_user = payload.get("user") if isinstance(payload.get("user"), dict) else {}
try: candidate_ids = (
valid_user_id = int(user_id) == settings.vk_id_allowed_user_id payload.get("user_id"),
except (TypeError, ValueError): payload.get("id"),
valid_user_id = False payload.get("sub"),
nested_user.get("user_id"),
nested_user.get("id"),
)
valid_user_id = any(
isinstance(candidate, (int, str))
and str(candidate).isdigit()
and int(candidate) == settings.vk_id_allowed_user_id
for candidate in candidate_ids
)
if not valid_user_id: if not valid_user_id:
raise HTTPException(status_code=403, detail="Этот VK ID не имеет доступа к Дзен-ассистенту.") raise HTTPException(status_code=403, detail="Этот VK ID не имеет доступа к Дзен-ассистенту.")

View file

@ -0,0 +1,75 @@
# Timeweb Data Inspection Retry 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:** Retry only transient Timeweb `DataInspectionFailed` HTTP 400 responses within the existing bounded LLM request loop.
**Architecture:** Extend the existing `HTTPStatusError` branch in `call_llm()` with one exact provider marker. Reuse the configured attempt count and backoff; keep every other status path unchanged and cover both retry and non-retry behavior with mocked HTTP responses.
**Tech Stack:** Python 3.12, stdlib `unittest` and `unittest.mock`, HTTPX, Docker Compose, Celery, Forgejo Actions.
---
### Task 1: Add failing HTTP retry tests
**Files:**
- Create: `tests/test_worker_llm_http_retry.py`
- Test: `tests/test_worker_llm_http_retry.py`
- [ ] **Step 1: Test transient inspection rejection followed by success**
Mock `SessionLocal` to return no extra instructions, mock `httpx.Client` with a 400 response containing `DataInspectionFailed` followed by a valid completion, and mock `time.sleep`. Assert two POST calls, one `sleep(2)`, and returned completion content.
- [ ] **Step 2: Test that an unrelated 400 remains final**
Return HTTP 400 with `invalid_request_error` but without `DataInspectionFailed`. Assert one POST call, no sleep, and `RuntimeError` containing `LLM-редактор отклонил запрос с кодом 400`.
- [ ] **Step 3: Run the tests before implementation**
Run in the project Docker test image:
```bash
docker run --rm -v "$PWD:/workspace:ro" -w /workspace dzen-assistant-test:local python -m unittest tests.test_worker_llm_http_retry -v
```
Expected: the transient-inspection test errors on the first 400; the unrelated-400 test passes.
### Task 2: Implement the bounded provider-specific retry
**Files:**
- Modify: `app/worker.py:945-954`
- Test: `tests/test_worker_llm_http_retry.py`
- [ ] **Step 1: Add the exact marker branch**
Inside `except httpx.HTTPStatusError`, before the generic status handling, add:
```python
if status_code == 400 and "DataInspectionFailed" in detail:
if attempt < attempts:
time.sleep(2 * attempt)
continue
raise RuntimeError(
f"Timeweb LLM отклонил проверку входных данных после {attempts} попыток: {detail}"
) from exc
```
- [ ] **Step 2: Run focused tests and syntax checks**
Run:
```bash
docker run --rm -v "$PWD:/workspace:ro" -w /workspace dzen-assistant-test:local python -m unittest tests.test_worker_llm_http_retry tests.test_worker_llm_retry -v
docker run --rm -e PYTHONPYCACHEPREFIX=/tmp/pycache -v "$PWD:/workspace:ro" -w /workspace dzen-assistant-test:local python -m compileall -q app tests
git diff --check -- app/worker.py tests/test_worker_llm_http_retry.py
```
Expected: three tests pass; compile and diff checks exit 0.
- [ ] **Step 3: Commit, push, and verify production**
Commit only `app/worker.py` and `tests/test_worker_llm_http_retry.py`, push `main`, verify the Forgejo deployment rebuilds all app services, public `/health` returns 200, and the running worker contains the exact marker branch.
- [ ] **Step 4: Reprocess video 213 once**
Queue the current automatically selected chapters once, monitor to `drafted` or `error`, and query the resulting non-rejected articles. Do not launch another full-video retry if the bounded provider retry is exhausted.

View file

@ -0,0 +1,32 @@
# Timeweb Data Inspection Retry Design
## Context
After the malformed-JSON retry fix reached production, video `#213` passed JSON parsing and processed several chapters. Timeweb then intermittently returned HTTP 400 with `InternalError.Algo.DataInspectionFailed`. The same chapter was accepted in one run and rejected in another, so this provider response is transient in practice. The current HTTP client treats every 4xx response as final and aborts the whole multi-chapter transaction immediately.
## Design
- Recognize only HTTP 400 responses whose body contains the exact marker `DataInspectionFailed`.
- Retry those responses inside the existing `call_llm()` loop using `settings.llm_retry_attempts` and the existing `2 * attempt` backoff.
- Preserve immediate failure for every other 4xx response.
- Preserve the existing handling of transport errors and 5xx responses.
- After the configured attempts are exhausted, raise a specific runtime error that states Timeweb rejected input inspection after all attempts.
## Testing
Use isolated stdlib `unittest` mocks for `httpx.Client`, `SessionLocal`, and `time.sleep`:
1. A `DataInspectionFailed` response followed by a valid completion performs two requests, sleeps once, and returns the completion content.
2. A different HTTP 400 response performs one request, does not sleep, and raises the existing rejection error.
No real LLM, database, or network calls are used.
## Production Verification
Deploy through Forgejo, verify public health and the code inside the running worker, then reprocess video `#213`. Completion requires at least one draft article and a terminal `drafted` status; health alone is insufficient. Do not launch repeated full-video jobs if the bounded retry is exhausted.
## Non-goals
- Do not weaken or bypass Timeweb moderation.
- Do not retry arbitrary HTTP 400 responses.
- Do not change transcript text, prompts, article quality rules, or frame lifecycle.