FACTORY_OUTCOME: COMPLETED ## Сводка для владельца Итог: независимое ревью задачи 255 — вердикт FAIL для активации (не для идеи). Основная логика (журнал исхода, retry при lock, replay без повторного запуска, fence, R1-исключение) подтверждена кодом и тестами; все целевые, R1 и legacy-регрессии на финальном коде проходят (25/25, 51/51, 56/56 при 13 прежних исключениях). Проблемы: (1) любая постоянная ошибка финализации, не связанная с lock (повреждённый/несовпадающий журнал, сбой записи артефакта), роняет каждый poll и полностью блокирует диспетчер — воспроизведено; (2) при смешанных версиях новый диспетчер прерывает живую задачу старого диспетчера (нет журнала) и ставит её на повтор — дубль запуска, воспроизведено; (3) в полном прогоне 15 падений вместо 13, два лишних (test_executor_policy) вне заявленного списка, но не вызваны этим исправлением; (4) причина lock в execution 343 по-прежнему не доказана. Решение: не разрешать миграцию/перезапуск/деплой до исправления п.1 и п.2 (или принять риск п.2 только с остановкой старых диспетчеров и пустой очередью RUNNING); R1 оставить PARKED; решить, считать ли 2 падения executor_policy новым техдолгом. # Dispatcher recovery review — task 255 (2026-11-29) Reviewer: independent (Claude). Scope: review of `review/dispatcher-recovery-fix.md` against incident 253/execution 343, `docs/operating-model/02-security.md` and `Task-Execution-Runbook.md` (§8). No code edits, no production writes, no migration/restart/deployment, no real CLI. All probes and tests used temporary SQLite DBs and fake executors; probe scripts are in `/tmp/rev/`, not in the repo. ## Verdict **FAIL for rollout/activation as it stands. Core design: verified. Two reproduced blockers (B1, B2), plus non-blocking findings.** No git repository exists (`not a git repository`), so no VCS diff was possible; the review used the retained `*.before.py` files and `implementation.diff`. ## Integrity of evidence - SHA-256 of all 7 source files and 2 docs match `recovery-evidence/source-sha256.json` exactly (dispatcher `dc31ac09…`, db `fcb01880…`, recovery `76bd8f32…`, runtime `4272ea72…`, service `10d1335f…`, outcome_journal `ba0635c1…`, tests `1408798d…`, docs `85327967…`/`d4a96eae…`). The code under review is the code that was reported. - `runtime.py` diff vs `runtime.before.py`: one line, `UPDATE tasks … WHERE id=? AND status='RUNNING'` (preserves owner override). `service.py` diff: accepted-result artifact read moved inside the connection context. Both as described. - Incident record `incident-readonly.json`: execution 343 COMPLETED, `OPERATOR_RECOVERY`, `exit_code=NULL`, event states baseline reconstructed / exit code not recovered. The report states this honestly; it does not claim the lock holder was found. Agreed: the root cause of the 343 lock is **unproven**; the fix is a recoverability fix, not a lock-cause fix. - Honest disclosure verified: intermediate failing logs (`final-regressions.log`, `legacy-final.log`) are retained and explained. `outcome-tests.log`/`dispatcher-tests.log` are interrupted stubs, not claimed as passes. - Production not touched by this review: `data/factory.db` SHA-256 `0230716708…beac8` unchanged before/after; artifact file count 804 unchanged; `data/artifacts/outcomes/` does not exist (journal has never been activated in production). ## Independent test results (final code, temp DBs) | Run | Result | |---|---| | `test_outcome_recovery.py` + `RecoveryTests` + checkpoint-branch test | **25 passed**, 4 subtests (111 s) | | `test_review_cycles_r1.py` + migration additive test (R1) | **51 passed**, 3 subtests (200 s) | | `r1-evidence/legacy_probe.py` (legacy, 13 deselected) | **56 passed**, 13 deselected, 15 subtests (241 s) | | Full `control_plane/tests` | 210 passed, **15 failed**, 76 subtests (580 s) | Full-suite failures: the 13 documented legacy nodes (set equal to `legacy-known-failures.json`, none missing) **plus 2 not on that list**: `test_executor_policy.py::test_creation_forms_and_visible_roadmap` (`None != 'nemotron'`) and `::test_inline_javascript_persists_then_refreshes_and_reports_failure` (UI text expectation). Re-run with `ClosingConnection.__exit__` reverted to the stock sqlite behaviour they fail identically (2 failed / 12 passed), so they are **not caused by the connection change**; they are config/UI expectation debt outside the probe's 5-file scope, and the fix report's "13 exclusions" understates the repo-wide failure count. Whether they pre-date the whole change set cannot be proven without VCS. ## Requirement-by-requirement findings **Durable journal — OK.** `outcome_journal.save`: temp file in same dir → write → `fsync` → `os.replace` → directory `fsync`; SHA-256 envelope; stages claimed → baseline → returned → prepared, each a whole-file replacement. Original baseline is saved before executor launch; raw result before verification. `read()` validates checksum, eid/version, required keys, success-requires-exit 0 + passing evidence + baseline. Path is scoped by hash of resolved DB path. Corrupt/partial/non-prepared journals → `INTERRUPTED`, unknown exit, `EVIDENCE_MISSING`/REVIEW, never success (tested: deleted-journal and corrupt cases; my probe confirmed non-serialisable result → journal stuck at `baseline` → REVIEW after poll, fail-closed). **Lock retry — OK with caveat.** `journal.retry` retries whole transactions only for BUSY/LOCKED (`sqlite_errorcode & 255`, Python ≥3.11 attribute; venv is 3.12), 50/100/200 ms, 4 tries, each on a fresh closed connection; non-lock errors propagate. Caveat B1: exhaustion/propagation raises out of `poll_recovery` and aborts the whole cycle. **Replay CAS — OK.** `finalize` does `BEGIN IMMEDIATE`, requires execution RUNNING and (task, attempt, executor) identity, returns False on already-finalized (duplicate replay no-op, tested), refuses R1 cycle executions. Executor/verification are not re-run on prepared replay (`load_executor` patched to assert in tests). **Crash gaps.** claim→first journal: executor cannot have started, legacy bounded PROCESS_CRASH retry applies — sound. baseline/returned stage crash → REVIEW, no auto-repeat (sound, conservative). prepared→DB: replay. DB-commit failure: rollback+close, journal retained. Journal externally deleted after `prepared` → silently treated as no-journal and the task is **re-executed** (probe: INTERRUPTED/RETRY/READY). Documented as out of scope; acceptable but note artifacts-root hygiene is now a correctness dependency (no GC exists, grep confirmed none). **Worker fencing — OK for same-version.** `fence()` = non-blocking `flock` per task from before claim to finalization; recovery skips busy tasks (`live_worker`); child-process death releases lock (tested). TOCTOU between listing RUNNING rows and taking the fence is harmless (finalize/interrupt both re-check RUNNING). Single host only — as disclosed. **Owner/dependency/retry semantics — OK.** `record_recovery` now updates the task only while RUNNING; completion of a task the owner already moved yields `OWNER_OVERRIDE` (retry fields untouched); checkpoint dependents stay blocked (test passes incl. the previously failing checkpoint test); attempts remain monotonic and bounded by `MAX_ATTEMPTS`; `FACTORY_OUTCOME: OWNER_CHECKPOINT` handling preserved. **R1 exclusion — OK.** `claim`, `finalize` and `recover_interrupted` all skip cycle-bound/R1-managed executions (`cycle_id` not NULL or managed state). Side effect: such a RUNNING execution is never recovered by the legacy path and is left to R3 (documented). R1 suite 51/51 on final code (the report's own R1 run predated the service fix; this re-run is on final code). **Connection lifetime callers — OK.** `ClosingConnection.__exit__` closes after commit/rollback/commit failure. AST scan of every non-test `with connect() as X` in `control_plane`, `console`, `dispatcher`, `executors`, `providers`: all later uses of the same name are re-bound by a subsequent `with` or are `sqlite3.Row` objects (valid after close); no use-after-close found, and no bare `x = connect()` assignments exist. The one real instance (`project_context`) was already fixed. The 2 console tests above fail identically without the closing change. Note: closing is hygiene; it does not demonstrate the 343 lock cause. **Docs.** FACTORY_RUNTIME.md and Runbook §8 describe journal path, ordering, retry, replay, corruption policy, "pending activation, PARKED". They do **not** mention mixed-version rollout or a drain procedure (B2). ## Blockers **B1 — a persistent non-lock finalization error wedges the entire dispatcher (reproduced).** `poll_recovery` catches only journal *read* errors. `finalize()` errors (identity mismatch `ValueError`, "Successful outcome lacks…", `RuntimeError("Cannot finalize without durable verification evidence")` on artifact write failure/disk full, lock exhaustion) propagate out of `poll_recovery`, which `cycle()` calls *before* `prepare_dependencies`/claim. Probe: one RUNNING execution with a prepared journal, `write_artifact` failing → `cycle()` raises every time; a second healthy READY task stays READY indefinitely (`TASK-001 RUNNING, T2 READY` after two cycles). Re-save of a valid-checksum journal with wrong executor name also raises out of `poll_recovery` and blocks recovery of all later rows. This reintroduces the starvation class the project fixed earlier. Required fix: isolate failures per execution in `poll_recovery` (catch, log event, continue; park the attempt in REVIEW after N non-lock failures), and make `cycle()` not abort claim/dispatch on a recovery error. **B2 — mixed-version rollout interrupts live old-version work (reproduced).** An attempt claimed by an old dispatcher has no journal and holds no flock. New `poll_recovery` treats every RUNNING execution without a journal as an orphan: probe shows `INTERRUPTED / RETRY`, task → READY immediately while the old worker is still running → duplicate execution/side effects; the old worker's later write then races the new attempt. The old `startup_recovery` timestamp guard (`not_before`) was removed from the poll path. Conversely an old dispatcher restarting can interrupt a new worker's RUNNING row, and the new worker's prepared journal then replays as a no-op (result lost). Requirement before activation: documented drain — stop all old dispatcher/supervisor processes, confirm zero RUNNING executions (read-only query), then start new version; or add an age/heartbeat guard for journal-less RUNNING rows. This must be in the runbook. ## Non-blocking findings 1. Two additional repo failures (`test_executor_policy`) are outside the declared "13" list; the report should state repo-wide failures honestly (15, not caused by this change). 2. A non-JSON-serialisable executor result makes `run_one` raise after the executor ran; result lost, attempt goes to REVIEW (fail-closed, but also aborts that cycle's `as_completed` loop). 3. Worst-case lock wait ≈ 20 s per replay inside the poll; with several stuck journals every poll is slow (poll is single-threaded before dispatch). 4. Journal retention/GC absent; checksum does not protect against same-user tampering; the journal stores full output (sensitivity: same as existing artifacts, but note in the security doc). 5. Tests use fault injection, not machine power loss or production load; `flock` semantics are single-host/local FS (disclosed). 343's lock holder remains unknown — closing connections is not claimed to prevent it, and I agree. 6. R1 route tests are direct handlers, not live HTTP (pre-existing). ## Rollout limitations / conditions for next task - Keep **PARKED**; this review does not authorize migration, restart or deployment. No schema migration is involved, but code activation requires an authorized idle window with a drain (B2). - Fix B1 and B2, add regression tests (poison journal does not block other tasks; journal-less RUNNING row of a live old worker is not requeued during rollout), then repeat this offline suite and re-hash sources. - Update the runbook with the drain procedure, retention policy for `data/artifacts/outcomes/`, and the operator action for a journal parked in REVIEW. - Real-CLI/E2E, power-loss and multi-host behaviour remain unverified.