FACTORY_OUTCOME: COMPLETED ## Сводка для владельца Итог: реализовано долговечное сохранение результата и повторная финализация без повторного запуска исполнителя; подготовлено к независимому Claude review. Проблемы: держатель SQLite lock в execution 343 не доказан; исходные exit code/baseline утрачены; 13 прежних legacy-исключений остаются. Решение: передать исправление на независимое ревью; оставить PARKED, не разрешать этим отчётом миграцию, перезапуск или деплой. # Dispatcher recovery fix — 2026-11-29 Scope: FACTORY-RUNTIME only. Read `docs/operating-model/02-security.md`, `docs/task-execution/Task-Execution-Runbook.md`, runtime documentation, R1 recheck and incident task 253/execution 343. No production DB writes, migration, restart, deployment, real CLI tests, outreach, Coral or paused L-IT work. Tests use temporary SQLite databases/artifact roots and fake executors. No automatic-review switch was changed. This is implementation evidence for independent review, not independent acceptance or activation. ## Incident and causality `recovery-evidence/incident-readonly.json` is a fresh, narrowly selected `mode=ro` query of the production record. Execution 343 is COMPLETED with `recovery_action=OPERATOR_RECOVERY`, `exit_code=NULL`, start 08:40:44 and completion 08:45:33 (+02:00). `OPERATOR_RESULT_RECOVERED` explicitly records an unrecovered exit code and a reconstructed baseline because the original in-memory snapshot was lost. R1 recheck separately verified the final session message/hash. This fix does not rewrite that history or claim that reconstructed baseline is original evidence. Proven from pre-change source (retained in `recovery-evidence/*.before.py`): - Executor return, original baseline and verification were local variables. The first finalization `BEGIN IMMEDIATE` preceded durable outcome publication; lock failure could discard them while leaving RUNNING. - There was no finalization retry or replay guard. Startup recovery ran once and skipped attempts started after process startup; a failed finalization in a surviving process could remain RUNNING indefinitely. - `connect()` returned an ordinary `sqlite3.Connection`. Its context manager commits/rolls back but does not close. Dispatcher preparation reused `db` and retained the last connection variable across executor execution. Deterministic close was absent; an open connection alone does **not** prove an active lock. - Fake-executor crash injection and real temporary SQLite contention reproduce the recoverability failure windows and exercise the fix. They do not identify the historical lock holder. Unproven hypotheses for incident 343: another writer's long transaction, a retained reader/cursor delaying commit, or overlapping service activity. Available records contain no lock-owner trace or failing-statement stack. No claim is made that connection retention caused that particular lock, or that every lock can be eliminated by closing connections. Filesystem/artifact work inside finalization can still lengthen a write transaction. The compatibility run exposed a concrete read after the connection context in `project_context()`; fixing it confirms prior reliance on non-closing contexts, but still does not identify the incident lock holder. ## Implementation | File | Change | |---|---| | `control_plane/db.py` | Connection subclass closes after context exit on commit, rollback and commit failure. Explicit non-context callers still own `close()`. No schema change. | | `control_plane/outcome_journal.py` | Database-path-scoped journal; original baseline before launch; returned result and prepared outcome; SHA-256 envelope; file fsync + atomic rename + directory fsync; durable directory creation; task flock; bounded BUSY/LOCKED transaction retry. | | `dispatcher/control_plane_dispatcher.py` | Worker fence before claim; save outcome before DB finalization; replayable finalizer with execution identity/status and R1 guards; poll/startup recovery; duplicate replay no-op. | | `control_plane/recovery.py` | Single-execution orphan recovery; R1 exclusion; incomplete/corrupt evidence → INTERRUPTED/unknown exit/REVIEW, without automatic executor repeat. | | `control_plane/service.py` | Accepted-result artifact reads moved inside the connection context; fixes the legacy use-after-context exposed by deterministic close. | | `control_plane/runtime.py` | Failure recovery only updates task fields while task remains RUNNING; owner overrides retain retry fields and timestamps as well as status/result/notes. | | `control_plane/tests/test_outcome_recovery.py` | Temporary-DB/fake-executor durability, contention, crash, process/thread concurrency, retry, dependency, owner and R1 regressions. | | Existing runtime/runbook docs | Persistence ordering, recovery policy, operational boundaries and historical incident limitations. | Journal path: `data/artifacts/outcomes//.json`. A prepared journal includes the task identity/contract, original `before` snapshot, raw executor return, normalized output/error/exit status, verification evidence, failure classification, completion time and round-log metadata. Each stage is a complete atomic replacement, never an in-place partial JSON update. No executor or verification command is rerun during prepared replay. Registration still validates deliverable hashes; changed/missing deliverables fail closed under existing policy. The DB transaction publishes artifacts, execution state, task transition, retry decision and events together. It first requires matching execution/task/attempt/executor and RUNNING; already-finalized attempts are a no-op. Four whole-transaction attempts only for SQLITE_BUSY/SQLITE_LOCKED, with 50/100/200 ms delays and the existing 5-second busy timeout (roughly 20.35 seconds of lock waiting worst case, excluding actual I/O). Each failure rolls back/closes before another connection is opened. Exhaustion leaves the journal for a later poll. Non-lock errors propagate without blind retries. Every ordinary dispatcher poll performs recovery before dependency preparation. A worker holds its task flock from before claim through finalization. Recovery acquires it nonblocking; busy workers are skipped. Startup uses the same replay path; the one-shot compatibility API remains, but polling no longer depends on its flag or timestamp inference. Terminal execution CAS/transaction serialization prevents duplicate artifacts/events and attempt consumption. Active R1-managed tasks and cycle-bound executions are left for R3, not passed through legacy recovery. Existing checkpoint acceptance/dependency gates, approval checks, fallback and retry budgets remain. Missing/incomplete/corrupt journal evidence never becomes success: an existing journal without a valid prepared outcome parks for owner review. A legacy attempt without any journal follows existing bounded PROCESS_CRASH policy. An executor cannot have started in the new claim→first-journal gap; missing journals after external deletion are outside that inference. ## Commands and evidence Commands were run from `/home/iovon/ai-factory` with `.venv/bin/python`. The read-only incident script uses `sqlite3.connect('file:/home/iovon/ai-factory/data/factory.db?mode=ro', uri=True)` and SELECT only. Source hashes and implementation diff are in `recovery-evidence/source-sha256.json` and `implementation.diff`; no Git repository is available, so no historical Git diff is claimed. | Command | Evidence/result | |---|---| | `.venv/bin/python -m pytest -q control_plane/tests/test_outcome_recovery.py control_plane/tests/test_control_plane_dispatcher.py::RecoveryTests control_plane/tests/test_runtime.py::RuntimeTests::test_checkpoint_gates_only_its_branch_until_owner_accepts` | **25 passed, 4 subtests**, 94.51 s; `recovery-evidence/verified-regressions.log`. Final code, including service lifecycle fix and rollback-journal commit-failure fixture. | | `.venv/bin/python -m pytest -q control_plane/tests/test_review_cycles_r1.py control_plane/tests/test_runtime.py::RuntimeTests::test_migration_is_additive_and_repeatable` | **51 passed, 3 subtests**, 2 FastAPI deprecation warnings, 191.89 s; `r1-final.log`. R1/temporary migration compatibility; run before the subsequent service read-lifetime fix. R1 implementation was not changed. | | `.venv/bin/python data/project_materials/FACTORY-RUNTIME/review/r1-evidence/legacy_probe.py` | **56 passed, 13 deselected, 15 subtests**, 2 FastAPI deprecation warnings, 164.02 s; `recovery-evidence/legacy-verified.log`. Final code; unchanged historical exclusion list. | | `.venv/bin/python -m py_compile control_plane/db.py control_plane/service.py control_plane/runtime.py control_plane/recovery.py control_plane/outcome_journal.py dispatcher/control_plane_dispatcher.py` | Exit 0. | The final 17 new outcome tests cover: complete original baseline/raw result/evidence; crash before finalization; failure midway through the transaction with rollback; duplicate replay after commit; real SQLite writer contention (exhaustion and later release); bounded retry and non-lock refusal; failed commit closes/rolls back; atomic replace failure retains the previous journal; claimed/baseline/returned/corrupt stages never invent success; incomplete prepared evidence parks; live worker versus polling and duplicate claim; concurrent replayers; abrupt child-process death releases flock; failure replay preserves retry time/attempt count; checkpoint dependents remain blocked; owner override; R1 managed-task exclusion; startup replay/fencing. The child executes only test flock coordination and `os._exit`, not any executor CLI. Earlier runs are retained rather than hidden: the original dispatcher plus first eight recovery tests passed **41 tests / 8 subtests** (`recovery-final.log`); expanded recovery tests passed **16 / 4 subtests** (`outcome-final.log`). These preceded the last service/commit-fixture fix. The first legacy probe found **1 failed / 55 passed / 13 deselected** (`legacy-final.log`): accepted project context used a connection after its context ended; this was fixed in `service.py`, not excluded. A targeted intermediate run found **1 failed / 23 passed** (`final-regressions.log`): the new commit-lock fixture had WAL enabled, so commit correctly did not block; explicitly using DELETE journal mode makes that check meaningful. The earliest two partial logs (`dispatcher-tests.log`, `outcome-tests.log`) were interrupted after a refactor typo (`payload["stat"]` instead of `log.finalized()` before payload preparation), then corrected; no success is claimed for those interrupted runs. The unversioned `python` executable was unavailable; actual patch/testing commands used `.venv/bin/python`. The previously listed **13 legacy exclusions** are unchanged, not new exclusions and not claimed fixed. Their earlier attribution remains limited: they reproduce without the R1 hooks and are consistent with existing executor/UI expectation debt; this task does not prove historical provenance or equate them with the old “12 tests” note. No unsafe real-CLI adapter tests were included. R1 route checks are direct handler tests, not running-server HTTP tests. ## Limitations and review focus - Single-host Linux flock and local filesystem fsync/rename semantics. No distributed lease, fencing token at external providers, or exactly-once external side-effect guarantee. A crash after external action but before returned-result persistence cannot prove completion; incomplete journals require owner review. - Do not replace/delete lock files or move DB/artifact roots while workers run. Journals are retained; no automatic GC was added. Checksums detect corruption, not malicious same-user edits. Existing logical-isolation limitations remain. - Recovery covers dispatcher-owned workers using the fence. Legacy standalone callers of the low-level interruption helper must still provide transaction/worker exclusion. Mixed old/new dispatcher versions and production activation were not exercised; activation must occur separately in an authorized idle window. - Crash windows are fault-injected at persistence/transaction boundaries; abrupt child-process exit verifies kernel lock release. No machine power-cut or production load test was performed. No real model/CLI/E2E claim. - R1 remains PARKED. R2/R3/R4 work and previously recorded legacy exclusions are not resolved by this fix. Independent Claude review remains required.