FACTORY_OUTCOME: COMPLETED
Итог: реализовано долговечное сохранение результата и повторная финализация без повторного запуска исполнителя; подготовлено к независимому Claude review.
Проблемы: держатель SQLite lock в execution 343 не доказан; исходные exit code/baseline утрачены; 13 прежних legacy-исключений остаются.
Решение: передать исправление на независимое ревью; оставить PARKED, не разрешать этим отчётом миграцию, перезапуск или деплой.
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.
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):
BEGIN IMMEDIATE preceded durable outcome publication; lock failure could discard them while leaving RUNNING.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.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.
| 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/<SHA256-of-resolved-DB-path-prefix>/<execution-id>.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 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.