Compare commits
25 Commits
feature/OR
...
feature/OR
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72d662ae88 | ||
|
|
348cf8c164 | ||
| bc2347abd3 | |||
| 62c1fe3461 | |||
| 0dfddf93f0 | |||
| 22d3b77426 | |||
| 4a06537afd | |||
| b6c0e11e4d | |||
| 3fb3d15cb4 | |||
| 4815e378d9 | |||
| 67e98b8296 | |||
|
|
cad5e98892 | ||
| bb03350ec9 | |||
| 930e65298c | |||
| cba67a4270 | |||
| 720c31393a | |||
| 9b7c855df3 | |||
| a6b444c356 | |||
| dbf14e3d5a | |||
| 4bebb921ff | |||
| 9f846b5a50 | |||
| b760b24a48 | |||
| f0ac9d5562 | |||
| 987ea810bf | |||
| f85e449d80 |
29
.env.example
29
.env.example
@@ -117,6 +117,35 @@ ORCH_RECONCILE_GRACE_OVERRIDES_JSON=
|
||||
ORCH_RECONCILE_NOTIFY_UNBLOCK=true
|
||||
ORCH_RECONCILE_SKIP_BLOCKED_ENABLED=true
|
||||
|
||||
# ORCH-065: job-reaper + proactive merge-lease reclaim. A background daemon thread
|
||||
# (src/job_reaper.py, started LAST in main.lifespan after requeue_running_jobs) reaps
|
||||
# zombie 'running' jobs whose monitor/process died before writing the terminal status
|
||||
# (one zombie at max_concurrency=1 blocks the whole shared queue) and periodically
|
||||
# reclaims dead/stale merge-leases. Liveness is three-tier: Tier-1 dead jobs.pid
|
||||
# (os.kill(pid,0)) after REAPER_DEAD_TICKS consecutive dead ticks (anti-false-positive
|
||||
# for a live agent); Tier-2 agent_runs.exit_code recorded but job still 'running'
|
||||
# (only after a REAPER_FINALIZE_GRACE_S finalization grace, so a live monitor still
|
||||
# doing git push / PR / Plane comments is never reaped); Tier-3 backstop after
|
||||
# REAPER_MAX_RUNNING_S. The terminal flip carries an atomic status='running' guard and
|
||||
# precedes any advance/enqueue (claim-before-act) so it never double-processes/-advances
|
||||
# a row racing a late monitor or requeue_running_jobs.
|
||||
# REAPER_ENABLED -> global kill-switch (false -> strictly prior behaviour).
|
||||
# REAPER_INTERVAL_S -> background scan period (seconds).
|
||||
# REAPER_DEAD_TICKS -> consecutive dead-pid ticks before reaping (Tier-1, >=2).
|
||||
# REAPER_MAX_RUNNING_S -> Tier-3 backstop ceiling; must exceed max agent_timeout+grace.
|
||||
# REAPER_FINALIZE_GRACE_S -> Tier-2 grace: how long agent_runs.exit_code must have been
|
||||
# recorded before a still-'running' job is reaped; MUST exceed
|
||||
# the max finalization window (git push + PR + Plane comments).
|
||||
# LEASE_RECLAIM_ENABLED -> kill-switch for the proactive stale/dead lease reclaim
|
||||
# (false -> only the legacy lazy TTL reclaim in acquire_merge_lease).
|
||||
# (reuse) ORCH_MERGE_LOCK_TIMEOUT_S -> lease TTL; ORCH_MERGE_GATE_REPOS -> reclaim scope.
|
||||
ORCH_REAPER_ENABLED=true
|
||||
ORCH_REAPER_INTERVAL_S=60
|
||||
ORCH_REAPER_DEAD_TICKS=2
|
||||
ORCH_REAPER_MAX_RUNNING_S=3600
|
||||
ORCH_REAPER_FINALIZE_GRACE_S=300
|
||||
ORCH_LEASE_RECLAIM_ENABLED=true
|
||||
|
||||
# ORCH-021: post-deploy production monitoring + degradation reaction. After the
|
||||
# terminal deploy->done transition for an applicable repo, a reserved-agent job
|
||||
# `post-deploy-monitor` (no LLM, modelled on deploy-finalizer) probes prod over a
|
||||
|
||||
@@ -91,6 +91,30 @@ The verdict contract is unchanged: `docs/work-items/<work_item_id>/14-deploy-log
|
||||
frontmatter field `deploy_status: SUCCESS|FAILED` (the gate `check_deploy_status` parses ONLY this).
|
||||
**What changed (ORCH-36): WHO and WHEN writes that verdict, for the self-hosting repo.**
|
||||
|
||||
### ⚠️ Idempotent merge guard — consult `pr_already_merged` BEFORE merging (ORCH-065)
|
||||
|
||||
The `deploy` stage can be **re-driven**: if a process/monitor thread died after the PR
|
||||
merged but before the job finalised, the job-reaper requeues it and this stage runs **again**
|
||||
(ADR-001 ORCH-065, Р-3). A blind second merge of an already-merged PR makes Gitea return a
|
||||
merge error → a false БАГ-8 rollback. To stay idempotent, **before you merge the feature
|
||||
branch PR into `main`, consult the deterministic guard** `merge_gate.pr_already_merged(repo, branch)`:
|
||||
|
||||
```bash
|
||||
# Already merged? exit 0 = yes (skip the merge), exit 1 = no (merge normally).
|
||||
python3 -c "import sys; from src.merge_gate import pr_already_merged; \
|
||||
sys.exit(0 if pr_already_merged('<repo>', '<branch>') else 1)" && MERGED=1 || MERGED=0
|
||||
```
|
||||
|
||||
- `MERGED=1` (PR already merged) → **do NOT merge again** (no second merge, no error).
|
||||
Treat the merge as already done and continue to write the deploy verdict
|
||||
(`deploy_status: SUCCESS` once the deploy itself is health-ok). This is the AC-11 no-op.
|
||||
- `MERGED=0` (not merged) → merge the PR normally, then proceed.
|
||||
|
||||
The guard is **never-raise** (any Gitea/parse error → `False` → "not known-merged", so a real
|
||||
merge is never silently skipped). This is the single consultation point ADR-001 Р-3 /
|
||||
README / CHANGELOG refer to: the **merge path (deployer/merge) consults the guard before a
|
||||
(repeat) merge**.
|
||||
|
||||
### Self-hosting repo (`orchestrator`) — you do NOT deploy yourself
|
||||
|
||||
For `orchestrator` the `deploy` stage is orchestrated by **deterministic code** in
|
||||
@@ -124,4 +148,7 @@ deploys go through `scripts/orchestrator-deploy-hook.sh` (parametrised; defaults
|
||||
|
||||
- Always write machine-readable YAML frontmatter — the quality gates parse ONLY the frontmatter fields, never the body prose.
|
||||
- Never push directly to `main`. Always use a PR or the artifact merge pattern.
|
||||
- **Idempotent merge (ORCH-065):** before any (re-)merge of a feature PR into `main`, consult
|
||||
`merge_gate.pr_already_merged(repo, branch)` (see the `deploy` stage section). Already merged
|
||||
→ no second merge, no error — the stage is a no-op on the merge and proceeds to its verdict.
|
||||
- Never modify `.env`, `.env.staging`, `docker-compose.yml`, or production infrastructure.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -38,6 +38,9 @@ created → analysis → architecture → development → review → testing →
|
||||
└──── REQUEST_CHANGES ──────┘ (откат на development, max 3)
|
||||
```
|
||||
|
||||
## Статусная модель Plane (ORCH-066) — индикация ≠ управление
|
||||
Статусы Plane — это **слой B (индикация)**, отдельный от **слоя A (машина стадий)** `src/stages.py::STAGE_TRANSITIONS`. Plane показывает наблюдателю осмысленную картину (`Backlog → Todo → Analysis → Architecture → Development → Code-Review → Testing → Awaiting Deploy → Deploying → Monitoring after Deploy → Done` + человеческие гейты `In Review/Approved`, `Confirm Deploy`), но НИКОГДА не управляет конвейером. Маппинг и сеттеры — `src/plane_sync.py` (6 новых ключей: `to_analyse/analysis/code_review/awaiting_deploy/deploying/monitoring`), с project-relative alias-fallback: на частично сконфигурированном проекте новый ключ деградирует на базовый UUID ТОГО ЖЕ проекта (нулевая регрессия для enduro-trails). Детали — `docs/architecture/README.md`.
|
||||
|
||||
## Конвенции
|
||||
- Conventional Commits (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`)
|
||||
- Ветки: `feature/ORCH-NNN-slug`, `fix/ORCH-NNN-slug`
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
- **Quality Gates** (`src/qg/checks.py`) — проверки выхода со стадии, реестр `QG_CHECKS`.
|
||||
- **Agent Launcher** (`src/agents/launcher.py`) — запуск Claude CLI агентов в изолированном git worktree, мониторинг, auto-advance.
|
||||
- **Queue** (`src/queue_worker.py`, ORCH-1) — персистентная очередь задач (SQLite `jobs`), atomic claim, max_concurrency, ретраи, restart-safe.
|
||||
- **Job-reaper** (`src/job_reaper.py`, ORCH-065 — [adr-0011](adr/adr-0011-job-reaper-lease-reclaim.md)) — фоновый daemon-поток (каркас `reconciler`), стартует/останавливается в `main.lifespan` (после `reconciler.start()` / перед `worker.stop()`). Детектирует «мёртвый» `running`-job **без рестарта** процесса (Tier-1 мёртвый `jobs.pid` после `reaper_dead_ticks` тиков; Tier-2 `agent_runs.exit_code` записан, а job ещё `running`; Tier-3 backstop `reaper_max_running_s`) и приводит строку к корректному статусу через те же контракты (`_try_advance_stage`/`_finalize_job`, gate-driven; exit≠0/неизвестно → `attempts<max`→`queued`, иначе `failed`+Telegram). Атомарный reap-claim (guard `status='running'`) совместим со стартовым `requeue_running_jobs`. Тот же поток периодически делает проактивный реклейм stale/dead merge-lease (см. ниже). never-raise; kill-switch `ORCH_REAPER_ENABLED`; снимок в `GET /queue` (блок `reaper`).
|
||||
- **Reconciler** (`src/reconciler.py`, ORCH-053 — реализовано, [adr-0007](adr/adr-0007-reconciler.md)) — фоновый daemon-поток (паттерн `queue_worker`), стартует/останавливается в `main.lifespan` (после `worker.start()` / перед `worker.stop()`). Реконсилирует рассинхрон «источник истины ≠ стадия задачи» при потерянном webhook. F-1 gate-side (продвигает застрявшую стадию по локальной БД через штатный `advance_stage(..., finished_agent=None)`), F-2 plane-side (опрос Plane API → `handle_*` из `plane.py`), F-3 (БД-fallback `sha→branch` в `handle_ci_status`). Источник истины — гейт/Plane, не событие; идемпотентность (active-job guard + atomic-claim + grace); kill-switch `ORCH_RECONCILE_ENABLED`. `analysis` F-1 не трогает (человеческий гейт). F-1 также пропускает escalated (retry≥лимита) и Blocked/Needs-Input задачи (ORCH-060). Наблюдаемость — блок `reconcile` в `GET /queue`.
|
||||
- **Project Registry** (`src/projects.py`, ORCH-6) — Plane project id → repo + prefix; фильтрация вебхуков по проекту.
|
||||
- **Plane Sync** (`src/plane_sync.py`) — синхронизация статусов/комментариев в Plane.
|
||||
@@ -190,6 +191,104 @@ never-raise на единицу работы; тишина при синхрон
|
||||
и реестры (`STAGE_TRANSITIONS`/`QG_CHECKS`) не меняются. Подробнее:
|
||||
[adr-0007](adr/adr-0007-reconciler.md), детально — `docs/work-items/ORCH-053/06-adr/ADR-001-stuck-task-reconciler.md`.
|
||||
|
||||
### Job-reaper + проактивный реклейм merge-lease (ORCH-065 — design)
|
||||
Финализация статуса job (`done`/`queued`/`failed`) выполняется ТОЛЬКО в
|
||||
`launcher._monitor_agent → _finalize_job` внутри живого процесса. Смерть
|
||||
monitor-потока/процесса между `proc.wait()` и `_finalize_job` (краш, OOM,
|
||||
self-restart во время deploy) оставляла строку `jobs` навсегда `running`; при
|
||||
`max_concurrency=1` одна зомби-строка блокирует claim всех job → встаёт конвейер
|
||||
ВСЕХ проектов (инциденты 07.06: jobs 236/239/242/254). `requeue_running_jobs()`
|
||||
спасал ТОЛЬКО на старте процесса. Симметрично залипал merge-lease (ORCH-043):
|
||||
реклейм был лениво-по-TTL и только при чужом `acquire`, liveness держателя по pid
|
||||
не проверялся. Это последняя ручная точка автономного self-deploy (блокер ORCH-54).
|
||||
ORCH-065 вводит фоновый watchdog, чтобы смерть процесса/потока на любой стадии НЕ
|
||||
оставляла навсегда захваченных ресурсов:
|
||||
- **Job-reaper** (`src/job_reaper.py`) — daemon-поток по образцу `reconciler`,
|
||||
работает **без рестарта**. Трёхуровневая liveness: Tier-1 мёртвый `jobs.pid`
|
||||
(новая колонка) после `reaper_dead_ticks` подряд тиков (анти-ложноположительность
|
||||
— живой долгий агент не реапится); Tier-2 `agent_runs.exit_code` записан, а job
|
||||
ещё `running` — но это окно неоднозначно (живой monitor пишет exit_code ПЕРВЫМ,
|
||||
затем git push/PR/Plane-комментарии), поэтому Tier-2 реапит только после
|
||||
finalization-grace `reaper_finalize_grace_s` (живой финализирующий monitor НЕ
|
||||
реапится); Tier-3 backstop по потолку `reaper_max_running_s` (> max
|
||||
agent_timeout+grace). Действие переиспользует контракты по принципу
|
||||
**claim-before-act**: для exit0 канонический QG оценивается read-only ПЕРЕД
|
||||
атомарным claim, затем claim `done` ПЕРВЫМ и только победитель claim делает
|
||||
`_try_advance_stage` (advance+enqueue) — проигравший claim (поздний monitor /
|
||||
стартовый requeue) не выполняет побочных эффектов (нет дубль-advance/-enqueue);
|
||||
источник истины — канонический QG, не факт «exit0»; гейт красный или exit≠0/
|
||||
неизвестно → `attempts<max`→`queued`, иначе `failed`+Telegram. Атомарный
|
||||
reap-claim (`UPDATE ... WHERE id=? AND status='running'`) совместим со стартовым
|
||||
`requeue_running_jobs` (restart-safe, без двойной обработки).
|
||||
- **Проактивный реклейм stale/dead lease** (функции в `merge_gate.py`:
|
||||
`pid_alive`, `reclaim_stale_lease`) — на старте (рядом с `requeue_running_jobs`)
|
||||
и периодически из тика reaper: освобождает lease, чей держатель **мёртв** (pid
|
||||
не жив) ИЛИ **просрочен** (TTL `merge_lock_timeout_s`); живой держатель в
|
||||
пределах TTL — НЕ трогать (защита легитимного merge). holder-aware, never-raise,
|
||||
условность как ORCH-43 (`merge_gate_repos`/self-hosting).
|
||||
- **Идемпотентная финализация merge** — без новой merge-логики: re-drive через
|
||||
reaper→`queued`→переисполнение стадии / reconciler; дорогие шаги не повторяются
|
||||
(`branch_is_behind_main==False`); добавлен never-raise guard `pr_already_merged`
|
||||
(читает состояние PR) — уже слит = no-op. **Консультируется самим merge-актором:**
|
||||
фактический merge PR в `main` делает агент `deployer` (в начале стадии `deploy`),
|
||||
поэтому wiring — в его промпте `.openclaw/agents/deployer.md`, который вызывает
|
||||
`pr_already_merged` ПЕРЕД любым (повторным) merge (AC-11). Чек `check_branch_mergeable`
|
||||
НЕ меняется (AC-13): он на ПЕРВОМ ребре `deploy-staging → deploy`, а риск второго
|
||||
merge — на re-drive самой стадии `deploy`.
|
||||
- **Схема БД:** единственное изменение — `jobs.pid INTEGER` через идемпотентный
|
||||
`_ensure_column` (live-safe). `STAGE_TRANSITIONS`, `QG_CHECKS`, `check_*`, БАГ-8,
|
||||
exit-коды хука, файл-схема lease — без изменений.
|
||||
- **Наблюдаемость:** блок `reaper` в `GET /queue` (enabled, interval, last_run_ts,
|
||||
reaped_total, last_reaped, lease_reclaimed_total); каждый reap/lease-reclaim →
|
||||
`logger.warning`; reap→`failed` и lease-reclaim → Telegram.
|
||||
- **Kill-switch'и:** `ORCH_REAPER_ENABLED`, `ORCH_REAPER_INTERVAL_S`,
|
||||
`ORCH_REAPER_DEAD_TICKS`, `ORCH_REAPER_MAX_RUNNING_S`,
|
||||
`ORCH_REAPER_FINALIZE_GRACE_S`, `ORCH_LEASE_RECLAIM_ENABLED`; `false` → строго
|
||||
прежнее поведение.
|
||||
|
||||
Подробнее: [adr-0011](adr/adr-0011-job-reaper-lease-reclaim.md), детально —
|
||||
`docs/work-items/ORCH-065/06-adr/ADR-001-job-reaper-and-lease-reclaim.md`.
|
||||
|
||||
### Осмысленная статусная модель Plane (ORCH-066 — реализовано)
|
||||
Plane-доска была семантически перегружена: `In Progress` означал «человек запускает
|
||||
конвейер», «идёт анализ», «идёт прод-деплой» и «возврат из Needs Input» одновременно.
|
||||
ORCH-066 наводит порядок по утверждённой Owner модели, меняя **только слой B**
|
||||
(Plane-индикация: `src/plane_sync.py` + точки простановки в `src/stage_engine.py`/
|
||||
`src/webhooks/plane.py`/`src/reconciler.py`) и **не трогая слой A** (`STAGE_TRANSITIONS`,
|
||||
инвариант). Статус — индикация, не управление (вердикты по-прежнему из YAML-frontmatter):
|
||||
```
|
||||
Backlog → Todo → [To Analyse] → Analysis → [In Review → Approved] → Architecture →
|
||||
Development → Code-Review → Testing → Awaiting Deploy → [Confirm Deploy] → Deploying →
|
||||
Monitoring after Deploy → Done
|
||||
```
|
||||
`[...]` = человеческий вход-триггер; остальное ставит орк.
|
||||
- **6 новых логических ключей** (`to_analyse`/`analysis`/`code_review`/`awaiting_deploy`/
|
||||
`deploying`/`monitoring`) в `_PLANE_NAME_TO_KEY` (резолв по имени) + `_DEFAULT_STATES`.
|
||||
`To Analyse` заменяет `In Progress` как вход-триггер (старт + resume аналитика из Needs
|
||||
Input; fork «старт vs resume» по `get_task_by_plane_id`+`has_active_job_for_task` —
|
||||
сохранён). Стадии: analysis→`Analysis`, review→`Code-Review` (`_STAGE_TO_STATE_KEY`).
|
||||
- **Self-deploy фазы:** Phase A → `Awaiting Deploy` (разгружает `In Review`), Phase B →
|
||||
`Deploying`, Phase C/terminal-sync (self) → `Monitoring after Deploy` (НЕ `Done` сразу);
|
||||
post-deploy monitor (ORCH-021): HEALTHY-окно → `Done`, DEGRADED → `Blocked` (тик
|
||||
по-прежнему НИКОГДА не рестартит прод — ALERT_ONLY). Не-self репо: `deploy → Done` как
|
||||
сейчас (terminal-sync разводится по `post_deploy.post_deploy_applies`).
|
||||
- **Fail-closed (project-relative alias-fallback):** отсутствующий новый статус в проекте
|
||||
деградирует на **собственный базовый UUID того же проекта** (`to_analyse/analysis→in_progress`,
|
||||
`code_review→review`, `awaiting_deploy→in_review`, `deploying→in_progress`,
|
||||
`monitoring→done`) — индикация откатывается к текущей, конвейер не ломается, PATCH валиден
|
||||
даже при частичной конфигурации. Enduro (статусы не создаются) → строго прежнее поведение.
|
||||
Усиленный паттерн ORCH-059 AC-7.
|
||||
- **Reconciler:** F-2 триггер `in_progress`→`to_analyse`; Guard 2 skip-set расширен
|
||||
активными ожиданиями (`awaiting_deploy`/`deploying`/`monitoring`) с **вычитанием базовых
|
||||
рабочих статусов** — на enduro (алиасы схлопнуты) нулевой регресс, на orchestrator skip
|
||||
реальных ожиданий (BR-13).
|
||||
- **Инварианты:** `STAGE_TRANSITIONS`, `QG_CHECKS`, `check_deploy_status`, exit-коды хука,
|
||||
merge-gate, `Confirm Deploy`, механизм `Needs Input` (analyst-only), схема БД — без
|
||||
изменений. Без нового kill-switch (раскат гейтится созданием Plane-статусов оператором).
|
||||
Инфра-предусловие — `docs/work-items/ORCH-066/07-infra-requirements.md`.
|
||||
|
||||
Подробнее: `docs/work-items/ORCH-066/06-adr/ADR-001-plane-status-model.md`.
|
||||
|
||||
## Откаты
|
||||
- Reviewer REQUEST_CHANGES → откат на `development` + retry (`MAX_DEVELOPER_RETRIES = 3`).
|
||||
- Tester `check_tests_passed` FAIL → откат на `development` + retry.
|
||||
@@ -223,7 +322,7 @@ never-raise на единицу работы; тишина при синхрон
|
||||
- `events` — входящие вебхуки (дедуп)
|
||||
- `tasks` — задачи и их стадии
|
||||
- `agent_runs` — запуски агентов (run_id, usage, cost)
|
||||
- `jobs` — очередь задач (ORCH-1)
|
||||
- `jobs` — очередь задач (ORCH-1); колонка `pid` (ORCH-065) — pid агентского процесса для liveness-детекции зомби job-reaper'ом
|
||||
|
||||
## Изоляция (git worktree, ORCH-2)
|
||||
Каждая задача исполняется в отдельном git worktree, ветки не пересекаются. Репозитории проектов разделены под `/repos/<project>`.
|
||||
@@ -233,7 +332,7 @@ never-raise на единицу работы; тишина при синхрон
|
||||
|--------|------|----------|
|
||||
| GET | `/health` | health check |
|
||||
| GET | `/status` | активные задачи (stage != done) |
|
||||
| GET | `/queue` | очередь: counts + max_concurrency + resilience + reconcile (ORCH-053) + post_deploy (ORCH-021) + последние jobs |
|
||||
| GET | `/queue` | очередь: counts + max_concurrency + resilience + reconcile (ORCH-053) + reaper (ORCH-065) + post_deploy (ORCH-021) + последние jobs |
|
||||
| POST | `/webhook/plane` | Plane webhook |
|
||||
| POST | `/webhook/gitea` | Gitea webhook (push, PR, CI status) |
|
||||
|
||||
@@ -247,4 +346,4 @@ never-raise на единицу работы; тишина при синхрон
|
||||
Схема БД, потоки данных, resilience-слой, детали Dockerfile — [internals.md](internals.md).
|
||||
|
||||
---
|
||||
*Актуально на 2026-06-07. Обновлять при изменении src/stages.py, src/qg/checks.py, src/main.py. Статусы доработок: ORCH-036 (исполняемый самодеплой `deploy`, adr-0007) — реализовано; ORCH-043 (merge-gate, adr-0006) — design, ветка feature/ORCH-043; ORCH-053 (reconciler, adr-0007, src/reconciler.py) — реализовано; ORCH-060 (F-1 skip escalated/Blocked/Needs-Input, `docs/work-items/ORCH-060/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-060 (Guard 1 `developer_retry_count>=MAX_DEVELOPER_RETRIES` + Guard 2 `plane_sync.fetch_issue_state` Blocked/Needs-Input, флаг `ORCH_RECONCILE_SKIP_BLOCKED_ENABLED`); ORCH-058 (провенанс staging-образа: check_staging_image_fresh + staging_check свежего образа + хук-guard, adr-0008) — реализовано в ветке feature/ORCH-058 (обновлять также при изменении src/image_freshness.py, scripts/orchestrator-deploy-hook.sh, Dockerfile); ORCH-061 (толерантность staging-вердикта к инфра-FAIL C9a/C9b, adr-0009, `docs/work-items/ORCH-061/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-061 (обновлять также при изменении src/staging_verdict.py, scripts/staging_check.py, флаг staging_infra_tolerance_enabled); ORCH-021 (post-deploy наблюдение прода + реакция на деградацию, adr-0010, `docs/work-items/ORCH-021/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-021-post-deploy-rollback (reserved-agent job `post-deploy-monitor`: арм в src/stage_engine.py блок `next_stage == "done"`, тик `run_post_deploy_monitor` + перехват в src/agents/launcher.py ДО _spawn; чистая логика src/post_deploy.py never-raise; флаги `post_deploy_*` в src/config.py; блок `post_deploy` в `/queue`; артефакт 16-post-deploy-log.md; self-hosting всегда ALERT_ONLY — тик не рестартит прод; обновлять также при изменении src/post_deploy.py / арм-блока / launcher-перехвата).*
|
||||
*Актуально на 2026-06-07. Обновлять при изменении src/stages.py, src/qg/checks.py, src/main.py. Статусы доработок: ORCH-036 (исполняемый самодеплой `deploy`, adr-0007) — реализовано; ORCH-043 (merge-gate, adr-0006) — design, ветка feature/ORCH-043; ORCH-053 (reconciler, adr-0007, src/reconciler.py) — реализовано; ORCH-060 (F-1 skip escalated/Blocked/Needs-Input, `docs/work-items/ORCH-060/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-060 (Guard 1 `developer_retry_count>=MAX_DEVELOPER_RETRIES` + Guard 2 `plane_sync.fetch_issue_state` Blocked/Needs-Input, флаг `ORCH_RECONCILE_SKIP_BLOCKED_ENABLED`); ORCH-058 (провенанс staging-образа: check_staging_image_fresh + staging_check свежего образа + хук-guard, adr-0008) — реализовано в ветке feature/ORCH-058 (обновлять также при изменении src/image_freshness.py, scripts/orchestrator-deploy-hook.sh, Dockerfile); ORCH-061 (толерантность staging-вердикта к инфра-FAIL C9a/C9b, adr-0009, `docs/work-items/ORCH-061/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-061 (обновлять также при изменении src/staging_verdict.py, scripts/staging_check.py, флаг staging_infra_tolerance_enabled); ORCH-021 (post-deploy наблюдение прода + реакция на деградацию, adr-0010, `docs/work-items/ORCH-021/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-021-post-deploy-rollback (reserved-agent job `post-deploy-monitor`: арм в src/stage_engine.py блок `next_stage == "done"`, тик `run_post_deploy_monitor` + перехват в src/agents/launcher.py ДО _spawn; чистая логика src/post_deploy.py never-raise; флаги `post_deploy_*` в src/config.py; блок `post_deploy` в `/queue`; артефакт 16-post-deploy-log.md; self-hosting всегда ALERT_ONLY — тик не рестартит прод; обновлять также при изменении src/post_deploy.py / арм-блока / launcher-перехвата); ORCH-065 (job-reaper + проактивный реклейм merge-lease + идемпотентная финализация merge, adr-0011, `docs/work-items/ORCH-065/06-adr/ADR-001`) — реализовано в ветке feature/ORCH-065 (новый daemon-поток src/job_reaper.py + старт/стоп в src/main.py lifespan; колонка `jobs.pid` через _ensure_column + проставление в src/agents/launcher.py `_spawn`; функции реклейма lease `pid_alive`/`reclaim_stale_lease` + guard `pr_already_merged` в src/merge_gate.py (консультируется merge-актором — промпт `.openclaw/agents/deployer.md`); флаги `reaper_*`/`lease_reclaim_*` в src/config.py; блок `reaper` в `/queue`; обновлять также при изменении этих мест); ORCH-066 (осмысленная статусная модель Plane — слой B, `docs/work-items/ORCH-066/06-adr/ADR-001-plane-status-model.md`) — реализовано в ветке feature/ORCH-066-plane (только Plane-индикация: новые ключи `to_analyse`/`analysis`/`code_review`/`awaiting_deploy`/`deploying`/`monitoring` в `_PLANE_NAME_TO_KEY`/`_DEFAULT_STATES` + project-relative `_STATE_ALIAS_FALLBACK` в get_project_states + `_STAGE_TO_STATE_KEY` analysis/review + 5 новых `set_issue_*` в src/plane_sync.py; триггер `in_progress`→`to_analyse` и `set_issue_analysis` в src/webhooks/plane.py; Phase A→Awaiting Deploy / Phase B→Deploying / terminal-sync split monitoring↔done / post-deploy monitor HEALTHY→Done DEGRADED→Blocked в src/stage_engine.py; F-2 триггер `to_analyse` + Guard 2 skip-set с вычитанием base_working в src/reconciler.py; `STAGE_TRANSITIONS`/QG/схема БД НЕ трогаются; без kill-switch — раскат гейтится созданием 6 Plane-статусов оператором, `docs/work-items/ORCH-066/07-infra-requirements.md`; обновлять при изменении этих мест).*
|
||||
|
||||
@@ -16,11 +16,12 @@ Per-work-item решения живут в `docs/work-items/<id>/06-adr/ADR-NNN-
|
||||
| adr-0008 | Провенанс staging-образа перед BUILD-ONCE retag | accepted | 2026-06-06 | ORCH-058 |
|
||||
| adr-0009 | Толерантность staging-вердикта к инфраструктурным FAIL | accepted | 2026-06-07 | ORCH-061 |
|
||||
| adr-0010 | Post-deploy мониторинг прода + реакция на деградацию | proposed | 2026-06-07 | ORCH-021 |
|
||||
| adr-0011 | Job-reaper + проактивный реклейм merge-lease | accepted | 2026-06-07 | ORCH-065 |
|
||||
|
||||
> ⚠️ Историческая коллизия: номер `0007` занят двумя файлами —
|
||||
> `adr-0007-reconciler.md` (ORCH-053) и `adr-0007-executable-self-deploy.md`
|
||||
> (ORCH-036). Оба accepted; для новых сквозных ADR использовать следующий
|
||||
> свободный номер (текущий максимум — `0010`).
|
||||
> свободный номер (текущий максимум — `0011`).
|
||||
|
||||
## Формат
|
||||
**Контекст → Решение → Альтернативы → Последствия → Связи.** Статус: proposed / accepted / superseded.
|
||||
|
||||
82
docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md
Normal file
82
docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# adr-0011: Job-reaper + проактивный реклейм merge-lease
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Статус | accepted |
|
||||
| Дата | 2026-06-07 |
|
||||
| Источник | ORCH-065 (BUG P0, блокер ORCH-54) |
|
||||
| Детально | `docs/work-items/ORCH-065/06-adr/ADR-001-job-reaper-and-lease-reclaim.md` |
|
||||
|
||||
## Контекст
|
||||
|
||||
Единый инстанс с общей БД и очередью (`jobs`, `max_concurrency=1` для
|
||||
self-hosting). Финализация статуса job (`done`/`queued`/`failed`) происходит
|
||||
ТОЛЬКО в `launcher._monitor_agent → _finalize_job` внутри живого процесса. Смерть
|
||||
monitor-потока/процесса между `proc.wait()` и `_finalize_job` (краш, OOM,
|
||||
self-restart во время deploy) оставляет строку `jobs` навсегда `running`. При
|
||||
`max_concurrency=1` одна такая зомби-строка блокирует claim всех job →
|
||||
**встаёт конвейер всех проектов**. Единственная защита — `requeue_running_jobs()`
|
||||
— работает ТОЛЬКО на старте процесса. Симметрично: merge-lease (ORCH-043,
|
||||
файл `.merge-lease-<repo>.json`) реклеймится лишь лениво по TTL при чужом
|
||||
`acquire`; liveness держателя по pid не проверяется → залипший lease блокирует
|
||||
чужие merge. Это последняя ручная точка автономного self-deploy (блокер ORCH-54);
|
||||
доказанные инциденты 07.06 — jobs 236/239/242/254.
|
||||
|
||||
## Решение
|
||||
|
||||
1. **Job-reaper** — новый daemon-поток `src/job_reaper.py` (каркас `reconciler`:
|
||||
never-raise, `_stop`-Event, старт/стоп в `lifespan`, снимок в `/queue`,
|
||||
kill-switch). Работает **без рестарта** процесса. Liveness — трёхуровневая:
|
||||
Tier-1 мёртвый `jobs.pid` (новая колонка) после `reaper_dead_ticks` подряд
|
||||
тиков; Tier-2 `agent_runs.exit_code` записан, а job ещё `running` — но только
|
||||
после finalization-grace `reaper_finalize_grace_s` (окно неоднозначно: живой
|
||||
monitor пишет exit_code ПЕРВЫМ, затем git push/PR/Plane-комментарии, поэтому
|
||||
живой финализирующий monitor НЕ реапится); Tier-3 backstop по потолку
|
||||
`reaper_max_running_s`. Действие — **claim-before-act**: для exit0 канонический
|
||||
QG оценивается read-only ПЕРЕД атомарным claim, затем claim `done` ПЕРВЫМ и
|
||||
только победитель claim выполняет `_try_advance_stage` (advance+enqueue) —
|
||||
проигравший не делает побочных эффектов (источник истины — QG, не «exit0»);
|
||||
гейт красный или exit≠0 / неизвестно → `attempts<max` → `queued`, иначе
|
||||
`failed`+Telegram. Атомарный reap-claim (`UPDATE ... WHERE id=? AND
|
||||
status='running'` + `rowcount`, как `claim_next_job`) исключает двойную
|
||||
обработку (совместимость со стартовым `requeue_running_jobs`).
|
||||
2. **Проактивный реклейм stale/dead lease** — функции в `merge_gate.py`
|
||||
(`pid_alive`, `reclaim_stale_lease`), вызываемые на старте (рядом с
|
||||
`requeue_running_jobs`) и периодически из тика reaper. Освобождение, если
|
||||
держатель **мёртв** (pid не жив) ИЛИ **просрочен** (TTL); живой держатель в
|
||||
пределах TTL — НЕ трогать. holder-aware, never-raise, условность как ORCH-43.
|
||||
3. **Идемпотентная финализация merge** — без новой merge-логики: re-drive через
|
||||
reaper→`queued`→переисполнение стадии / reconciler; дорогие шаги не
|
||||
повторяются (`branch_is_behind_main==False`); добавлен детерминированный
|
||||
never-raise guard `pr_already_merged` (читает состояние PR), консультируемый
|
||||
перед повторным merge → уже слит = no-op.
|
||||
4. **Схема БД** — `jobs.pid INTEGER` через идемпотентный `_ensure_column`
|
||||
(паттерн live-safe миграции). Больше ничего не меняется.
|
||||
|
||||
Kill-switch'и (`ORCH_*`): `reaper_enabled`, `reaper_interval_s`,
|
||||
`reaper_dead_ticks`, `reaper_max_running_s`, `reaper_finalize_grace_s`,
|
||||
`lease_reclaim_enabled`; переиспользуются `merge_lock_timeout_s`,
|
||||
`merge_gate_repos`. `false` → строго прежнее поведение.
|
||||
|
||||
## Альтернативы
|
||||
- Reaper внутри reconciler — отвергнуто (смешение stage- и jobs-уровней, общий
|
||||
kill-switch, хуже изоляция).
|
||||
- Только эвристика `agent_runs` без `jobs.pid` — отвергнуто как основной механизм
|
||||
(не ловит зомби, чей monitor умер до записи exit_code); оставлена как Tier-2/3.
|
||||
- БД-lock / внешний брокер очередей — вне объёма (single-node SQLite).
|
||||
- Форс `done` по факту exit0 — отвергнуто; выбран gate-driven advance.
|
||||
|
||||
## Последствия
|
||||
- (+) Зомби-job и залипший lease самовосстанавливаются без рестарта и без
|
||||
оператора; очередь общего инстанса не встаёт; снят технический блокер ORCH-54.
|
||||
- (+) Контракты неизменны (`STAGE_TRANSITIONS`, `QG_CHECKS`, `check_*`, БАГ-8,
|
||||
exit-коды хука); одна колонка через проверенный idempotent-паттерн.
|
||||
- (−) pid-liveness валиден в предположении одного pid-namespace (агент —
|
||||
дочерний процесс оркестратора); закрыто backstop'ом по времени и TTL.
|
||||
- (−) streak-счётчик in-memory (сброс на рестарте; рестарт покрыт
|
||||
`requeue_running_jobs`).
|
||||
|
||||
## Связи
|
||||
- Базируется: adr-0002 (очередь), adr-0006 (merge-gate), adr-0007 (reconciler /
|
||||
self-deploy).
|
||||
- Разблокирует: ORCH-54.
|
||||
@@ -326,6 +326,7 @@ webhook (plane/gitea) background thread (queue_worker)
|
||||
| `status` | `queued` → `running` → `done` \| `failed` |
|
||||
| `attempts` / `max_attempts` | счётчик попыток (инкремент при claim) / лимит ретраев (default 2) |
|
||||
| `run_id` | FK на `agent_runs.id` после старта |
|
||||
| `pid` | (ORCH-065) pid агентского процесса (`proc.pid` из `_spawn`); liveness-сигнал для job-reaper. Добавляется `_ensure_column` (idempotent) |
|
||||
| `task_content` | ТЗ, которое пишется в task-файл агента |
|
||||
| `error` | последняя ошибка |
|
||||
|
||||
@@ -343,6 +344,36 @@ status='queued'` и проверяет `rowcount`. При гонке двух т
|
||||
jobs со статусом `running` (воркер умёр на рестарте) → возвращаются в `queued`.
|
||||
Потом стартует воркер; на shutdown — `worker.stop()` (Event.set + join).
|
||||
|
||||
### Job-reaper (ORCH-065, рестарт НЕ требуется)
|
||||
|
||||
`requeue_running_jobs()` спасает ТОЛЬКО на старте процесса. Зомби-job, возникший
|
||||
**без** рестарта (умер monitor-поток/дочерний процесс, а сервис жив), оставался
|
||||
`running` навсегда и при `max_concurrency=1` блокировал всю очередь. Фоновый
|
||||
daemon-поток `src/job_reaper.py` (каркас `reconciler`) периодически
|
||||
(`reaper_interval_s`) сканирует `running`-jobs и реапит «мёртвые»:
|
||||
- **Tier-1** — `jobs.pid` мёртв (`os.kill(pid,0)`→`ProcessLookupError`) на
|
||||
протяжении `reaper_dead_ticks` подряд тиков (анти-ложноположительность);
|
||||
- **Tier-2** — у `agent_runs[run_id]` записан `exit_code`, а `jobs.status` ещё
|
||||
`running`. Окно неоднозначно: живой monitor пишет `exit_code` ПЕРВЫМ, затем
|
||||
git push/PR/Plane-комментарии (секунды-десятки секунд) и лишь потом
|
||||
`_finalize_job`; pid агента к этому моменту мёртв в обоих случаях. Поэтому
|
||||
Tier-2 реапит только после finalization-grace `reaper_finalize_grace_s`
|
||||
(`finished_age_s >= grace`) — живой финализирующий monitor НЕ реапится;
|
||||
- **Tier-3** — backstop: job висит `running` дольше `reaper_max_running_s`.
|
||||
|
||||
Реап атомарен (`UPDATE jobs SET ... WHERE id=? AND status='running'` + `rowcount`,
|
||||
как `claim_next_job`) → совместим со стартовым `requeue_running_jobs` без двойной
|
||||
обработки. Действие — **claim-before-act**: для exit0 канонический QG оценивается
|
||||
read-only ПЕРЕД атомарным claim, затем claim `done` ПЕРВЫМ и только победитель
|
||||
claim делает `_try_advance_stage` (advance+enqueue) — проигравший (поздний monitor
|
||||
/ стартовый requeue) не выполняет побочных эффектов (нет дубль-advance/-enqueue);
|
||||
источник истины — QG, не «exit0»; гейт красный или exit≠0/неизвестно →
|
||||
`attempts<max`→`queued`, иначе `failed`+Telegram. Тот же поток на старте и
|
||||
периодически делает проактивный реклейм stale/dead merge-lease (`merge_gate.py`:
|
||||
`pid_alive`/`reclaim_stale_lease`). never-raise; kill-switch `ORCH_REAPER_ENABLED`
|
||||
/ `ORCH_LEASE_RECLAIM_ENABLED`; снимок в `GET /queue` (блок `reaper`). Подробнее —
|
||||
adr-0011.
|
||||
|
||||
### Конфиг
|
||||
|
||||
- `ORCH_MAX_CONCURRENCY` (default 1) — лимит параллельных jobs.
|
||||
|
||||
78
docs/history/LESSONS_2026-06-07_autonomy-closure.md
Normal file
78
docs/history/LESSONS_2026-06-07_autonomy-closure.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Lessons Learned — 2026-06-07: замыкание автономности self-deploy (5 задач в прод)
|
||||
|
||||
## Итог
|
||||
За одну сессию закрыты в прод **5 задач**, завершающих автономный self-deploy эпика ORCH-54:
|
||||
|
||||
| Задача | Что | Прод-коммит |
|
||||
|--------|-----|-------------|
|
||||
| ORCH-58 | provenance retag-guard (свежесть staging-образа перед BUILD-ONCE) | 094b5e2 |
|
||||
| ORCH-60 | reconciler не трогает escalated/Blocked/Needs-Input | d4c6cc0 |
|
||||
| ORCH-61 | фикс петли deploy-staging (staging_verdict: waive sandbox-infra FAILs C9a/C9b) | e18947d |
|
||||
| ORCH-21 | post-deploy мониторинг прода + auto-rollback (self-hosting=alert-only) | f85e449 |
|
||||
| ORCH-65 | job-reaper + stale merge-lease reclaim + idempotent merge | bb03350 |
|
||||
|
||||
**Главное:** после ORCH-60/61 конвейер впервые провёз задачи (ORCH-21/65) через deploy-staging
|
||||
**автономно** без отката; после ORCH-65 (job-reaper в проде) зомби-job и зависшие merge-lease
|
||||
лечатся сами. Последняя ручная точка автономного деплоя закрыта.
|
||||
|
||||
---
|
||||
|
||||
## Класс багов: «процесс умер — ресурс захвачен навсегда» (ORCH-65)
|
||||
Три связанных отказа, все воспроизвелись на ORCH-58/60/61/21:
|
||||
- **zombie jobs:** агент завершился/умер, строка jobs осталась running. requeue_running_jobs()
|
||||
спасает только на старте процесса; зомби без рестарта не лечился → при concurrency=1 встаёт
|
||||
конвейер ВСЕХ проектов. (jobs 236/239/242/254/265 — все зомби за сессию.)
|
||||
- **stale merge-lease:** merge-gate берёт .merge-lease-<repo>.json, делает rebase+re-test green,
|
||||
а на финальном merge процесс умирает с зажатым lease → merge не докатывается.
|
||||
- **неидемпотентный merge:** re-drive повторно пытается слить уже слитый PR.
|
||||
Фикс: фоновый job_reaper (паттерн reconciler, dead_ticks streak + мёртвый pid + exit_code,
|
||||
атомарный reap-claim, never-raise, kill-switch, снимок в /queue) + проактивный lease-reclaim
|
||||
по pid + guard pr_already_merged ПЕРЕД merge.
|
||||
|
||||
## Петля deploy-staging (ORCH-61) — ДВЕ причины
|
||||
1. ложный check_staging_status FAILED: staging_check падает на C9a/C9b (sandbox e2e branch +
|
||||
analyst-job-in-queue), т.к. bot-токены SANDBOX-проекта не настроены — НЕ регресс кода.
|
||||
2. no-changes для action-стадий (деплой = рестарт/retag, не правка → коммитить нечего).
|
||||
Фикс: staging_verdict waive sandbox-infra-only FAILs.
|
||||
|
||||
## Инфра-каскад от переполненного диска (инцидент дня)
|
||||
- Частые build-once/--build-staging пересборки за день забили docker build cache до 11 ГБ →
|
||||
диск 100% → CI red (No space left).
|
||||
- ДАЖЕ после чистки диска Gitea осталась в сломанном состоянии: внутренняя queue
|
||||
(/data/gitea/queues/common/*.log) залипла → post-receive hook 500 → actions tasks НЕ
|
||||
создаются, CI не триггерится вовсе (статус пустой, не failure). runner при этом online+idle.
|
||||
- Лечение: docker builder prune -af + рестарт Gitea (queue распускается → CI ожил).
|
||||
|
||||
---
|
||||
|
||||
## Уроки
|
||||
1. **Self-hosting safety (сквозной принцип):** прод-орк обслуживает ВСЕ проекты. Нельзя авто-
|
||||
откатывать/рестартить self в рамках задачи; нельзя пушить main. ORCH-21 post-deploy для
|
||||
self-hosting = alert-only, авто-rollback только для не-self репо.
|
||||
2. **TDD без доводки (повтор ORCH-58 и ORCH-65 v1):** тесты есть, реализация/wiring не
|
||||
подключены к боевому пути → мёртвый код + врущая дока. Reviewer обязан грепать вызовы из
|
||||
прод-кода, не только наличие функции.
|
||||
3. **Concurrency-баги ловятся итеративно:** ORCH-65 3 прохода reviewer (мёртвый guard → race
|
||||
condition side-effects-before-claim → approve) — каждый раз НОВЫЙ реальный дефект, не
|
||||
зацикливание. Atomic-claim ДО side-effects — обязательное правило.
|
||||
4. **При красном CI + зелёных локальных тестах — ПЕРВЫМ делом df -h / и docker system df**,
|
||||
не копаться в коде. После disk-full обязателен рестарт Gitea (queue залипает).
|
||||
5. **Bootstrap-разрыв:** задача про автономность деплоя не может задеплоить себя автономно,
|
||||
пока её механизм не в проде. Последний прод-деплой каждого такого фикса — вручную.
|
||||
6. **Перед прод-retag (build-once SOURCE_IMAGE=staging):** проверить revision-label staging-
|
||||
образа == целевой main HEAD, иначе guard fail-closed (by design). Если != → пересобрать
|
||||
--build-staging GIT_SHA=<main HEAD>.
|
||||
|
||||
## Ручная доводка прод-deploy (схема до ORCH-65 в проде)
|
||||
cancel zombie job → park task In Progress → merge PR (Gitea pulls/{n}/merge Do=merge, CI green)
|
||||
→ --build-staging GIT_SHA=<main HEAD> (проставит label) → rollback-снимок → --deploy с
|
||||
EXPECTED_REVISION=<sha> (guard сверит → retag → health 200) → Plane Done + UPDATE tasks stage=done.
|
||||
|
||||
## Follow-up (Backlog)
|
||||
- ORCH-62: авто-prune docker build cache (cron/daemon.json defaultKeepStorage).
|
||||
- ORCH-63: мониторинг диска mva154 + алерт >85%.
|
||||
- ORCH-64: починить NTP/часы mva154 (ушли ~+3ч от UTC).
|
||||
|
||||
## Осталось в эпике ORCH-54
|
||||
ORCH-22 (security-гейт), ORCH-59 (Confirm Deploy статус), ORCH-23 (budget circuit-breaker),
|
||||
P2: ORCH-57, ORCH-51.
|
||||
30
docs/work-items/ORCH-022/15-staging-log.md
Normal file
30
docs/work-items/ORCH-022/15-staging-log.md
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
staging_status: SUCCESS
|
||||
timestamp: 2026-06-07T18:02:27+00:00
|
||||
base_url: http://localhost:8501
|
||||
---
|
||||
|
||||
# Staging Gate Log
|
||||
|
||||
Staging test suite completed via canonical run (ORCH-048, ADR-001):
|
||||
|
||||
```
|
||||
docker exec orchestrator-staging \
|
||||
python3 /repos/orchestrator/scripts/staging_check.py \
|
||||
--base-url http://localhost:8501 --mode stub
|
||||
```
|
||||
|
||||
**Result: 8/10 checks PASS — exit code 0 (advance).**
|
||||
|
||||
All REAL (pipeline) checks green: A1, A2, A3 (SMOKE), B4, B5, B6 (ACCESS), C7, C8 (E2E).
|
||||
|
||||
Two sandbox-infra-only checks failed and were waived per ORCH-061
|
||||
(`staging_infra_tolerance_enabled=True`) — these depend on SANDBOX bot accounts
|
||||
being members of the SANDBOX Plane project, not on the pipeline:
|
||||
|
||||
```
|
||||
INFRA-WAIVED: C9a Branch appears in orchestrator-sandbox, C9b Analyst job enqueued in staging queue (known sandbox-infra; real checks green)
|
||||
VERDICT: SUCCESS (exit 0) — SUCCESS (infra-waived): ['C9a Branch appears in orchestrator-sandbox', 'C9b Analyst job enqueued in staging queue'] are known sandbox-infra checks; all real checks green
|
||||
```
|
||||
|
||||
Cleanup ran (Plane SANDBOX test issue deleted, HTTP 204). Exit code 0 → `staging_status: SUCCESS`.
|
||||
29
docs/work-items/ORCH-059/15-staging-log.md
Normal file
29
docs/work-items/ORCH-059/15-staging-log.md
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
staging_status: SUCCESS
|
||||
timestamp: 2026-06-07T19:19:25Z
|
||||
base_url: http://localhost:8501
|
||||
---
|
||||
|
||||
# Staging Gate Log
|
||||
|
||||
Staging test suite completed. Verdict: **SUCCESS** (exit 0).
|
||||
|
||||
Canonical run inside the `orchestrator-staging` container (ORCH-048, ADR-001):
|
||||
`python3 /repos/orchestrator/scripts/staging_check.py --base-url http://localhost:8501 --mode stub`
|
||||
|
||||
## Result
|
||||
|
||||
- RESULT: 8/10 checks PASS
|
||||
- REAL failed: none
|
||||
- SANDBOX_INFRA failed: C9a (branch in orchestrator-sandbox), C9b (analyst job enqueued)
|
||||
|
||||
All REAL pipeline checks (Block A SMOKE, Block B ACCESS incl. B6 registry isolation,
|
||||
C7/C8) are green. The two failing checks are sandbox-infra-only (SANDBOX bot accounts
|
||||
not members of the SANDBOX Plane project) and were waived per ORCH-061. Exit code 0.
|
||||
|
||||
```
|
||||
INFRA-WAIVED: C9a Branch appears in orchestrator-sandbox, C9b Analyst job enqueued in staging queue (known sandbox-infra; real checks green)
|
||||
VERDICT: SUCCESS (exit 0) — SUCCESS (infra-waived): ['C9a Branch appears in orchestrator-sandbox', 'C9b Analyst job enqueued in staging queue'] are known sandbox-infra checks; all real checks green
|
||||
```
|
||||
|
||||
tolerance: staging_infra_tolerance_enabled=True
|
||||
7
docs/work-items/ORCH-065/00-business-request.md
Normal file
7
docs/work-items/ORCH-065/00-business-request.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# Business Request: BUG: zombie jobs + merge-lease залип (процесс умер, статус running)
|
||||
|
||||
Work Item ID: ORCH-065
|
||||
|
||||
## Description
|
||||
|
||||
TBD
|
||||
103
docs/work-items/ORCH-065/01-brd.md
Normal file
103
docs/work-items/ORCH-065/01-brd.md
Normal file
@@ -0,0 +1,103 @@
|
||||
# BRD — ORCH-065: zombie jobs + залипший merge-lease
|
||||
|
||||
Work Item ID: ORCH-065
|
||||
Тип: BUG (P0)
|
||||
Репозиторий: orchestrator (self-hosting)
|
||||
Эпик: блокер ORCH-54 (полностью автономный self-deploy)
|
||||
|
||||
## 1. Контекст и проблема
|
||||
|
||||
Оркестратор — единый инстанс с **общей БД и общей очередью** (`jobs`,
|
||||
`max_concurrency=1` для self-hosting), обслуживающий несколько проектов. Финальная
|
||||
автономность self-deploy упирается в два связанных класса отказов, оба сводящиеся
|
||||
к «процесс умер/завершился, а состояние осталось захваченным навсегда»:
|
||||
|
||||
### Проблема A — zombie jobs (строка `jobs` навсегда `running`)
|
||||
Агент (deployer/developer/reviewer) завершается **или умирает** (краш, OOM,
|
||||
рестарт контейнера в ходе self-deploy, гибель monitor-потока), но строка в таблице
|
||||
`jobs` остаётся в статусе `running`. Финализация статуса job выполняется **только**
|
||||
в `_monitor_agent` → `_finalize_job` внутри того же процесса; если этот поток/процесс
|
||||
не доживает до финализации — job «зомбирован».
|
||||
|
||||
- Единственная имеющаяся защита — `requeue_running_jobs()` в `main.lifespan`,
|
||||
срабатывающая **исключительно на старте процесса**. Зомби, возникший **без**
|
||||
рестарта (умер дочерний процесс/monitor-поток, а сервис жив), не реанимируется
|
||||
никогда.
|
||||
- При `max_concurrency=1` одна зомби-строка `running` блокирует claim всех
|
||||
последующих job (`count_running_jobs() >= max_concurrency` → claim не происходит)
|
||||
→ **встаёт конвейер всех проектов**.
|
||||
|
||||
### Проблема B — залипший merge-lease
|
||||
Merge-gate (ORCH-043) берёт файловый lease `<repos_dir>/.merge-lease-<repo>.json`
|
||||
ПЕРЕД rebase+re-test и держит его до фактического merge PR в `main`. Если процесс
|
||||
умирает на финальном merge **с зажатым lease**:
|
||||
|
||||
- Реклейм lease реализован **лениво и только по возрасту** (`age >=
|
||||
merge_lock_timeout_s`) и **только в момент `acquire_merge_lease` другой задачей**.
|
||||
Проактивного освобождения (на старте / периодически) нет; **liveness держателя по
|
||||
pid не проверяется** (хотя `pid` в lease пишется).
|
||||
- Пострадавшая задача сама re-drive не получает: merge не финализируется → задача
|
||||
висит, lease мешает чужим merge до истечения TTL.
|
||||
|
||||
### Проблема C — неидемпотентная финализация merge
|
||||
Если rebase+re-test прошли зелёно (ветка догнана и проверена), но процесс умер до
|
||||
завершения слияния PR — повторного «докатывания» merge нет. Задача застревает в
|
||||
полу-выполненном состоянии, хотя вся дорогая работа (rebase+re-test) уже сделана.
|
||||
|
||||
## 2. Бизнес-последствия
|
||||
- **Это ПОСЛЕДНЯЯ ручная точка автономного деплоя.** Без фикса ни одна self-hosting
|
||||
задача не доезжает до прода без оператора (cancel zombie + ручной merge PR +
|
||||
ручной `--deploy`).
|
||||
- Прямой блокер эпика ORCH-54.
|
||||
- Доказанные инциденты (07.06): ORCH-58/60/61/21 — каждый раз после успешного
|
||||
deployer-прохода job оставался `running`; jobs **236/239/242/254** — зомби,
|
||||
прод-merge/deploy доводились вручную.
|
||||
- Групповой риск: зомби в общей очереди при concurrency=1 останавливает конвейер
|
||||
enduro-trails и всех прочих проектов.
|
||||
|
||||
## 3. Цель
|
||||
Сделать так, чтобы **смерть процесса/потока на любой стадии (включая self-restart
|
||||
во время deploy) НЕ оставляла навсегда захваченных ресурсов** — ни строки `jobs` в
|
||||
`running`, ни merge-lease. Конвейер должен самовосстанавливаться без оператора, при
|
||||
этом сохраняя все инварианты self-hosting (не ронять прод-контейнер, не трогать
|
||||
`main`, fail-closed на реальных ошибках).
|
||||
|
||||
## 4. Объём (Scope)
|
||||
|
||||
### В объёме
|
||||
1. **Job-reaper** — фоновый watchdog (паттерн `reconciler`/`queue_worker`),
|
||||
детектирующий «мёртвый» `running`-job и приводящий его строку в корректный
|
||||
терминальный/повторный статус (`done`/`failed`/`queued`) детерминированно,
|
||||
без LLM. Restart-safe и работающий **без** рестарта процесса.
|
||||
2. **Проактивный реклейм stale merge-lease** — освобождение lease, чей держатель
|
||||
мёртв (pid не жив) ИЛИ возраст превысил TTL — на старте и периодически (reaper/
|
||||
reconciler), а не только лениво при чужом `acquire`.
|
||||
3. **Идемпотентная финализация merge** — если rebase+re-test зелёные, но merge не
|
||||
состоялся, операция повторяется/докатывается без потери уже сделанной работы.
|
||||
|
||||
### Вне объёма
|
||||
- Переход на внешний брокер очередей / смену схемы блокировок merge на БД-lock.
|
||||
- Полный авто-approve деплоя (ORCH-54) — отдельная задача; здесь только снятие
|
||||
технического блокера.
|
||||
- Изменение конвейера стадий (`STAGE_TRANSITIONS`) и реестра гейтов как контрактов.
|
||||
|
||||
## 5. Заинтересованные стороны
|
||||
- Owner оркестратора (self-hosting автономность).
|
||||
- Все проекты на общем инстансе (enduro-trails и пр.) — страдают от блокировки
|
||||
общей очереди.
|
||||
|
||||
## 6. Допущения и ограничения
|
||||
- `max_concurrency=1` для self-hosting сохраняется.
|
||||
- Self-hosting safety (CLAUDE.md): нельзя ронять/рестартить прод-контейнер в рамках
|
||||
задачи; нельзя пушить/форс-пушить `main`; реклейм lease не должен прерывать
|
||||
легитимно работающий merge.
|
||||
- Никаких ложных реанимаций: живой, но долгий job не должен помечаться зомби
|
||||
(нужен порог/грейс «N тиков» + проверка реальной смерти, а не просто долготы).
|
||||
- Контракт **never-raise** для всей новой фоновой логики (как у reconciler/merge_gate).
|
||||
- Kill-switch на каждый новый механизм (как `reconcile_enabled` / `merge_gate_enabled`).
|
||||
|
||||
## 7. Критерий успеха (бизнес-уровень)
|
||||
После фикса воспроизводимый сценарий «успешный deployer-проход + смерть процесса/
|
||||
self-restart» НЕ оставляет зомби-job и зажатого lease: задача либо корректно
|
||||
доезжает до `done` сама, либо откатывается по штатному контракту — **без участия
|
||||
оператора**. Регресс-тест на jobs-зомби и stale-lease зелёный.
|
||||
170
docs/work-items/ORCH-065/02-trz.md
Normal file
170
docs/work-items/ORCH-065/02-trz.md
Normal file
@@ -0,0 +1,170 @@
|
||||
# ТЗ — ORCH-065: job-reaper + stale merge-lease reclaim + идемпотентный merge
|
||||
|
||||
Work Item ID: ORCH-065
|
||||
Базируется на: 01-brd.md
|
||||
Примечание архитектору: ТЗ фиксирует ТРЕБОВАНИЯ и кандидатные модули. Выбор
|
||||
конкретной реализации (новый модуль vs расширение reconciler; колонка `jobs.pid`
|
||||
vs эвристика на `agent_runs`) — за стадией architecture (ADR). Если какая-либо
|
||||
часть ТЗ окажется нереализуемой/спорной — вернуть в Анализ, не комментировать
|
||||
задним числом.
|
||||
|
||||
## 0. Текущее состояние (факты из кода)
|
||||
|
||||
| Место | Факт |
|
||||
|-------|------|
|
||||
| `src/queue_worker.py` `_drain_once` | claim не происходит, пока `count_running_jobs() >= max_concurrency`. Одна зомби-строка `running` при concurrency=1 блокирует всю очередь. |
|
||||
| `src/agents/launcher.py` `_monitor_agent` → `_finalize_job` | статус job (`done`/`queued`/`failed`) выставляется ТОЛЬКО в этом monitor-потоке. Смерть потока/процесса до финализации ⇒ job навсегда `running`. |
|
||||
| `src/main.py` (lifespan, строки ~55-61) | `requeue_running_jobs()` вызывается ТОЛЬКО при старте процесса. |
|
||||
| `src/db.py` `requeue_running_jobs` | flip всех `running`→`queued`. Без рестарта не запускается. |
|
||||
| `src/db.py` таблица `jobs` | колонки `pid`/`heartbeat` НЕТ; есть `run_id`, `started_at`, `attempts`, `max_attempts`. |
|
||||
| `src/merge_gate.py` `acquire_merge_lease` | реклейм stale lease (age `>= merge_lock_timeout_s`) и corrupt — ТОЛЬКО лениво в момент `acquire`. Lease пишет `pid`, но liveness по pid нигде не проверяется. |
|
||||
| `src/merge_gate.py` `release_merge_lease` | holder-aware (по `branch`), идемпотентен. Вызовы: `webhooks/gitea.py:380` (PR-merged), `stage_engine.py:352/740/876/952`, `qg/checks.py:683/691/697`. |
|
||||
| `src/qg/checks.py` `check_branch_mergeable` | при SUCCESS lease ДЕРЖИТСЯ до фактического merge PR. Если процесс умрёт после этого — lease зажат. |
|
||||
| `src/reconciler.py` | паттерн-образец фонового daemon-потока (never-raise, kill-switch, observability в `/queue`). |
|
||||
|
||||
## 1. Задействованные модули `src/`
|
||||
|
||||
- `src/db.py` — новые job-запросы для reaper (выборка stale running-job, атомарный
|
||||
reap). Возможна lightweight-миграция (см. §3).
|
||||
- **Job-reaper** — НОВЫЙ модуль (кандидат `src/job_reaper.py`) ИЛИ расширение
|
||||
`src/reconciler.py`. Решение — за архитектором; ТЗ требует daemon-поток по образцу
|
||||
`reconciler` (never-raise, `_stop`-Event, старт/стоп в `main.lifespan`, снимок в
|
||||
`/queue`).
|
||||
- `src/merge_gate.py` — функция проактивного реклейма stale/dead lease (по pid-
|
||||
liveness + по TTL); helper проверки liveness pid; helper идемпотентной
|
||||
финализации merge.
|
||||
- `src/main.py` — старт/стоп нового daemon-потока в `lifespan` (после `worker.start()`
|
||||
/ `reconciler.start()`, симметрично остановка перед `worker.stop()`); вызов
|
||||
стартового реклейма stale-lease рядом с `requeue_running_jobs()`.
|
||||
- `src/config.py` — новые настройки/флаги (см. §5).
|
||||
- `src/main.py` `GET /queue` — блок наблюдаемости reaper (образец `reconcile`/
|
||||
`post_deploy`).
|
||||
|
||||
## 2. Функциональные требования
|
||||
|
||||
### FR-1. Job-reaper (Проблема A)
|
||||
- Фоновый поток периодически (`reaper_interval_s`) сканирует строки `jobs` в статусе
|
||||
`running`.
|
||||
- Для каждого `running`-job определяет, **жив ли его исполнитель**. «Мёртвым» job
|
||||
считается, когда выполнено и устойчиво (см. FR-1.3) хотя бы одно из:
|
||||
- процесс агента (по pid/run_id) не существует, а финализация не произошла;
|
||||
- `agent_runs` строки run_id имеет `finished_at`/`exit_code` (процесс реально
|
||||
завершился), но `jobs.status` всё ещё `running` (monitor умер между записью
|
||||
exit_code и `_finalize_job`);
|
||||
- job висит `running` дольше предохранительного потолка
|
||||
`reaper_max_running_s` (заведомо больше любого легитимного `agent_timeout` +
|
||||
grace) — backstop на случай, когда liveness определить нельзя.
|
||||
- FR-1.2 Действие при подтверждённой смерти:
|
||||
- если есть достоверный успешный исход (`agent_runs.exit_code == 0`) — довести job
|
||||
к корректному завершению **через тот же контракт**, что `_finalize_job`
|
||||
(включая, при необходимости, повторную попытку auto-advance) — НЕ дублировать
|
||||
переход, если он уже произошёл (идемпотентность через `has_active_job_for_task`
|
||||
/ проверку стадии);
|
||||
- если исход неуспешный/неизвестен и бюджет попыток не исчерпан
|
||||
(`attempts < max_attempts`) — `queued` (повторная постановка), как делает
|
||||
`requeue_running_jobs`;
|
||||
- если бюджет исчерпан — `failed` + Telegram-алерт.
|
||||
- FR-1.3 **Анти-ложноположительность.** Job помечается зомби только после
|
||||
устойчивого подтверждения смерти: процесс мёртв на протяжении `reaper_dead_ticks`
|
||||
последовательных тиков (≥2) ИЛИ превышен `reaper_max_running_s`. Живой долгий
|
||||
агент (в пределах своего `agent_timeout`) НИКОГДА не реапится.
|
||||
- FR-1.4 Работает **без рестарта** процесса (главное отличие от существующего
|
||||
`requeue_running_jobs`).
|
||||
- FR-1.5 Restart-safe: после рестарта поведение корректно совмещается со стартовым
|
||||
`requeue_running_jobs()` (нет двойной обработки одной строки; атомарность reap-
|
||||
UPDATE с guard по `status='running'`, как в `claim_next_job`).
|
||||
|
||||
### FR-2. Проактивный реклейм stale/dead merge-lease (Проблема B)
|
||||
- FR-2.1 На старте процесса (рядом с `requeue_running_jobs()` в `lifespan`) и
|
||||
периодически в фоновом потоке: для каждого репо с merge-gate проверить lease и
|
||||
освободить его, если держатель **мёртв** или lease **просрочен**.
|
||||
- FR-2.2 «Держатель мёртв» = pid из lease не существует в системе (liveness-проба,
|
||||
напр. `os.kill(pid, 0)` с обработкой `ProcessLookupError`/`PermissionError`),
|
||||
при условии что pid принадлежит этому хосту/неймспейсу. «Просрочен» = `age >=
|
||||
merge_lock_timeout_s` (существующий TTL-контракт сохраняется).
|
||||
- FR-2.3 Реклейм **holder-aware и безопасен**: НЕ освобождать lease, чей держатель
|
||||
жив и в пределах TTL (защита легитимного merge). Логировать `warning` при каждом
|
||||
реклейме (наблюдаемость, как сейчас в `acquire_merge_lease`).
|
||||
- FR-2.4 Условность как ORCH-35/43: реально только для self-hosting/`merge_gate_repos`;
|
||||
прочие репо — no-op.
|
||||
- FR-2.5 Контракт **never-raise**; любая ошибка реклейма не должна валить поток.
|
||||
|
||||
### FR-3. Идемпотентная финализация merge (Проблема C)
|
||||
- FR-3.1 Если ветка прошла rebase+re-test (догнана до `origin/main` и зелёная), но
|
||||
merge PR не состоялся из-за смерти процесса — система должна **докатить/повторить**
|
||||
merge без повторного прогона дорогих шагов, когда это безопасно.
|
||||
- FR-3.2 Финализация merge должна быть **идемпотентной**: повторный вызов при уже
|
||||
слитом PR — no-op (определять по состоянию PR в Gitea и/или по
|
||||
`branch_is_behind_main`/состоянию `main`), без ошибки и без второго слияния.
|
||||
- FR-3.3 Восстановление re-drive обеспечивается штатными механизмами (reaper
|
||||
довёл job до `queued` → повторный проход стадии `deploy`/merge-gate; либо
|
||||
reconciler доигрывает переход). Дублирующая логика merge НЕ создаётся — переиспользуются
|
||||
существующие пути (`check_branch_mergeable` / deployer-merge).
|
||||
- FR-3.4 При повторе lease берётся заново (идемпотентный re-acquire «held by self»
|
||||
по branch уже поддержан в `acquire_merge_lease`).
|
||||
|
||||
### FR-4. Наблюдаемость
|
||||
- FR-4.1 Блок `reaper` в `GET /queue`: enabled, interval, last_run_ts, reaped_total,
|
||||
last_reaped (job_id/agent), lease_reclaimed_total (best-effort, как у reconciler).
|
||||
- FR-4.2 Каждый reap и каждый lease-reclaim — `logger.warning` с идентификаторами
|
||||
(job_id, run_id, pid, repo, branch).
|
||||
- FR-4.3 При reap→`failed` и при lease-reclaim — Telegram (как существующие алерты).
|
||||
|
||||
## 3. Изменения схемы БД
|
||||
- Текущая `jobs` НЕ содержит `pid`. Для надёжной pid-liveness job-reaper'у, скорее
|
||||
всего, потребуется **lightweight-миграция**: добавить `jobs.pid INTEGER` (через
|
||||
`_ensure_column`, идемпотентно, безопасно на live prod DB — паттерн уже
|
||||
применяется в `db.py`). pid проставляется в `_spawn` рядом с `run_id`/`started_at`.
|
||||
- **Альтернатива без миграции** (на усмотрение архитектора): определять смерть по
|
||||
`agent_runs.finished_at/exit_code` + потолку `reaper_max_running_s`, без хранения
|
||||
pid в `jobs`. ADR должен зафиксировать выбор и обоснование.
|
||||
- Реестры `STAGE_TRANSITIONS` и `QG_CHECKS` — **без изменений** (новых стадий/гейтов
|
||||
не вводим; reaper и lease-reclaim — фоновые механизмы, не стадии).
|
||||
- Merge-lease остаётся файловым (`.merge-lease-<repo>.json`); схема файла lease
|
||||
не меняется (pid и acquired_at уже есть).
|
||||
|
||||
## 4. Изменения API
|
||||
- `GET /queue` — добавить блок `reaper` (read-only наблюдаемость). Прочие endpoints
|
||||
без изменений. Новых webhook-роутов нет.
|
||||
|
||||
## 5. Конфигурация / kill-switches (`src/config.py`)
|
||||
Именование — по образцу `reconcile_*` / `merge_*`. Кандидаты (точные имена/дефолты
|
||||
уточняет архитектор):
|
||||
|
||||
| Настройка | Назначение | Дефолт (предложение) |
|
||||
|-----------|-----------|----------------------|
|
||||
| `reaper_enabled` | глобальный kill-switch job-reaper | `true` |
|
||||
| `reaper_interval_s` | период сканирования | `60` |
|
||||
| `reaper_dead_ticks` | сколько подряд тиков pid должен быть мёртв перед reap | `2` |
|
||||
| `reaper_max_running_s` | потолок «running» (backstop), > max agent_timeout+grace | `3600` |
|
||||
| `lease_reclaim_enabled` | kill-switch проактивного реклейма lease | `true` |
|
||||
| (переиспользуется) `merge_lock_timeout_s` | TTL lease | `300` (как есть) |
|
||||
| (переиспользуется) `merge_gate_repos` | область применения lease-reclaim | как есть |
|
||||
|
||||
Все флаги — пробрасываются из env (`ORCH_*`), `false` → строго прежнее поведение.
|
||||
|
||||
## 6. Требования к QG checks
|
||||
- Новых QG checks НЕ вводить (это фоновые resilience-механизмы, не гейты выхода со
|
||||
стадии). `check_branch_mergeable` остаётся контрактно неизменным; допускается лишь
|
||||
переиспользование его как идемпотентного пути финализации merge (FR-3.3).
|
||||
|
||||
## 7. Артефакты pipeline, создаваемые/обновляемые в ЭТОМ PR
|
||||
- Код: см. §1.
|
||||
- `06-adr/ADR-001-*.md` — архитектурное решение (где живёт reaper; pid-колонка vs
|
||||
эвристика; механизм идемпотентного merge) — создаёт architect.
|
||||
- `docs/architecture/README.md` — новый раздел про job-reaper + lease-reclaim
|
||||
(golden-source, в этом же PR).
|
||||
- `docs/architecture/internals.md` — детали (если затрагивается схема БД / потоки).
|
||||
- `CHANGELOG.md` — запись ORCH-065.
|
||||
- `.env.example` — новые `ORCH_*` флаги (канон секретов/настроек).
|
||||
- `docs/operations/INFRA.md` — упоминание поведения при self-restart, если
|
||||
затрагивается (best-effort).
|
||||
|
||||
## 8. Инварианты (НЕ нарушать)
|
||||
- Не ронять/не рестартить прод-контейнер `orchestrator` в рамках задачи.
|
||||
- Никогда не пушить/форс-пушить `main`; реклейм lease не инициирует git-операций.
|
||||
- `STAGE_TRANSITIONS`, реестр `QG_CHECKS`, контракты `check_*`, БАГ-8 откат,
|
||||
exit-коды deploy-хука — без изменений.
|
||||
- never-raise на единицу фоновой работы; идемпотентность; restart-safe; тишина при
|
||||
отсутствии аномалий (как reconciler).
|
||||
- Анти-ложноположительность (FR-1.3): живой долгий агент не реапится.
|
||||
122
docs/work-items/ORCH-065/03-acceptance-criteria.md
Normal file
122
docs/work-items/ORCH-065/03-acceptance-criteria.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# Критерии приёмки — ORCH-065
|
||||
|
||||
Work Item ID: ORCH-065
|
||||
Формат: каждый критерий имеет явное условие PASS/FAIL. Все критерии должны быть
|
||||
PASS для прохождения review/testing.
|
||||
|
||||
## A. Job-reaper (Проблема A)
|
||||
|
||||
### AC-1 — реап мёртвого running-job без рестарта
|
||||
- PASS: при наличии строки `jobs` в статусе `running`, чей процесс/исполнитель
|
||||
достоверно мёртв (pid не существует ИЛИ `agent_runs.exit_code` записан, а job всё
|
||||
ещё `running`) и условие устойчивости (FR-1.3) выполнено, фоновый reaper переводит
|
||||
строку в корректный статус (`done`/`queued`/`failed`) **без перезапуска процесса**.
|
||||
- FAIL: строка остаётся `running` после `reaper_dead_ticks` тиков / превышения
|
||||
`reaper_max_running_s`.
|
||||
|
||||
### AC-2 — разблокировка очереди при concurrency=1
|
||||
- PASS: после реапа зомби-строки `count_running_jobs()` снижается, и следующий
|
||||
queued-job успешно claim'ится воркером.
|
||||
- FAIL: очередь остаётся заблокированной зомби-строкой.
|
||||
|
||||
### AC-3 — анти-ложноположительность (живой долгий агент не реапится)
|
||||
- PASS: `running`-job с ЖИВЫМ процессом в пределах его `agent_timeout` НЕ помечается
|
||||
зомби (ни по одному тику, ни в пределах `reaper_max_running_s`, если потолок
|
||||
больше таймаута).
|
||||
- FAIL: живой агент помечен `failed`/`queued` reaper'ом.
|
||||
|
||||
### AC-4 — корректный исход по результату
|
||||
- PASS: при `agent_runs.exit_code == 0` reaper доводит до успешного завершения без
|
||||
дублирования уже выполненного stage-advance (идемпотентно); при неуспехе и
|
||||
`attempts < max_attempts` → `queued`; при исчерпании → `failed` + Telegram.
|
||||
- FAIL: успешный исход помечен `failed`; либо дублируется stage-переход; либо
|
||||
исчерпанный бюджет молча зацикливается на `queued`.
|
||||
|
||||
### AC-5 — restart-safe совместимость
|
||||
- PASS: одновременная работа стартового `requeue_running_jobs()` и периодического
|
||||
reaper не приводит к двойной обработке одной строки (атомарный UPDATE с guard
|
||||
`status='running'`).
|
||||
- FAIL: одна строка обработана дважды / гонка приводит к рассинхрону статуса.
|
||||
|
||||
## B. Stale/dead merge-lease reclaim (Проблема B)
|
||||
|
||||
### AC-6 — реклейм lease мёртвого держателя
|
||||
- PASS: lease `.merge-lease-<repo>.json`, чей `pid` не существует, проактивно
|
||||
освобождается на старте И периодическим потоком (не дожидаясь TTL и не дожидаясь
|
||||
чужого `acquire`).
|
||||
- FAIL: lease мёртвого держателя остаётся до истечения `merge_lock_timeout_s` или
|
||||
до следующего чужого `acquire`.
|
||||
|
||||
### AC-7 — реклейм по TTL сохранён
|
||||
- PASS: lease старше `merge_lock_timeout_s` освобождается (существующий контракт не
|
||||
сломан), с `logger.warning`.
|
||||
- FAIL: просроченный lease не освобождается.
|
||||
|
||||
### AC-8 — не трогать живой lease
|
||||
- PASS: lease с ЖИВЫМ держателем (pid жив) и возрастом `< merge_lock_timeout_s` НЕ
|
||||
освобождается (защита легитимного merge).
|
||||
- FAIL: освобождён lease живого держателя → возможен параллельный конфликтный merge.
|
||||
|
||||
### AC-9 — условность и never-raise
|
||||
- PASS: реклейм реален только для `merge_gate_repos`/self-hosting; для прочих репо
|
||||
— no-op; любая ошибка реклейма логируется и не валит поток (never-raise).
|
||||
- FAIL: реклейм выполняется для не-self-hosting репо; либо ошибка пробрасывается
|
||||
наружу/роняет поток.
|
||||
|
||||
## C. Идемпотентная финализация merge (Проблема C)
|
||||
|
||||
### AC-10 — докатывание незавершённого merge
|
||||
- PASS: сценарий «rebase+re-test зелёные, merge не состоялся, процесс умер»
|
||||
восстанавливается автоматически (job → `queued` reaper'ом / reconciler доигрывает),
|
||||
и merge доводится без повторного ненужного прогона дорогих шагов.
|
||||
- FAIL: задача остаётся в полу-выполненном состоянии, требует ручного merge.
|
||||
|
||||
### AC-11 — идемпотентность при уже слитом PR
|
||||
- PASS: повторный вызов финализации при уже слитом PR — no-op (определяется по
|
||||
состоянию PR/`main`), без ошибки и без второго merge.
|
||||
- FAIL: второй merge / ошибка при уже слитом PR.
|
||||
|
||||
## D. Инварианты и безопасность self-hosting
|
||||
|
||||
### AC-12 — прод-контейнер не трогается
|
||||
- PASS: ни reaper, ни lease-reclaim не рестартят/не роняют прод-контейнер и не
|
||||
инициируют git-push в `main`.
|
||||
- FAIL: любая из новых веток кода рестартит self / пушит main.
|
||||
|
||||
### AC-13 — контракты неизменны
|
||||
- PASS: `STAGE_TRANSITIONS`, реестр `QG_CHECKS`, сигнатуры/поведение `check_*`,
|
||||
БАГ-8 откат, exit-коды deploy-хука — без изменений; новых QG checks/стадий нет.
|
||||
- FAIL: затронут любой из перечисленных контрактов.
|
||||
|
||||
### AC-14 — kill-switches
|
||||
- PASS: `reaper_enabled=false` → reaper не работает (строго прежнее поведение);
|
||||
`lease_reclaim_enabled=false` → проактивный реклейм отключён (остаётся лишь
|
||||
прежний ленивый TTL-реклейм в `acquire`).
|
||||
- FAIL: флаг `false` не отключает соответствующий механизм.
|
||||
|
||||
## E. Наблюдаемость
|
||||
|
||||
### AC-15 — блок reaper в /queue
|
||||
- PASS: `GET /queue` содержит блок `reaper` (enabled, interval, last_run_ts,
|
||||
reaped_total, last_reaped, lease_reclaimed_total).
|
||||
- FAIL: блок отсутствует/не обновляется.
|
||||
|
||||
### AC-16 — логи и алерты
|
||||
- PASS: каждый reap и lease-reclaim → `logger.warning` с идентификаторами;
|
||||
reap→`failed` и lease-reclaim → Telegram.
|
||||
- FAIL: реап/реклейм происходят молча.
|
||||
|
||||
## F. Документация (gate reviewer)
|
||||
|
||||
### AC-17 — golden-source обновлён в этом же PR
|
||||
- PASS: обновлены `docs/architecture/README.md` (раздел про reaper + lease-reclaim),
|
||||
`CHANGELOG.md`, `.env.example` (новые `ORCH_*` флаги); заведён
|
||||
`06-adr/ADR-001-*.md`.
|
||||
- FAIL: код изменён, документация — нет (reviewer → REQUEST_CHANGES).
|
||||
|
||||
## G. Тесты
|
||||
|
||||
### AC-18 — регресс-тесты зелёные
|
||||
- PASS: новые unit/integration тесты (см. 04-test-plan.yaml) проходят; существующий
|
||||
`pytest tests/ -q` зелёный (нет регресса merge_gate / queue / reconciler).
|
||||
- FAIL: любой тест из плана красный или сломан существующий тест.
|
||||
196
docs/work-items/ORCH-065/04-test-plan.yaml
Normal file
196
docs/work-items/ORCH-065/04-test-plan.yaml
Normal file
@@ -0,0 +1,196 @@
|
||||
work_item: ORCH-065
|
||||
description: >
|
||||
Тест-план для фикса zombie jobs (job-reaper), залипшего merge-lease
|
||||
(проактивный реклейм dead/stale lease) и идемпотентной финализации merge.
|
||||
Все новые фоновые механизмы — never-raise, restart-safe, kill-switch.
|
||||
Модуль reaper и точные имена функций уточнит архитектор; в module указаны
|
||||
кандидатные пути (tests/test_job_reaper.py / tests/test_merge_lease_reclaim.py).
|
||||
|
||||
tests:
|
||||
# ---- A. Job-reaper ----
|
||||
- id: TC-01
|
||||
type: unit
|
||||
description: >
|
||||
Reaper переводит running-job с мёртвым исполнителем в корректный статус
|
||||
без рестарта процесса (pid не существует / exit_code записан, job всё ещё
|
||||
running). Покрывает AC-1.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-02
|
||||
type: unit
|
||||
description: >
|
||||
Анти-ложноположительность: running-job с ЖИВЫМ процессом в пределах
|
||||
agent_timeout НЕ реапится (ни по одному тику, ни в пределах reaper_max_running_s).
|
||||
Покрывает AC-3.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-03
|
||||
type: unit
|
||||
description: >
|
||||
Устойчивость: job помечается зомби только после reaper_dead_ticks
|
||||
последовательных тиков смерти pid (>=2), а не на первом тике. Покрывает FR-1.3.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-04
|
||||
type: unit
|
||||
description: >
|
||||
Backstop по потолку: job, висящий running дольше reaper_max_running_s,
|
||||
реапится даже если liveness определить нельзя. Покрывает FR-1.1/AC-1.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-05
|
||||
type: unit
|
||||
description: >
|
||||
Корректный исход: exit_code==0 -> успешное завершение без дублирования
|
||||
stage-advance; неуспех при attempts<max -> queued; исчерпан бюджет -> failed
|
||||
+ Telegram. Покрывает AC-4.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-06
|
||||
type: unit
|
||||
description: >
|
||||
Атомарность reap-UPDATE с guard status='running': параллельная обработка
|
||||
одной строки (стартовый requeue_running_jobs + reaper) не приводит к двойному
|
||||
reap. Покрывает AC-5.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-07
|
||||
type: unit
|
||||
description: >
|
||||
Kill-switch reaper_enabled=false -> reaper не трогает ни одной строки
|
||||
(строго прежнее поведение). Покрывает AC-14.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-08
|
||||
type: unit
|
||||
description: >
|
||||
never-raise: ошибка БД/ОС внутри одного тика reaper не пробрасывается и не
|
||||
останавливает поток (изоляция per-job, образец reconciler). Покрывает AC-9.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-09
|
||||
type: integration
|
||||
description: >
|
||||
Очередь разблокируется: после reap зомби-строки при max_concurrency=1
|
||||
следующий queued-job успешно claim'ится (claim_next_job + count_running_jobs).
|
||||
Покрывает AC-2.
|
||||
module: tests/test_queue.py
|
||||
expected: PASS
|
||||
|
||||
# ---- B. Stale/dead merge-lease reclaim ----
|
||||
- id: TC-10
|
||||
type: unit
|
||||
description: >
|
||||
Реклейм lease с мёртвым pid (os.kill(pid,0) -> ProcessLookupError)
|
||||
проактивно, не дожидаясь TTL и чужого acquire. Покрывает AC-6.
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-11
|
||||
type: unit
|
||||
description: >
|
||||
Реклейм по TTL (age >= merge_lock_timeout_s) сохранён, с logger.warning.
|
||||
Покрывает AC-7. (расширяет существующий stale-lease сценарий merge_gate.)
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-12
|
||||
type: unit
|
||||
description: >
|
||||
Живой lease (pid жив, age < TTL) НЕ освобождается — защита легитимного merge.
|
||||
Покрывает AC-8.
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-13
|
||||
type: unit
|
||||
description: >
|
||||
Условность: реклейм реален только для merge_gate_repos/self-hosting; для
|
||||
прочих репо no-op. Покрывает AC-9.
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-14
|
||||
type: unit
|
||||
description: >
|
||||
never-raise: ошибка чтения/удаления lease-файла не валит реклейм-поток.
|
||||
Покрывает AC-9.
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-15
|
||||
type: unit
|
||||
description: >
|
||||
Kill-switch lease_reclaim_enabled=false -> проактивный реклейм отключён,
|
||||
остаётся лишь прежний ленивый TTL-реклейм в acquire_merge_lease.
|
||||
Покрывает AC-14.
|
||||
module: tests/test_merge_lease_reclaim.py
|
||||
expected: PASS
|
||||
|
||||
# ---- C. Идемпотентная финализация merge ----
|
||||
- id: TC-16
|
||||
type: unit
|
||||
description: >
|
||||
Идемпотентность финализации: повторный вызов при уже слитом PR / уже
|
||||
актуальном main (branch_is_behind_main == False) — no-op, без ошибки и без
|
||||
второго merge. Покрывает AC-11.
|
||||
module: tests/test_merge_gate.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-17
|
||||
type: integration
|
||||
description: >
|
||||
Восстановление: сценарий "rebase+re-test зелёные, merge не состоялся,
|
||||
процесс умер" -> job доводится до queued reaper'ом и merge докатывается
|
||||
штатным путём без повторного дорогого re-test, когда безопасно. Покрывает AC-10.
|
||||
module: tests/test_merge_gate_race.py
|
||||
expected: PASS
|
||||
|
||||
# ---- D/E. Инварианты и наблюдаемость ----
|
||||
- id: TC-18
|
||||
type: integration
|
||||
description: >
|
||||
GET /queue содержит блок reaper (enabled, interval, last_run_ts,
|
||||
reaped_total, last_reaped, lease_reclaimed_total). Покрывает AC-15.
|
||||
module: tests/test_queue.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-19
|
||||
type: unit
|
||||
description: >
|
||||
Контракты неизменны: STAGE_TRANSITIONS и реестр QG_CHECKS не получили новых
|
||||
стадий/чеков; check_branch_mergeable сигнатурно не изменён. Покрывает AC-13.
|
||||
module: tests/test_config.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-20
|
||||
type: unit
|
||||
description: >
|
||||
Новые настройки reaper_*/lease_reclaim_* присутствуют в config с дефолтами и
|
||||
читаются из ORCH_* env. Покрывает §5 ТЗ / AC-14.
|
||||
module: tests/test_config.py
|
||||
expected: PASS
|
||||
|
||||
- id: TC-21
|
||||
type: unit
|
||||
description: >
|
||||
Стартовый реклейм stale/dead lease вызывается в lifespan рядом с
|
||||
requeue_running_jobs (smoke на регистрацию старт/стоп reaper-потока).
|
||||
Покрывает FR-2.1 / AC-6.
|
||||
module: tests/test_job_reaper.py
|
||||
expected: PASS
|
||||
|
||||
regression:
|
||||
- command: pytest tests/ -q
|
||||
expected: PASS
|
||||
note: >
|
||||
Полный прогон не должен ломать существующие тесты merge_gate / queue /
|
||||
reconciler / deploy.
|
||||
@@ -0,0 +1,275 @@
|
||||
# ADR-001 (ORCH-065): Job-reaper + проактивный реклейм merge-lease + идемпотентная финализация merge
|
||||
|
||||
## Статус
|
||||
Accepted — 2026-06-07
|
||||
|
||||
Связь со сквозным ADR: [docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md](../../../architecture/adr/adr-0011-job-reaper-lease-reclaim.md).
|
||||
|
||||
## Контекст
|
||||
|
||||
Оркестратор — единый инстанс с **общей БД и общей очередью** (`jobs`,
|
||||
`max_concurrency=1` для self-hosting). BRD/ТЗ фиксируют три связанных класса
|
||||
отказов «процесс/поток умер, а состояние осталось захваченным навсегда»:
|
||||
|
||||
- **A — zombie jobs.** Статус job (`done`/`queued`/`failed`) выставляется ТОЛЬКО
|
||||
в `launcher._monitor_agent` → `_finalize_job` внутри того же процесса. Смерть
|
||||
monitor-потока/процесса между `proc.wait()` и `_finalize_job` (краш, OOM,
|
||||
self-restart во время deploy) оставляет строку `jobs` навсегда `running`.
|
||||
Единственная защита — `requeue_running_jobs()`, срабатывает ТОЛЬКО на старте
|
||||
процесса. Зомби без рестарта не реанимируется никогда. При `max_concurrency=1`
|
||||
одна зомби-строка блокирует claim всех job (`count_running_jobs() >=
|
||||
max_concurrency`) → встаёт конвейер ВСЕХ проектов. Доказано: jobs 236/239/242/254
|
||||
(07.06).
|
||||
- **B — залипший merge-lease.** Файловый lease `.merge-lease-<repo>.json`
|
||||
(ORCH-043) реклеймится **лениво и только по возрасту** (`age >=
|
||||
merge_lock_timeout_s`) и **только** в момент `acquire_merge_lease` другой
|
||||
задачей. Liveness держателя по pid не проверяется, хотя pid в lease пишется.
|
||||
Смерть с зажатым lease блокирует чужие merge до истечения TTL.
|
||||
- **C — неидемпотентная финализация merge.** Если rebase+re-test зелёные, но
|
||||
процесс умер до фактического merge PR — повторного докатывания нет; дорогая
|
||||
работа (rebase+re-test) сделана, а задача висит.
|
||||
|
||||
Факты кода, на которых строится решение:
|
||||
- `_spawn` (launcher.py:401) создаёт `subprocess.Popen(["bash","-c",cmd])`;
|
||||
`proc.pid` — pid агентского процесса, дочернего к процессу оркестратора в ОДНОМ
|
||||
pid-namespace контейнера. Сейчас `jobs.pid` НЕ хранится.
|
||||
- `_monitor_agent` (launcher.py:541) порядок: `proc.wait()` → запись
|
||||
`agent_runs.finished_at/exit_code` → git commit/push (+PR) → БАГ-8 deployer
|
||||
rollback → usage-комменты → `_try_advance_stage` (exit0, gate-driven advance)
|
||||
→ `_finalize_job` (драйв статуса job по контракту attempts/transient).
|
||||
- `claim_next_job` (db.py:454) — атомарный claim через `UPDATE ... WHERE id=? AND
|
||||
status='queued'` + `rowcount` (образец атомарности).
|
||||
- `reconciler.py` — образец фонового daemon-потока (never-raise, `_stop`-Event,
|
||||
старт/стоп в `main.lifespan`, снимок в `/queue`, kill-switch).
|
||||
- `merge_gate.py`: lease пишет `pid=os.getpid()` (pid процесса оркестратора, НЕ
|
||||
агента), `acquired_at`; `release_merge_lease` уже holder-aware (по `branch`) и
|
||||
идемпотентен; `acquire_merge_lease` идемпотентен для «held by self» (по branch).
|
||||
- `is_self_hosting_repo` / `merge_gate_repos` — образец условности (ORCH-35/43).
|
||||
|
||||
## Решение
|
||||
|
||||
### Р-1. Job-reaper — отдельный daemon-поток `src/job_reaper.py`
|
||||
|
||||
Reaper — **новый модуль и отдельный daemon-поток** (НЕ расширение reconciler).
|
||||
Обоснование: reconciler работает на уровне **stage-transition** (источник истины —
|
||||
гейт/Plane); reaper работает на уровне **jobs/agent_runs** (источник истины —
|
||||
liveness процесса). Это разные never-raise-домены и разные kill-switch'и; слияние
|
||||
в один тик смешало бы ответственности. Reaper копирует проверенный каркас
|
||||
`Reconciler`: `threading.Thread(daemon=True)` + `threading.Event`, старт/стоп в
|
||||
`main.lifespan`, снимок в `/queue`, per-job изоляция исключений.
|
||||
|
||||
**Liveness — трёхуровневая (defense in depth):**
|
||||
|
||||
1. **Tier-1 (liveness, основной): мёртвый pid.** Добавляем колонку `jobs.pid`
|
||||
(см. Р-4). В `_spawn` рядом с `run_id`/`started_at` пишем `proc.pid`. Reaper:
|
||||
`pid_alive(pid)` = `os.kill(pid, 0)` с обработкой `ProcessLookupError` (мёртв)
|
||||
/ `PermissionError` (жив, чужой) — единственный сигнал, ловящий «monitor умер
|
||||
ДО записи `finished_at`».
|
||||
2. **Tier-2 (completion race): exit_code записан, job ещё `running`.** Окно
|
||||
**неоднозначно**: это И «monitor умер между записью exit_code и
|
||||
`_finalize_job`», И «живой monitor ещё финализирует» — `_monitor_agent`
|
||||
пишет `exit_code` ПЕРВЫМ, затем git commit/push (+PR), БАГ-8-проверку и
|
||||
сетевые usage-комментарии в Plane (секунды-десятки секунд), и лишь потом
|
||||
`_try_advance_stage` → `_finalize_job`. pid агента к этому моменту уже мёртв в
|
||||
ОБОИХ случаях, поэтому по pid их не различить. **Анти-ложноположительность
|
||||
Tier-2 (FR-1.3, AC-3): finalization-grace.** Job реапится по Tier-2 только
|
||||
когда `exit_code` записан не меньше `reaper_finalize_grace_s` назад (потолок
|
||||
заведомо > максимального окна финализации). В пределах grace строка не
|
||||
трогается (живой финализирующий monitor НИКОГДА не реапится; нет дубль-advance
|
||||
/ дубль-enqueue). После grace monitor заведомо мёртв → исход **известен**.
|
||||
3. **Tier-3 (backstop по потолку):** job висит `running` дольше
|
||||
`reaper_max_running_s` (заведомо > max `agent_timeout`+grace). Реап даже когда
|
||||
liveness определить нельзя (pid переиспользован/неизвестен).
|
||||
|
||||
**Анти-ложноположительность (FR-1.3, AC-3):** по Tier-1 job реапится только после
|
||||
`reaper_dead_ticks` (≥2) ПОДРЯД тиков мёртвого pid — in-memory streak-счётчик по
|
||||
`job_id` (best-effort, сбрасывается на рестарте — но рестарт покрыт стартовым
|
||||
`requeue_running_jobs`). Tier-3 — одношаговый (порог времени, streak не нужен).
|
||||
Живой агент в пределах своего `agent_timeout` НЕ реапится никогда (pid жив + не
|
||||
превышен потолок).
|
||||
|
||||
**Действие при подтверждённой смерти (FR-1.2, AC-4) — переиспользование
|
||||
существующих контрактов, без дублирования:**
|
||||
|
||||
- **Атомарный reap-claim.** Перед любым действием с побочными эффектами reaper
|
||||
атомарно «застолбляет» строку тем же приёмом, что `claim_next_job`: терминальный
|
||||
flip несёт guard `WHERE id=? AND status='running'` и проверяет `rowcount`. При
|
||||
гонке (поздно доехавший monitor, стартовый `requeue_running_jobs`) проигравший
|
||||
видит `rowcount==0` и НЕ обрабатывает строку повторно (AC-5).
|
||||
- **Исход известен (Tier-2, exit_code в `agent_runs`, grace прошёл):**
|
||||
- `exit==0`: **claim-BEFORE-act, gate-driven idempotent advance.** Порядок
|
||||
критичен (см. «Атомарный reap-claim» выше): атомарный claim ОБЯЗАН
|
||||
предшествовать любому `advance_stage`/`enqueue_job`. Поскольку claim
|
||||
переводит строку ИЗ `running`, прогнать advance ДО claim, чтобы узнать цвет
|
||||
гейта, нельзя — поэтому канонический QG оценивается **read-only, без
|
||||
побочных эффектов** (тот же `_run_qg`, что у reconciler) ПЕРЕД claim:
|
||||
- стадия уже продвинута мимо этого агента → атомарный `done` без advance
|
||||
(идемпотентная уборка);
|
||||
- гейт зелёный → атомарный claim `done` ПЕРВЫМ, и только победитель claim
|
||||
выполняет `_try_advance_stage` (advance + `enqueue_job` следующей стадии)
|
||||
РОВНО один раз; проигравший claim (поздний monitor / стартовый
|
||||
`requeue_running_jobs`) НЕ делает побочных эффектов (нет дубль-advance /
|
||||
дубль-enqueue);
|
||||
- гейт красный (monitor умер ДО git-push, артефакта нет) → НЕ выдумываем
|
||||
`done`, уходим в ветку «исход неуспешен» ниже.
|
||||
**Источник истины — гейт, не «exit0».**
|
||||
- `exit!=0`: ровно существующий контракт `_finalize_job` (классификация
|
||||
transient/permanent, `attempts<max` → `queued`, иначе `failed`+Telegram).
|
||||
- **Исход неизвестен (Tier-1 мёртвый pid без exit_code, или Tier-3 backstop):**
|
||||
не выдумываем `exit0`. Если `attempts < max_attempts` → `queued` (как
|
||||
`requeue_running_jobs`); если бюджет исчерпан → `failed` + Telegram-алерт.
|
||||
|
||||
**Restart-safe (FR-1.5, AC-5):** reaper стартует в `lifespan` ПОСЛЕ
|
||||
`requeue_running_jobs()`, поэтому при рестарте сначала отрабатывает стартовый
|
||||
requeue, а периодический reaper лишь добивает то, что возникнет позже; атомарный
|
||||
guard `status='running'` исключает двойную обработку.
|
||||
|
||||
### Р-2. Проактивный реклейм stale/dead merge-lease — функции в `merge_gate.py`
|
||||
|
||||
Логика lease живёт в одном месте (`merge_gate.py`). Добавляем:
|
||||
- `pid_alive(pid) -> bool` (never-raise; ошибка/`PermissionError` → считаем
|
||||
«жив», т.е. консервативно НЕ реклеймим — безопаснее не трогать).
|
||||
- `reclaim_stale_lease(repo) -> bool` — для репо из области (см. ниже): прочитать
|
||||
lease; освободить (`release_merge_lease(repo, branch=holder_branch)` —
|
||||
holder-aware), если держатель **мёртв** (`pid` из lease не жив) ИЛИ **просрочен**
|
||||
(`age >= merge_lock_timeout_s`). Живой держатель в пределах TTL — НЕ трогать
|
||||
(AC-8, защита легитимного merge). Каждый реклейм → `logger.warning` +
|
||||
Telegram.
|
||||
|
||||
**Точки вызова (FR-2.1):**
|
||||
- на старте — в `lifespan` рядом с `requeue_running_jobs()`;
|
||||
- периодически — из тика reaper (один общий фоновый поток на оба механизма A и B).
|
||||
|
||||
**Условность (FR-2.4, AC-9):** реально только для `merge_gate_repos`/self-hosting
|
||||
(тот же предикат, что merge-gate); прочие репо — no-op. Kill-switch
|
||||
`lease_reclaim_enabled` (=false → остаётся лишь прежний ленивый TTL-реклейм в
|
||||
`acquire_merge_lease`). Контракт **never-raise**: ошибка реклейма логируется и не
|
||||
валит поток.
|
||||
|
||||
**pid-семантика lease:** lease пишет pid процесса ОРКЕСТРАТОРА (`os.getpid()`).
|
||||
После рестарта контейнера старый pid мёртв → детектируется. Риск pid-reuse
|
||||
(контейнер мог переиспользовать номер pid) закрыт тем, что реклейм срабатывает по
|
||||
**ИЛИ** (pid мёртв **ИЛИ** TTL истёк): даже при ложном «жив» TTL добьёт lease
|
||||
(контракт ORCH-043 сохранён). См. 10-tech-risks.
|
||||
|
||||
### Р-3. Идемпотентная финализация merge (Проблема C) — re-drive + guard, без новой merge-логики
|
||||
|
||||
Per FR-3.3 — НЕ создаём дублирующую merge-логику. Восстановление обеспечивается
|
||||
**штатными путями**:
|
||||
- reaper доводит зомби-job до `queued` → стадия `deploy-staging`/`deploy`
|
||||
переисполняется и снова проходит `check_branch_mergeable` (merge-gate), ЛИБО
|
||||
reconciler доигрывает переход по зелёному гейту;
|
||||
- дорогие шаги не повторяются «вхолостую»: `branch_is_behind_main == False` → этап
|
||||
rebase+re-test пропускается (ветка уже догнана);
|
||||
- lease при повторе берётся заново — `acquire_merge_lease` уже идемпотентен для
|
||||
«held by self» по branch (FR-3.4).
|
||||
|
||||
**Идемпотентность у самого merge (FR-3.2, AC-11):** добавляем детерминированный
|
||||
never-raise guard `pr_already_merged(repo, branch) -> bool` (переиспользует
|
||||
существующий Gitea-клиент; запрос состояния PR). Путь слияния (deployer/merge)
|
||||
консультируется с этим guard ПЕРЕД повторным merge: PR уже слит → no-op (без
|
||||
второго merge и без ошибки). Это единственная новая «merge-related» функция — она
|
||||
не сливает, а лишь читает состояние, поэтому не нарушает «no duplicate merge
|
||||
logic».
|
||||
|
||||
### Р-4. Изменение схемы БД — `jobs.pid INTEGER` (lightweight migration)
|
||||
|
||||
Колонка добавляется идемпотентно через существующий `_ensure_column(conn, "jobs",
|
||||
"pid", "INTEGER")` в `init_db` (паттерн уже применяется к `jobs.transient_attempts`
|
||||
/ `jobs.available_at` — безопасно на live prod DB). `pid` проставляется в `_spawn`
|
||||
рядом с `run_id`/`started_at`. **Альтернатива без миграции отвергнута** (см.
|
||||
Альтернативы): только по `agent_runs.finished_at/exit_code` нельзя поймать
|
||||
зомби, у которого monitor умер ДО записи exit_code — а это и есть основной класс
|
||||
инцидента. `STAGE_TRANSITIONS`, `QG_CHECKS`, схема `agent_runs`, файл-схема lease —
|
||||
без изменений.
|
||||
|
||||
### Р-5. Конфигурация (`src/config.py`, env `ORCH_*`)
|
||||
|
||||
| Настройка | Назначение | Дефолт |
|
||||
|-----------|-----------|--------|
|
||||
| `reaper_enabled` | глобальный kill-switch job-reaper | `True` |
|
||||
| `reaper_interval_s` | период сканирования | `60` |
|
||||
| `reaper_dead_ticks` | подряд тиков мёртвого pid перед реапом (Tier-1) | `2` |
|
||||
| `reaper_max_running_s` | потолок `running` (Tier-3 backstop), > max agent_timeout+grace | `3600` |
|
||||
| `reaper_finalize_grace_s` | Tier-2 grace: сколько `exit_code` должен быть записан до реапа (> max окна финализации) | `300` |
|
||||
| `lease_reclaim_enabled` | kill-switch проактивного реклейма lease | `True` |
|
||||
| (reuse) `merge_lock_timeout_s` | TTL lease | `300` |
|
||||
| (reuse) `merge_gate_repos` | область применения lease-reclaim | как есть |
|
||||
|
||||
`false` → строго прежнее поведение (AC-14).
|
||||
|
||||
### Р-6. Наблюдаемость (`GET /queue`)
|
||||
|
||||
Блок `reaper` (образец `reconcile`/`post_deploy`): `enabled`, `interval`,
|
||||
`last_run_ts`, `reaped_total`, `last_reaped` (`{job_id, agent, outcome}`),
|
||||
`lease_reclaimed_total`. Каждый reap и lease-reclaim → `logger.warning` с
|
||||
идентификаторами (`job_id`, `run_id`, `pid`, `repo`, `branch`). reap→`failed` и
|
||||
lease-reclaim → Telegram (AC-16).
|
||||
|
||||
### Р-7. Lifespan (`src/main.py`)
|
||||
|
||||
Старт (после существующего `requeue_running_jobs()`):
|
||||
```
|
||||
init_db() # + _ensure_column(jobs, pid)
|
||||
... orphan-recovery (M-1) ...
|
||||
requeue_running_jobs()
|
||||
+ startup lease-reclaim # reclaim_stale_lease для merge_gate_repos
|
||||
worker.start()
|
||||
reconciler.start()
|
||||
+ reaper.start() # НОВЫЙ daemon-поток (A + периодический B)
|
||||
```
|
||||
Стоп (reverse): `reaper.stop()` → `reconciler.stop()` → `worker.stop()`.
|
||||
|
||||
## Альтернативы
|
||||
|
||||
- **Reaper как часть reconciler** — отвергнуто: смешивает stage-уровень и
|
||||
jobs-уровень, два разных kill-switch'а в одном тике, хуже изоляция отказов.
|
||||
- **Без `jobs.pid`, только эвристика `agent_runs` + потолок** — отвергнуто как
|
||||
основной механизм: не ловит зомби, чей monitor умер ДО записи `exit_code`
|
||||
(главный класс инцидента). Эвристика оставлена как Tier-2/Tier-3 поверх pid.
|
||||
- **БД-lock вместо файлового lease / внешний брокер очередей** — вне объёма
|
||||
(BRD §4), несоразмерно для single-node SQLite.
|
||||
- **Реаниматор фабрикует `exit0` и форсит `done`** — отвергнуто: ложный `done`
|
||||
без реальной работы (если git-push не случился). Выбран gate-driven advance:
|
||||
источник истины — канонический QG, не предположение об успехе.
|
||||
- **Новый статус `reaping` в enum `jobs.status`** — отвергнуто: меняет контракт
|
||||
статусов; атомарного guard `WHERE status='running'` достаточно.
|
||||
|
||||
## Последствия
|
||||
|
||||
**Плюсы:**
|
||||
- Зомби-job самовосстанавливается БЕЗ рестарта процесса → очередь не встаёт
|
||||
(групповой риск снят для всех проектов общего инстанса).
|
||||
- Залипший lease освобождается проактивно (старт + период), не дожидаясь TTL и
|
||||
чужого acquire.
|
||||
- Незавершённый merge докатывается штатным путём, идемпотентно; ручные шаги
|
||||
оператора устранены → снят технический блокер ORCH-54.
|
||||
- Контракты неизменны (`STAGE_TRANSITIONS`, `QG_CHECKS`, `check_*`, БАГ-8,
|
||||
exit-коды хука); один новый столбец через проверенный idempotent-паттерн.
|
||||
|
||||
**Минусы / ограничения:**
|
||||
- pid-liveness валиден в предположении ОДНОГО pid-namespace (агент — дочерний
|
||||
процесс оркестратора в том же контейнере). Multi-container/namespaced pid →
|
||||
pid-liveness ненадёжен; закрыто backstop'ом по времени и TTL. См. 10-tech-risks.
|
||||
- streak-счётчик in-memory best-effort: после рестарта он сбрасывается, но
|
||||
стартовый `requeue_running_jobs` покрывает рестарт-сценарий.
|
||||
- Tier-3 backstop консервативен (потолок > max timeout); очень долгий легитимный
|
||||
агент (близко к потолку) теоретически может быть реапнут — потолок выбран с
|
||||
большим запасом, чтобы этого не случалось (AC-3).
|
||||
|
||||
## Инварианты (НЕ нарушать)
|
||||
- Reaper/lease-reclaim НЕ рестартят/не роняют прод-контейнер `orchestrator` и НЕ
|
||||
инициируют git-push в `main` (AC-12). Реклейм lease — только удаление
|
||||
файла-lease, без git-операций.
|
||||
- `STAGE_TRANSITIONS`, реестр `QG_CHECKS`, сигнатуры/поведение `check_*` (в т.ч.
|
||||
`check_branch_mergeable`), БАГ-8 откат, exit-коды deploy-хука — без изменений;
|
||||
новых QG checks/стадий нет (AC-13).
|
||||
- never-raise на единицу фоновой работы; идемпотентность (атомарный guard +
|
||||
gate-driven advance); restart-safe; тишина при отсутствии аномалий.
|
||||
- Анти-ложноположительность (FR-1.3): живой долгий агент не реапится.
|
||||
|
||||
## Связи
|
||||
- Базируется на: ORCH-1 (очередь, adr-0002), ORCH-043 (merge-gate, adr-0006),
|
||||
ORCH-053 (reconciler-паттерн, adr-0007), ORCH-36 (self-deploy, adr-0007).
|
||||
- Сквозной ADR: adr-0011.
|
||||
- Разблокирует: ORCH-54 (полностью автономный self-deploy).
|
||||
42
docs/work-items/ORCH-065/07-infra-requirements.md
Normal file
42
docs/work-items/ORCH-065/07-infra-requirements.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# 07 — Требования к инфраструктуре (ORCH-065)
|
||||
|
||||
## Топология
|
||||
**Без изменений.** Новых контейнеров, портов, сетевых сервисов, внешних
|
||||
зависимостей нет. Job-reaper — ещё один фоновый daemon-поток ВНУТРИ существующего
|
||||
процесса оркестратора (как `queue_worker` и `reconciler`), стартует/останавливается
|
||||
в `main.lifespan`. Деплой/рестарт прод-контейнера в рамках задачи НЕ требуется и
|
||||
ЗАПРЕЩЁН (self-hosting safety) — выкатка через штатный `deploy-staging → deploy`.
|
||||
|
||||
## Допущение pid-namespace (важно для liveness-детекции)
|
||||
- Агент запускается как `subprocess.Popen(["bash","-c",cmd])` — **дочерний
|
||||
процесс оркестратора в ТОМ ЖЕ pid-namespace** (один контейнер). Значит
|
||||
`os.kill(jobs.pid, 0)` корректно отражает liveness агента, пока жив сам
|
||||
оркестратор. Это инвариант текущей упаковки (один контейнер на инстанс).
|
||||
- Lease пишет `pid = os.getpid()` — pid ПРОЦЕССА ОРКЕСТРАТОРА. После рестарта
|
||||
контейнера старый pid мёртв → детектируется. Риск переиспользования номера pid
|
||||
новым процессом закрыт условием «pid мёртв **ИЛИ** TTL истёк»: TTL добивает
|
||||
lease в любом случае (контракт ORCH-043 сохранён).
|
||||
- **Если в будущем агенты переедут в отдельные контейнеры/namespace** — Tier-1
|
||||
pid-liveness станет ненадёжной; тогда полагаемся на Tier-2 (exit_code) и Tier-3
|
||||
(потолок `reaper_max_running_s`). Зафиксировано в 10-tech-risks.
|
||||
|
||||
## Поведение при self-restart (ORCH-36 executable self-deploy)
|
||||
Self-restart прод-контейнера во время `deploy` — ровно тот сценарий, что плодит
|
||||
зомби: monitor-поток умирает вместе со старым контейнером. После рестарта:
|
||||
1. стартовый `requeue_running_jobs()` + стартовый `reclaim_stale_lease` чистят
|
||||
состояние, оставшееся от убитого процесса;
|
||||
2. периодический reaper добивает то, что возникнет позже без рестарта.
|
||||
Reaper/lease-reclaim сами НИКОГДА не рестартят и не роняют прод-контейнер и не
|
||||
делают git-push в `main` (AC-12).
|
||||
|
||||
## Эксплуатационные ручки (env, хост `.env`/`.env.staging`)
|
||||
`ORCH_REAPER_ENABLED`, `ORCH_REAPER_INTERVAL_S`, `ORCH_REAPER_DEAD_TICKS`,
|
||||
`ORCH_REAPER_MAX_RUNNING_S`, `ORCH_LEASE_RECLAIM_ENABLED`; переиспользуются
|
||||
`ORCH_MERGE_LOCK_TIMEOUT_S`, `ORCH_MERGE_GATE_REPOS`. Все флаги документируются в
|
||||
`.env.example` (developer-стадия). Полное отключение (`false`) → строго прежнее
|
||||
поведение.
|
||||
|
||||
## Документация эксплуатации
|
||||
`docs/operations/INFRA.md` — добавить (best-effort, developer/PR) короткое
|
||||
упоминание поведения reaper/lease-reclaim при self-restart. Топологическая карта
|
||||
INFRA.md не меняется.
|
||||
29
docs/work-items/ORCH-065/08-data-requirements.md
Normal file
29
docs/work-items/ORCH-065/08-data-requirements.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# 08 — Требования к данным (ORCH-065)
|
||||
|
||||
## Изменение схемы: `jobs.pid`
|
||||
|
||||
| Поле | Значение |
|
||||
|------|----------|
|
||||
| Таблица | `jobs` |
|
||||
| Колонка | `pid` |
|
||||
| Тип | `INTEGER` (nullable, без DEFAULT) |
|
||||
| Назначение | pid агентского процесса (`subprocess.Popen.pid` из `launcher._spawn`) для liveness-детекции зомби job-reaper'ом (Tier-1) |
|
||||
| Механизм миграции | `_ensure_column(conn, "jobs", "pid", "INTEGER")` в `db.init_db` — идемпотентно, no-op если колонка уже есть |
|
||||
| Безопасность на live prod DB | ДА. Тот же паттерn уже применён к `jobs.transient_attempts`, `jobs.available_at`, `events.delivery_id`, `agent_runs.*`. `ALTER TABLE ADD COLUMN` в SQLite — мгновенная метаданная-операция, не блокирует и не переписывает строки |
|
||||
| Заполнение | в `_spawn` рядом с существующим `UPDATE jobs SET run_id=?, started_at=datetime('now') WHERE id=?` добавить `pid=?` (`proc.pid`). Старые строки остаются `pid IS NULL` → для них Tier-1 неприменим, работают Tier-2/Tier-3 |
|
||||
|
||||
## Что НЕ меняется
|
||||
- `STAGE_TRANSITIONS`, реестр `QG_CHECKS` — без изменений (это контракты).
|
||||
- Схема `agent_runs` — без изменений (`finished_at`/`exit_code` уже есть — основа Tier-2).
|
||||
- Файл-схема merge-lease `.merge-lease-<repo>.json` — без изменений (`pid`,
|
||||
`acquired_at`, `branch`, `work_item_id`, `task_id` уже пишутся
|
||||
`acquire_merge_lease`).
|
||||
- `jobs.status` enum (`queued|running|done|failed`) — без изменений; новый статус
|
||||
`reaping` НЕ вводится (атомарного guard `WHERE status='running'` достаточно).
|
||||
|
||||
## Совместимость / откат
|
||||
- Откат миграции не требуется: лишняя nullable-колонка безвредна при
|
||||
`reaper_enabled=false`.
|
||||
- `pid IS NULL` (строки до миграции, или если запись pid не успела) → reaper не
|
||||
делает Tier-1, опирается на Tier-2 (exit_code) и Tier-3 (потолок). Поведение
|
||||
деградирует gracefully, ложноположительных реапов не возникает.
|
||||
22
docs/work-items/ORCH-065/10-tech-risks.md
Normal file
22
docs/work-items/ORCH-065/10-tech-risks.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# 10 — Технические риски (ORCH-065)
|
||||
|
||||
| # | Риск | Вероятн. | Влияние | Митигация |
|
||||
|---|------|----------|---------|-----------|
|
||||
| R-1 | **Ложноположительный реап живого долгого агента** (AC-3). Reaper помечает зомби работающий агент → потеря работы, дубль-запуск. | Сред. | Высокое | Tier-1 требует `reaper_dead_ticks`(≥2) подряд тиков мёртвого pid; живой pid = `os.kill(pid,0)` без `ProcessLookupError`. Tier-3 потолок `reaper_max_running_s` выбирается заведомо > max `agent_timeout`+grace. Юнит-тест TC-02/TC-03. |
|
||||
| R-2 | **Ложный `done` без выполненной работы.** Reaper при exit0-зомби помечает job done, хотя git-push/advance не случились (monitor умер до них). | Сред. | Высокое | Реап exit0 НЕ форсит done напрямую — идёт через **gate-driven** `_try_advance_stage`: канонический QG проверяет наличие артефакта/PR; нет артефакта → красный гейт → НЕ advance → ветка «исход неуспешен» (requeue). Источник истины — гейт, не «exit0». |
|
||||
| R-3 | **pid-reuse / namespace.** Номер pid переиспользован новым процессом → ложное «жив» (lease не реклеймится; зомби-job не реапится по Tier-1). | Низк. | Сред. | Lease: условие «pid мёртв **ИЛИ** TTL истёк» — TTL добивает в любом случае. Job-reaper: Tier-3 backstop по времени ловит то, что Tier-1 пропустил. Допущение «один pid-namespace» зафиксировано в 07-infra. |
|
||||
| R-4 | **Гонка reaper vs поздно доехавший monitor / стартовый `requeue_running_jobs`** → двойная обработка строки. | Сред. | Сред. | Атомарный reap-claim `UPDATE ... WHERE id=? AND status='running'` + проверка `rowcount` (образец `claim_next_job`). Reaper стартует ПОСЛЕ `requeue_running_jobs` в lifespan. Юнит-тест TC-06. |
|
||||
| R-5 | **Реклейм живого lease** → параллельный конфликтный merge, риск красного `main` self-hosting. | Низк. | Высокое | `reclaim_stale_lease` освобождает ТОЛЬКО при «держатель мёртв ИЛИ TTL истёк»; живой держатель в пределах TTL не трогается. holder-aware `release_merge_lease(repo, branch)`. Юнит-тест TC-12. |
|
||||
| R-6 | **Реклейм инициирует git-операцию / трогает прод-контейнер** (нарушение self-hosting safety, AC-12). | Низк. | Высокое | Реклейм = только удаление файла-lease (`os.remove`), без git. Reaper не вызывает деплой-хук/рестарт. Явный инвариант в ADR + тест/ревью. |
|
||||
| R-7 | **Идемпотентность merge не достигнута**: повторный проход стадии делает второй merge уже слитого PR. | Сред. | Сред. | never-raise guard `pr_already_merged(repo,branch)` (читает состояние PR) консультируется перед merge → уже слит = no-op. `branch_is_behind_main==False` пропускает rebase+re-test. Юнит-тест TC-16, интеграция TC-17. |
|
||||
| R-8 | **streak-счётчик in-memory теряется при рестарте** → задержка реапа или сброс прогресса. | Низк. | Низкое | Рестарт-сценарий покрыт стартовым `requeue_running_jobs` (мгновенно чистит running). Периодический reaper нужен лишь для зомби БЕЗ рестарта; сброс счётчика лишь переоткладывает реап на `reaper_dead_ticks` тиков. |
|
||||
| R-9 | **never-raise нарушен** — необработанное исключение валит daemon-поток reaper → защита тихо отключается. | Низк. | Сред. | Per-job изоляция `try/except` (образец `reconciler.reconcile_gate_once`) + внешний `try/except` в `_run`. Юнит-тест TC-08/TC-14. |
|
||||
| R-10 | **Регресс существующих тестов** merge_gate/queue/reconciler/deploy. | Низк. | Сред. | Контракты неизменны (`STAGE_TRANSITIONS`/`QG_CHECKS`/`check_*`/exit-коды хука); только новая колонка + новый поток + флаги (дефолт сохраняет поведение). Полный прогон `pytest tests/ -q` (regression в 04-test-plan). |
|
||||
|
||||
## Открытые вопросы / follow-up
|
||||
- **Полная автоматизация merge-финализации.** Если деплой-merge (deployer/ORCH-36
|
||||
detached host-process) окажется не полностью идемпотентным к повторному проходу,
|
||||
может понадобиться доп. работа поверх `pr_already_merged`. Здесь закрываем
|
||||
технический блокер; полный авто-approve деплоя — ORCH-54.
|
||||
- Допущение «агенты — дочерние процессы в одном pid-namespace» (R-3) должно быть
|
||||
пересмотрено, если упаковка агентов изменится (отдельные контейнеры).
|
||||
70
docs/work-items/ORCH-065/12-review.md
Normal file
70
docs/work-items/ORCH-065/12-review.md
Normal file
@@ -0,0 +1,70 @@
|
||||
---
|
||||
type: review
|
||||
work_item_id: ORCH-065
|
||||
verdict: APPROVED
|
||||
version: 3
|
||||
---
|
||||
|
||||
# Review ORCH-065
|
||||
|
||||
## Summary
|
||||
|
||||
Задача закрывает три связанных класса отказов «процесс/поток умер, а ресурс остался
|
||||
захваченным навсегда»: zombie jobs (A), залипший merge-lease (B), неидемпотентная
|
||||
финализация merge (C). Реализация качественная: новый daemon-поток `src/job_reaper.py`
|
||||
по образцу `reconciler` (never-raise, kill-switch, снимок в `/queue`), трёхуровневая
|
||||
liveness, атомарный `reap_running_job(... WHERE status='running')`, проактивный реклейм
|
||||
lease (`pid_alive` + `reclaim_stale_lease`), идемпотентный guard `pr_already_merged`,
|
||||
колонка `jobs.pid` через идемпотентный `_ensure_column`.
|
||||
|
||||
**Все блокеры предыдущих ревью устранены:**
|
||||
- v1 P0 (guard `pr_already_merged` не подключён к merge-пути) — устранён `aa46e5d`:
|
||||
промпт `.openclaw/agents/deployer.md` консультирует `pr_already_merged` ПЕРЕД любым
|
||||
(повторным) merge (AC-11 wiring на месте, подтверждено строками 94–105/152).
|
||||
- v2 P1 (Tier-2 реапит живой финализирующий monitor; side-effects ДО атомарного claim,
|
||||
нарушение ADR-001 Р-1) — устранён `3e2eb27` двумя мерами:
|
||||
1. **Tier-2 finalization grace** — новая колонка `finished_age_s` в `get_running_jobs`
|
||||
(`src/db.py:609`) + настройка `reaper_finalize_grace_s` (дефолт 300с); Tier-2
|
||||
реапит только при `finished_age >= grace`, иначе строка не трогается
|
||||
(`src/job_reaper.py:197-209`). Живой финализирующий monitor больше не реапится
|
||||
(FR-1.3/AC-3).
|
||||
2. **claim-before-act** — `_reap_exit0` (`src/job_reaper.py:242-286`) сначала оценивает
|
||||
канонический QG read-only (`_gate_is_green` → `_run_qg`, без побочных эффектов),
|
||||
затем атомарно claim `done` ПЕРВЫМ, и только победитель claim выполняет
|
||||
`_gate_driven_advance`. Проигравший гонку (поздний monitor / стартовый requeue) не
|
||||
делает НИКАКИХ побочных эффектов → нет дубль-advance/дубль-enqueue (FR-1.2/AC-4).
|
||||
- v2 P3 (битая ссылка на adr-0011 в CHANGELOG) — исправлена в `3e2eb27`
|
||||
(`adr-0011-job-reaper-lease-reclaim.md`).
|
||||
|
||||
Инварианты сохранены (AC-13): ORCH-065-коммиты (`1a2e881`/`aa46e5d`/`3e2eb27`) НЕ касаются
|
||||
`src/stages.py` и `src/qg/checks.py` — `STAGE_TRANSITIONS`/`QG_CHECKS`/`check_*`/БАГ-8/
|
||||
exit-коды хука не тронуты; реклейм lease — только удаление файла, без git-операций
|
||||
(AC-12). Документация (README, internals, ADR-001, глобальный adr-0011, CHANGELOG,
|
||||
.env.example) обновлена в этом же PR (AC-17). Новые тесты покрывают grace-окно,
|
||||
lost-claim-no-side-effects, already-advanced-идемпотентность. `pytest tests/ -q` —
|
||||
**747 passed**.
|
||||
|
||||
## Findings
|
||||
|
||||
### P0 — Blocker
|
||||
- нет
|
||||
|
||||
### P1 — Must fix
|
||||
- нет
|
||||
|
||||
### P2 — Should fix
|
||||
- нет
|
||||
|
||||
### P3 — Nice to have
|
||||
- нет
|
||||
|
||||
## Документация
|
||||
|
||||
Обновлена корректно и в этом же PR (AC-17 PASS): `docs/architecture/README.md`
|
||||
(раздел про job-reaper + lease-reclaim, таблицы БД и `/queue`),
|
||||
`docs/architecture/internals.md`, `docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md`
|
||||
(+ запись в `adr/README.md`),
|
||||
`docs/work-items/ORCH-065/06-adr/ADR-001-job-reaper-and-lease-reclaim.md`, `CHANGELOG.md`
|
||||
(ссылка на adr-0011 исправлена), `.env.example` (флаги `ORCH_REAPER_*` /
|
||||
`ORCH_REAPER_FINALIZE_GRACE_S` / `ORCH_LEASE_RECLAIM_ENABLED`). ADR-001 Р-1 и реализация
|
||||
exit0-пути теперь согласованы (claim-before-act).
|
||||
92
docs/work-items/ORCH-065/13-test-report.md
Normal file
92
docs/work-items/ORCH-065/13-test-report.md
Normal file
@@ -0,0 +1,92 @@
|
||||
---
|
||||
type: test-report
|
||||
work_item_id: ORCH-065
|
||||
result: PASS
|
||||
---
|
||||
|
||||
# Test Report — ORCH-065
|
||||
|
||||
Тема: job-reaper + проактивный реклейм stale/dead merge-lease + идемпотентная
|
||||
финализация merge. Прогон полного регресса в ветке
|
||||
`feature/ORCH-065-bug-zombie-jobs-merge-lease-ru`. Review-вердикт — APPROVED (v3).
|
||||
|
||||
## Окружение
|
||||
- Python: 3.12.13
|
||||
- pytest: 8.3.3
|
||||
- Ветка: feature/ORCH-065-bug-zombie-jobs-merge-lease-ru (worktree)
|
||||
- Прод (8500): health `200 {"status":"ok"}` — НЕ перезапускался (self-hosting инвариант соблюдён)
|
||||
- Дата: 2026-06-07
|
||||
|
||||
## Smoke API (прод 8500, read-only)
|
||||
| Endpoint | Результат |
|
||||
|----------|-----------|
|
||||
| `GET /health` | 200 `{"status":"ok","service":"orchestrator"}` |
|
||||
| `GET /status` | 200, активные задачи отдаются (ORCH-065 в `testing`, ET-013 в `development`) |
|
||||
| `GET /queue` | 200, counts/resilience/reconcile/post_deploy присутствуют |
|
||||
|
||||
Примечание: блок `reaper` в `/queue` прода (8500) ОТСУТСТВУЕТ — ожидаемо, т.к. прод
|
||||
исполняет ещё не задеплоенный (до-ORCH-065) код. Контракт блока `reaper` проверен
|
||||
тестом TC-18 (`tests/test_queue.py::test_tc18_queue_endpoint_has_reaper_block`)
|
||||
против кода ветки — PASS. Curl недоступен в окружении, smoke выполнен через
|
||||
`urllib.request` (read-only, без побочных эффектов на прод).
|
||||
|
||||
## Результаты по тест-плану (04-test-plan.yaml)
|
||||
|
||||
| TC ID | Тип | Модуль | Покрывает | Результат |
|
||||
|-------|-----|--------|-----------|-----------|
|
||||
| TC-01 | unit | test_job_reaper.py | AC-1 (реап мёртвого job без рестарта) | PASS |
|
||||
| TC-02 | unit | test_job_reaper.py | AC-3 (живой агент не реапится) | PASS |
|
||||
| TC-03 | unit | test_job_reaper.py | FR-1.3 (устойчивость reaper_dead_ticks) | PASS |
|
||||
| TC-04 | unit | test_job_reaper.py | FR-1.1/AC-1 (backstop reaper_max_running_s) | PASS |
|
||||
| TC-05 | unit | test_job_reaper.py | AC-4 (исход по результату: done/queued/failed) | PASS |
|
||||
| TC-06 | unit | test_job_reaper.py | AC-5 (атомарность reap-UPDATE guard) | PASS |
|
||||
| TC-07 | unit | test_job_reaper.py | AC-14 (kill-switch reaper_enabled=false) | PASS |
|
||||
| TC-08 | unit | test_job_reaper.py | AC-9 (never-raise per-job) | PASS |
|
||||
| TC-09 | integration | test_queue.py | AC-2 (разблокировка очереди concurrency=1) | PASS |
|
||||
| TC-10 | unit | test_merge_lease_reclaim.py | AC-6 (реклейм lease мёртвого pid) | PASS |
|
||||
| TC-11 | unit | test_merge_lease_reclaim.py | AC-7 (реклейм по TTL сохранён) | PASS |
|
||||
| TC-12 | unit | test_merge_lease_reclaim.py | AC-8 (живой lease не трогается) | PASS |
|
||||
| TC-13 | unit | test_merge_lease_reclaim.py | AC-9 (условность self-hosting/no-op) | PASS |
|
||||
| TC-14 | unit | test_merge_lease_reclaim.py | AC-9 (never-raise при ошибке lease-файла) | PASS |
|
||||
| TC-15 | unit | test_merge_lease_reclaim.py | AC-14 (kill-switch lease_reclaim_enabled=false) | PASS |
|
||||
| TC-16 | unit | test_merge_gate.py | AC-11 (идемпотентность при уже слитом PR) | PASS |
|
||||
| TC-17 | integration | test_merge_gate_race.py | AC-10 (докатывание незавершённого merge) | PASS |
|
||||
| TC-18 | integration | test_queue.py | AC-15 (блок reaper в /queue) | PASS |
|
||||
| TC-19 | unit | test_config.py | AC-13 (контракты STAGE_TRANSITIONS/QG_CHECKS неизменны) | PASS |
|
||||
| TC-20 | unit | test_config.py | §5/AC-14 (новые настройки reaper_*/lease_reclaim_*) | PASS |
|
||||
| TC-21 | unit | test_job_reaper.py | FR-2.1/AC-6 (стартовый реклейм в lifespan) | PASS |
|
||||
|
||||
Все 21 TC из плана — PASS.
|
||||
|
||||
## Сопоставление с критериями приёмки (03-acceptance-criteria.md)
|
||||
- A (AC-1…AC-5): job-reaper — покрыты TC-01..TC-06, TC-09 → PASS
|
||||
- B (AC-6…AC-9): lease-reclaim — покрыты TC-10..TC-15 → PASS
|
||||
- C (AC-10, AC-11): идемпотентная финализация — TC-16, TC-17 → PASS
|
||||
- D (AC-12 прод не трогается, AC-13 контракты, AC-14 kill-switches): TC-07, TC-15, TC-19, TC-20 + smoke прода без рестарта → PASS
|
||||
- E (AC-15 /queue, AC-16 логи/алерты): TC-18 → PASS
|
||||
- F (AC-17 документация): review подтвердил обновление README/internals/ADR-001/adr-0011/CHANGELOG/.env.example (APPROVED) → PASS
|
||||
- G (AC-18 регресс зелёный): `pytest tests/` 747 passed → PASS
|
||||
|
||||
## Вывод pytest
|
||||
|
||||
### Целевые модули плана
|
||||
```
|
||||
$ python -m pytest tests/test_job_reaper.py tests/test_merge_lease_reclaim.py \
|
||||
tests/test_merge_gate.py tests/test_merge_gate_race.py \
|
||||
tests/test_queue.py tests/test_config.py -q
|
||||
92 passed, 1 warning in 3.40s
|
||||
```
|
||||
|
||||
### Полный регресс
|
||||
```
|
||||
$ python -m pytest tests/ -v --tb=short
|
||||
======================= 747 passed, 1 warning in 15.47s ========================
|
||||
```
|
||||
(1 warning — PydanticDeprecatedSince20 в src/config.py, не связан с ORCH-065,
|
||||
предсуществующий.)
|
||||
|
||||
## Итог
|
||||
**PASS.** Полный регресс — 747 passed, 0 failed. Все 21 TC тест-плана зелёные,
|
||||
все критерии приёмки (AC-1…AC-18) подтверждены. Smoke прода — health/status/queue
|
||||
200 OK, прод-контейнер не перезапускался (self-hosting инвариант соблюдён).
|
||||
Задача готова к переходу на стадию `deploy-staging`.
|
||||
32
docs/work-items/ORCH-065/15-staging-log.md
Normal file
32
docs/work-items/ORCH-065/15-staging-log.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
staging_status: SUCCESS
|
||||
timestamp: 2026-06-07T16:13:48Z
|
||||
base_url: http://localhost:8501
|
||||
---
|
||||
|
||||
# Staging Gate Log
|
||||
|
||||
Staging test suite completed against the live staging environment (8501),
|
||||
run canonically inside the `orchestrator-staging` container (ORCH-048, ADR-001).
|
||||
|
||||
**Verdict:** SUCCESS — `staging_check.py` exited **0**. All REAL (pipeline)
|
||||
checks green; the only failures are the two known sandbox-infra checks
|
||||
(C9a/C9b), which are waived per ORCH-061 because every REAL check passed.
|
||||
|
||||
## Result
|
||||
|
||||
- RESULT: 8/10 checks PASS
|
||||
- REAL failed: none
|
||||
- SANDBOX_INFRA failed (waived): C9a Branch appears in orchestrator-sandbox; C9b Analyst job enqueued in staging queue
|
||||
|
||||
INFRA-WAIVED: C9a Branch appears in orchestrator-sandbox, C9b Analyst job enqueued in staging queue (known sandbox-infra; real checks green)
|
||||
VERDICT: SUCCESS (exit 0) — SUCCESS (infra-waived): ['C9a Branch appears in orchestrator-sandbox', 'C9b Analyst job enqueued in staging queue'] are known sandbox-infra checks; all real checks green
|
||||
|
||||
## Block detail
|
||||
|
||||
- [Block A] SMOKE — A1 /health, A2 /queue, A3 ORCH_STAGING=true → PASS
|
||||
- [Block B] ACCESS — B4 Plane sandbox, B5 Gitea orchestrator-sandbox (push=true), B6 registry isolation (sandbox present, prod ET/ORCH absent) → PASS
|
||||
- [Block C] E2E (stub) — C7 create issue in SANDBOX, C8 trigger pipeline via /webhook/plane → PASS; C9a/C9b → FAIL (sandbox-infra, waived)
|
||||
- CLEANUP — Plane issue deleted (HTTP 204)
|
||||
|
||||
tolerance: staging_infra_tolerance_enabled=True
|
||||
7
docs/work-items/ORCH-066/00-business-request.md
Normal file
7
docs/work-items/ORCH-066/00-business-request.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# Business Request: [высокий] Статусная модель Plane: осмысленные статусы этапов
|
||||
|
||||
Work Item ID: ORCH-066
|
||||
|
||||
## Description
|
||||
|
||||
TBD
|
||||
110
docs/work-items/ORCH-066/01-brd.md
Normal file
110
docs/work-items/ORCH-066/01-brd.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# 01 — Business Requirements Document (BRD)
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
**Заголовок:** [высокий] Статусная модель Plane: осмысленные статусы этапов
|
||||
**Стадия:** analysis
|
||||
**Автор:** Analyst
|
||||
**Дата:** 2026-06-07
|
||||
|
||||
---
|
||||
|
||||
## 1. Контекст и проблема
|
||||
|
||||
Статусная модель Plane оркестратора имеет **семантические перегрузки**: один и тот
|
||||
же Plane-статус используется для несовместимых смыслов, из-за чего:
|
||||
|
||||
- оператор не понимает, на каком реально этапе стоит задача (доска нечитаема);
|
||||
- повышается риск ошибки оператора (например, неверный ручной перевод статуса);
|
||||
- `In Progress` одновременно означает «человек запускает конвейер», «идёт анализ»,
|
||||
«идёт прод-деплой» и «возврат из Needs Input» — четыре разных смысла на одном статусе.
|
||||
|
||||
Уже частично исправлено: ORCH-059 ввёл отдельный статус для подтверждения деплоя
|
||||
(`Confirm Deploy`), разгрузив перегруженный `Approved`. ORCH-066 завершает наведение
|
||||
порядка по **утверждённой Owner** статусной модели.
|
||||
|
||||
### Два слоя (критично различать)
|
||||
|
||||
| Слой | Что это | Источник | Трогаем? |
|
||||
|------|---------|----------|----------|
|
||||
| **A** | `STAGE_TRANSITIONS` — внутренняя машина стадий (`created→analysis→…→done`) | `src/stages.py` | **НЕТ (инвариант)** |
|
||||
| **B** | Plane-статусы — индикация на доске | `src/plane_sync.py` + точки в `src/stage_engine.py` / `src/webhooks/plane.py` | **ДА** |
|
||||
|
||||
ORCH-066 меняет **только слой B** и точки, где код вручную проставляет Plane-статусы.
|
||||
|
||||
---
|
||||
|
||||
## 2. Целевая статусная модель (решение Owner)
|
||||
|
||||
```
|
||||
Backlog → Todo → [To Analyse] → Analysis → [In Review → Approved] → Architecture →
|
||||
Development → Code-Review → Testing → Awaiting Deploy → [Confirm Deploy] → Deploying →
|
||||
Monitoring after Deploy → Done
|
||||
```
|
||||
|
||||
- `[...]` = **действие человека** (вход-триггер).
|
||||
- Остальное ставит **орк** (индикация).
|
||||
|
||||
### Ветки (нелинейные исходы)
|
||||
- **Rejected** — откат на предыдущую стадию (человек).
|
||||
- **Needs Input** — ТОЛЬКО аналитик (НЕ расширять на других агентов).
|
||||
- **Blocked** — затык / фейл деплоя / деградация прода.
|
||||
- **Cancelled** — человек решил не делать задачу (валидный выход из In Review).
|
||||
|
||||
---
|
||||
|
||||
## 3. Бизнес-требования
|
||||
|
||||
| ID | Требование | Приоритет |
|
||||
|----|------------|-----------|
|
||||
| **BR-1** | Каждый этап конвейера показывается на доске Plane осмысленным статусом (To Analyse / Analysis / Code-Review / Awaiting Deploy / Deploying / Monitoring after Deploy). | Must |
|
||||
| **BR-2** | `To Analyse` — единый человеческий вход: (а) старт нового конвейера, (б) resume/relaunch аналитика при возврате из Needs Input. Заменяет роль `In Progress` как входа-триггера. | Must |
|
||||
| **BR-3** | Стадия `analysis` индицируется отдельным статусом `Analysis` (орк ставит при старте/relaunch аналитика), а не `In Progress`. | Must |
|
||||
| **BR-4** | Стадия `review` индицируется Plane-статусом `Code-Review` (переименование `Review`). | Must |
|
||||
| **BR-5** | Self-deploy Phase A (approval-pending) ставит `Awaiting Deploy` вместо `In Review`. | Must |
|
||||
| **BR-6** | Self-deploy Phase B (старт прод-деплоя) ставит `Deploying`. | Must |
|
||||
| **BR-7** | Self-deploy Phase C (health-OK финализация) ставит `Monitoring after Deploy` (НЕ `Done` сразу). | Must |
|
||||
| **BR-8** | Post-deploy monitor (ORCH-021): чистое закрытие окна (HEALTHY) → `Done`; UNHEALTHY/деградация → `Blocked`. | Must |
|
||||
| **BR-9** | `In Review` разгрузить: оставить ТОЛЬКО за approve-pending артефактов конвейера (BRD/ревью). Выходы: `Approved` (вперёд), `Rejected` (откат), `Cancelled` (человек отменил). | Must |
|
||||
| **BR-10** | `Needs Input` — БЕЗ ИЗМЕНЕНИЙ. Остаётся только у аналитика (`01-questions.md` → `set_issue_needs_input`). Механизм не трогать. | Must |
|
||||
| **BR-11** | Возврат аналитика из Needs Input выполняется через `To Analyse` (а НЕ через `In Progress`). Логика fork «старт vs resume» (по наличию task + active-job) сохраняется. | Must (грабли R1) |
|
||||
| **BR-12** | **Fail-closed:** отсутствие нового статуса в проекте (enduro / Plane API down / fallback `_DEFAULT_STATES`) НЕ приводит к падению; поведение остаётся backward-compatible (паттерн ORCH-059 AC-7). | Must |
|
||||
| **BR-13** | Reconciler не «оживляет» активные ожидания (`Awaiting Deploy` / `Deploying` / `Monitoring after Deploy`) как зависшие задачи (Guard 2 skip-list). | Must |
|
||||
| **BR-14** | Документация (golden source) обновлена в том же PR: `CLAUDE.md`, `docs/architecture/README.md`, `CHANGELOG.md`, ADR per-work-item. | Must |
|
||||
|
||||
---
|
||||
|
||||
## 4. Границы (Out of Scope / НЕ трогать)
|
||||
|
||||
- `STAGE_TRANSITIONS` (`src/stages.py`) — машина стадий, инвариант.
|
||||
- `QG_CHECKS`, `check_deploy_status`, exit-коды хука (0/1/2), merge-gate, схема БД.
|
||||
- `Confirm Deploy` (уже работает, ORCH-059).
|
||||
- Механизм `Needs Input` (analyst-only) — не расширять, не менять.
|
||||
- Поведение прод-деплоя **не-self** репозиториев (enduro-trails): для них терминальный
|
||||
переход остаётся `deploy → Done` как сейчас (Monitoring after Deploy не применяется —
|
||||
post-deploy monitor армится только для self-hosting).
|
||||
- Автоматический approve / авто-rollback self-hosting (ORCH-54 / ORCH-021 политика
|
||||
ALERT_ONLY) — не меняется.
|
||||
|
||||
---
|
||||
|
||||
## 5. Инфра-предусловие (вне кода, делает оператор)
|
||||
|
||||
Новые Plane-статусы в проекте **ORCH** создаёт оператор через Plane API **ДО** эксплуатации:
|
||||
`To Analyse`, `Analysis`, `Code-Review`, `Awaiting Deploy`, `Deploying`,
|
||||
`Monitoring after Deploy` (`Confirm Deploy` уже есть).
|
||||
|
||||
Резолвер (`_PLANE_NAME_TO_KEY` + `get_project_states`) подхватывает их **по имени** с
|
||||
**fail-closed fallback** на `_DEFAULT_STATES` (см. BR-12). Документируется в
|
||||
`07-infra-requirements.md` (создаёт архитектор) и в `docs/operations/`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Definition of Done
|
||||
|
||||
- Plane показывает осмысленные статусы на каждом этапе.
|
||||
- Возврат аналитика из Needs Input работает через `To Analyse`.
|
||||
- Phase A → `Awaiting Deploy`, Phase B → `Deploying`, Phase C → `Monitoring after Deploy`,
|
||||
окно HEALTHY → `Done`, фейл → `Blocked`.
|
||||
- `STAGE_TRANSITIONS` не изменён.
|
||||
- `pytest tests/ -q` — зелёный. Fail-closed покрыт тестами.
|
||||
- Документация обновлена.
|
||||
178
docs/work-items/ORCH-066/02-trz.md
Normal file
178
docs/work-items/ORCH-066/02-trz.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# 02 — Техническое задание (ТЗ)
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
**Стадия:** analysis → (вход для architecture)
|
||||
**Автор:** Analyst
|
||||
|
||||
> ТЗ фиксирует ТРЕБУЕМОЕ ПОВЕДЕНИЕ и затронутые точки кода. Конкретную архитектуру
|
||||
> резолвера (точные имена ключей/функций) финализирует архитектор в ADR. Ниже —
|
||||
> опорный контракт, согласованный с бизнес-запросом Owner.
|
||||
|
||||
---
|
||||
|
||||
## 1. Задействованные модули `src/`
|
||||
|
||||
| Модуль | Роль в задаче |
|
||||
|--------|---------------|
|
||||
| `src/plane_sync.py` | **Ядро изменений (слой B):** реестр логических статусов (`_DEFAULT_STATES`), `_PLANE_NAME_TO_KEY`, маппинг стадия→статус (`_STAGE_TO_STATE_KEY`, `STAGE_VISIBILITY_STATE`), хелперы `set_issue_*`. |
|
||||
| `src/webhooks/plane.py` | Маршрутизация входящего статуса (`handle_issue_updated`): `To Analyse` → `handle_status_start` (старт **или** resume). |
|
||||
| `src/stage_engine.py` | Точки ручной простановки статуса: analyst-flow (`Analysis`/`Needs Input`/`In Review`), Phase A (`Awaiting Deploy`), Phase B (`Deploying`), Phase C → `Monitoring after Deploy`, post-deploy monitor → `Done`/`Blocked`. |
|
||||
| `src/reconciler.py` | F-2 запрос статусов (`To Analyse` в список), Guard 2 skip-list (активные ожидания). |
|
||||
| `src/stages.py` | **НЕ менять** (инвариант слоя A). Используется только для чтения переходов. |
|
||||
| `src/config.py` | (При необходимости) kill-switch для новой статусной модели — на усмотрение архитектора (см. §6). |
|
||||
|
||||
---
|
||||
|
||||
## 2. Изменения статусной модели (слой B)
|
||||
|
||||
### 2.1. Реестр логических статусов (`src/plane_sync.py`)
|
||||
|
||||
Ввести новые **логические ключи** и их имена в `_PLANE_NAME_TO_KEY`:
|
||||
|
||||
| Логический ключ | Plane name | Назначение |
|
||||
|-----------------|-----------|------------|
|
||||
| `to_analyse` | `To Analyse` | Вход-триггер (старт + resume аналитика). |
|
||||
| `analysis` | `Analysis` | Индикация стадии analysis (орк). |
|
||||
| `code_review` | `Code-Review` | Индикация стадии review (орк). Заменяет `review`. |
|
||||
| `awaiting_deploy` | `Awaiting Deploy` | Phase A approval-pending (орк). |
|
||||
| `deploying` | `Deploying` | Phase B прод-деплой идёт (орк). |
|
||||
| `monitoring` | `Monitoring after Deploy` | Phase C / post-deploy окно (орк). |
|
||||
|
||||
Сохранить существующие: `backlog`, `todo`, `in_progress` (backward-compat), `needs_input`,
|
||||
`in_review`, `blocked`, `done`, `cancelled`, `architecture`, `development`, `testing`,
|
||||
`approved`, `rejected`. `Cancelled` уже присутствует в `_PLANE_NAME_TO_KEY`.
|
||||
|
||||
### 2.2. Fail-closed резолюция (КРИТИЧНО — BR-12)
|
||||
|
||||
`get_project_states()` после резолва по API делает `setdefault(k, v)` из `_DEFAULT_STATES`.
|
||||
Чтобы отсутствие нового статуса в проекте (enduro / Plane down / частичная конфигурация)
|
||||
**не ломало** конвейер, новые логические ключи в `_DEFAULT_STATES` должны
|
||||
**алиаситься на существующие UUID** (degrade-to-current):
|
||||
|
||||
| Новый ключ | Default-алиас (UUID) | Деградированное поведение |
|
||||
|------------|----------------------|---------------------------|
|
||||
| `to_analyse` | = `in_progress` | enduro/старый проект: `In Progress` по-прежнему триггерит старт/resume. |
|
||||
| `analysis` | = `in_progress` | analysis показывается как `In Progress` (как сейчас). |
|
||||
| `code_review` | = `review` | review показывается как `Review` (как сейчас). |
|
||||
| `awaiting_deploy` | = `in_review` | Phase A показывается как `In Review` (как сейчас). |
|
||||
| `deploying` | = `in_progress` | Phase B показывается как `In Progress` (как сейчас). |
|
||||
| `monitoring` | = `done` | Phase C показывается как `Done` (как сейчас); монитор затем держит Done / флипает Blocked. |
|
||||
|
||||
> Эффект: если оператор НЕ создал новый статус — система работает строго как до ORCH-066
|
||||
> (никаких падений, никаких 404 от Plane PATCH). Если создал — резолвится по имени и
|
||||
> используется новый UUID. Это ровно паттерн ORCH-059 AC-7.
|
||||
|
||||
### 2.3. Маппинг стадия → статус
|
||||
|
||||
`src/plane_sync.py`:
|
||||
- `_STAGE_TO_STATE_KEY`: `analysis` → `analysis` (было `in_progress`); `review` → `code_review`
|
||||
(было `review`). `deploy` остаётся (управляется Phase A/B/C напрямую, не через
|
||||
`update_issue_state`). `created`/`architecture`/`development`/`testing`/`done` — без изменений.
|
||||
- `STAGE_VISIBILITY_STATE`: `review` → `code_review` (было `review`). Добавить
|
||||
`analysis` → `analysis`, если индикация analysis ставится через `set_issue_stage_state`
|
||||
(решает архитектор; альтернатива — отдельный хелпер `set_issue_analysis`).
|
||||
- Сохранить совместимость `STAGE_TO_STATE` / `PLANE_STATES` алиасов (импортируются тестами).
|
||||
|
||||
### 2.4. Точки простановки статуса
|
||||
|
||||
| Место (файл:симв.) | Сейчас | Должно стать |
|
||||
|--------------------|--------|--------------|
|
||||
| `webhooks/plane.py` `handle_issue_updated` | `new_state == in_progress` → `handle_status_start` | `new_state == to_analyse` (с fail-closed: при алиасе совпадает с `in_progress`) → `handle_status_start` |
|
||||
| `webhooks/plane.py` `start_pipeline` (старт) | статус остаётся `In Progress` | при старте/enqueue analyst орк ставит `Analysis` |
|
||||
| `webhooks/plane.py` `handle_status_start` (resume из Needs Input) | relaunch на `In Progress`-триггере | relaunch на `To Analyse`-триггере; при relaunch орк ставит `Analysis`. Fork «старт vs resume» (по `get_task_by_plane_id` + `has_active_job_for_task`) — **сохранить как есть.** |
|
||||
| `stage_engine.py` `_handle_analysis_approved_flow` (artifacts ready) | `set_issue_in_review` | оставить `In Review` (BR-9: In Review только за approve-pending конвейера) ✔ без изменений |
|
||||
| `stage_engine.py` `_handle_analysis_approved_flow` (questions) | `set_issue_needs_input` | **без изменений** (BR-10) |
|
||||
| `stage_engine.py` `_handle_self_deploy_phase_a` | `set_issue_in_review` | `Awaiting Deploy` (`set_issue_awaiting_deploy` или аналог) |
|
||||
| `stage_engine.py` `_handle_self_deploy_phase_b` | (статус не меняет) | `Deploying` |
|
||||
| `stage_engine.py` advance `deploy → done` (terminal-sync, строка ~338) | `set_issue_done` для всех | **self-hosting:** `Monitoring after Deploy` (перед/вместо арма монитора); **не-self:** `Done` как сейчас |
|
||||
| `stage_engine.py` `run_post_deploy_monitor` (HEALTHY, окно закрыто) | пишет лог + коммент, статус Plane НЕ трогает (остаётся Done) | `Done` (явно) |
|
||||
| `stage_engine.py` `run_post_deploy_monitor` (DEGRADED) | пишет лог + alert | `Blocked` |
|
||||
|
||||
> **Замечание по terminal-sync (важно для архитектора):** сейчас `advance_stage` на
|
||||
> `next_stage == "done"` вызывает `set_issue_done` безусловно (строка ~338), затем армит
|
||||
> post-deploy monitor для self-hosting (~361). Нужно развести: для репо, где
|
||||
> `post_deploy.post_deploy_applies(repo)` истинно (self-hosting) — ставить `Monitoring
|
||||
> after Deploy` вместо `Done`, и переложить простановку `Done`/`Blocked` на финал
|
||||
> монитора (`run_post_deploy_monitor`). Для прочих репо — `Done` как сейчас.
|
||||
|
||||
### 2.5. Новые хелперы `src/plane_sync.py`
|
||||
|
||||
Добавить тонкие обёртки по образцу `set_issue_in_review` (резолв per-project UUID +
|
||||
`_set_issue_state_direct`), never-raise при отсутствии issue:
|
||||
- `set_issue_analysis(work_item_id, project_id=None)`
|
||||
- `set_issue_code_review(...)` (или через `set_issue_stage_state("review")`)
|
||||
- `set_issue_awaiting_deploy(...)`
|
||||
- `set_issue_deploying(...)`
|
||||
- `set_issue_monitoring(...)`
|
||||
|
||||
(Точный набор/именование — на усмотрение архитектора; контракт: per-project резолв +
|
||||
fail-closed.)
|
||||
|
||||
---
|
||||
|
||||
## 3. Изменения reconciler (`src/reconciler.py`)
|
||||
|
||||
- **F-2** `_reconcile_plane_project`: добавить `to_analyse` в список запрашиваемых
|
||||
статусов (`list_issues_by_state([... , to_analyse])`) и в `_reconcile_plane_issue`
|
||||
маршрутизировать `new_state == to_analyse` → `handle_status_start` (старт при `task is
|
||||
None`, resume при существующем task без active-job — логика уже в `handle_status_start`).
|
||||
Сохранить обработку `approved`/`rejected`. При fail-closed алиасе `to_analyse==in_progress`
|
||||
поведение не дублируется (один и тот же UUID).
|
||||
- **Guard 2** `_is_blocked_or_needs_input` (F-1 skip): расширить skip-множество активными
|
||||
ожиданиями — `awaiting_deploy`, `deploying`, `monitoring` — чтобы реконсилер НЕ
|
||||
«оживлял» их как зависшие (BR-13). Имя метода/семантику можно обобщить
|
||||
(«human-or-active-wait»), флаг `reconcile_skip_blocked_enabled` продолжает управлять
|
||||
этим networked-чеком.
|
||||
|
||||
> Примечание: F-1 и так не тронет Phase A (`check_deploy_status` red → silent),
|
||||
> Deploying (active finalizer job), Monitoring (стадия `done`). Guard 2 — явная
|
||||
> defense-in-depth по требованию Owner.
|
||||
|
||||
---
|
||||
|
||||
## 4. Изменения API / эндпоинтов
|
||||
|
||||
**Нет** новых HTTP-эндпоинтов. `GET /queue` / `GET /status` — без изменений контракта
|
||||
(статусы Plane там не отражаются). Изменения только во внешней индикации Plane (PATCH
|
||||
issue state — существующий механизм).
|
||||
|
||||
---
|
||||
|
||||
## 5. Изменения схемы БД
|
||||
|
||||
**Нет.** `tasks` не хранит Plane-статус (источник истины — стадия в БД + Plane API).
|
||||
Миграции не требуются.
|
||||
|
||||
---
|
||||
|
||||
## 6. Требования к новым QG checks
|
||||
|
||||
**Нет.** `QG_CHECKS` не расширяется. Статусы — индикация, не управление (канон:
|
||||
машинные вердикты читаются из YAML-frontmatter артефактов, не из Plane-статуса).
|
||||
|
||||
Опционально (на усмотрение архитектора): единый kill-switch новой статусной модели
|
||||
(env-флаг) для безопасного раската, по образцу `staging_infra_tolerance_enabled` /
|
||||
`reconcile_skip_blocked_enabled`. Не обязателен, т.к. fail-closed алиасинг (§2.2) уже даёт
|
||||
backward-compatible деградацию.
|
||||
|
||||
---
|
||||
|
||||
## 7. Артефакты pipeline, создаваемые/обновляемые
|
||||
|
||||
- `06-adr/ADR-001-plane-status-model.md` — архитектор (решение по резолверу,
|
||||
алиасингу, разводке terminal-sync).
|
||||
- `07-infra-requirements.md` — архитектор (список Plane-статусов для ручного создания
|
||||
оператором + Plane API инструкция).
|
||||
- Документация (golden source, тот же PR): `CLAUDE.md` (секция статусной модели),
|
||||
`docs/architecture/README.md` (секция статусов рядом с ORCH-036/ORCH-021),
|
||||
`CHANGELOG.md`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Инварианты (проверяемые)
|
||||
|
||||
- `src/stages.py` `STAGE_TRANSITIONS` — байт-в-байт без изменений.
|
||||
- `QG_CHECKS`, `check_deploy_status`/`_parse_deploy_status`, exit-коды хука, merge-gate,
|
||||
схема БД, `Confirm Deploy`, механизм `Needs Input` — без изменений.
|
||||
- Все новые `set_issue_*` / резолв — never-raise (Plane down ⇒ degrade, не crash).
|
||||
- Поведение enduro (не-self) и его терминальный `Done` — без регресса.
|
||||
71
docs/work-items/ORCH-066/03-acceptance-criteria.md
Normal file
71
docs/work-items/ORCH-066/03-acceptance-criteria.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# 03 — Критерии приёмки (Acceptance Criteria)
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
|
||||
Каждый критерий — чёткое условие PASS/FAIL. Покрытие тестами — см. `04-test-plan.yaml`.
|
||||
|
||||
---
|
||||
|
||||
## Группа A — Вход и стадия анализа
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-1** | `To Analyse` запускает конвейер | Перевод issue без task в `To Analyse` → `handle_status_start` → `start_pipeline` (создаётся task, ветка, enqueue analyst). | Не запускается / запускается на другом статусе. |
|
||||
| **AC-2** | `To Analyse` делает resume аналитика из Needs Input | Существующий task без active-job + перевод в `To Analyse` → relaunch агента текущей стадии (analyst читает свежие комменты). Fork «старт vs resume» определяется по `get_task_by_plane_id` + `has_active_job_for_task` (как раньше). | Создаётся второй task / двойной запуск / resume не происходит. |
|
||||
| **AC-3** | Стадия `analysis` индицируется статусом `Analysis` | При старте/relaunch аналитика орк ставит `Analysis`. | Остаётся `In Progress` (при наличии статуса `Analysis` в проекте). |
|
||||
| **AC-4** | Busy-guard сохранён | `To Analyse` при существующем active-job для task → НЕ relaunch (no double launch). | Двойной запуск агента. |
|
||||
|
||||
## Группа B — Code-Review
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-5** | Стадия `review` индицируется `Code-Review` | Вход в стадию `review` → Plane-статус `Code-Review`. | Остаётся `Review` (при наличии нового статуса). |
|
||||
|
||||
## Группа C — Self-deploy фазы
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-6** | Phase A → `Awaiting Deploy` | `_handle_self_deploy_phase_a` ставит `Awaiting Deploy` (не `In Review`). | Ставит `In Review` (при наличии нового статуса). |
|
||||
| **AC-7** | Phase B → `Deploying` | `_handle_self_deploy_phase_b` при успешном `initiate_deploy` ставит `Deploying`. | Статус не меняется / иной. |
|
||||
| **AC-8** | Phase C → `Monitoring after Deploy` (self) | Финализатор SUCCESS для self-hosting → статус `Monitoring after Deploy`, НЕ `Done` сразу. | Ставит `Done` немедленно (для self-hosting). |
|
||||
| **AC-9** | Не-self deploy → `Done` без регресса | Для не-self репо (`post_deploy_applies==False`) терминальный `deploy → done` ставит `Done` как сейчас. | Не-self репо получает `Monitoring after Deploy` / иной регресс. |
|
||||
|
||||
## Группа D — Post-deploy monitor
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-10** | Чистое окно → `Done` | `run_post_deploy_monitor` HEALTHY + окно исчерпано → статус `Done`. | Остаётся `Monitoring after Deploy` / иной. |
|
||||
| **AC-11** | Деградация → `Blocked` | `run_post_deploy_monitor` DEGRADED → статус `Blocked` (+ существующий ALERT_ONLY для self). | Остаётся в Monitoring / ставит Done. |
|
||||
| **AC-12** | Self-hosting монитор не рестартит прод | Тик НИКОГДА не рестартит/откатывает прод-контейнер (ORCH-021 BR-5 сохранён). | Тик трогает прод-контейнер. |
|
||||
|
||||
## Группа E — In Review / Needs Input / ветки
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-13** | `In Review` только за approve-pending конвейера | `In Review` ставится лишь для approve артефактов (analyst BRD/ревью), не для Phase A. | Phase A / иные стадии ставят `In Review`. |
|
||||
| **AC-14** | `Needs Input` без изменений | Поведение `set_issue_needs_input` (analyst `01-questions.md`) идентично прежнему; не расширено на других агентов. | Механизм изменён / расширен. |
|
||||
| **AC-15** | `Cancelled` — валидный выход из In Review без действий конвейера | Перевод в `Cancelled` → орк не выполняет advance/rollback (индикация, не управление). | Орк совершает действие конвейера на `Cancelled`. |
|
||||
|
||||
## Группа F — Fail-closed (КРИТИЧНО)
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-16** | Отсутствие нового статуса не ломает конвейер | Проект без новых статусов (enduro/частичный/Plane down) → `get_project_states` отдаёт default-алиасы; все `set_issue_*`/триггеры работают backward-compatible, без исключений и без 404 PATCH. | Падение / необработанное исключение / зависание задачи. |
|
||||
| **AC-17** | enduro `In Progress` по-прежнему стартует конвейер | Через `to_analyse`-алиас (= `in_progress` UUID) перевод enduro-issue в `In Progress` запускает старт/resume. | enduro-старт сломан. |
|
||||
| **AC-18** | Резолв по имени | При наличии статуса в проекте по `name` (`_PLANE_NAME_TO_KEY`) используется его UUID, а не default-алиас. | Используется неверный UUID. |
|
||||
|
||||
## Группа G — Reconciler
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-19** | F-2 реконсилирует `To Analyse` | `_reconcile_plane_project` запрашивает `to_analyse` и маршрутизирует к `handle_status_start` (старт/resume при потерянном webhook). | `To Analyse`-старты не реконсилируются. |
|
||||
| **AC-20** | Guard 2 skip активных ожиданий | Задачи в `Awaiting Deploy` / `Deploying` / `Monitoring after Deploy` НЕ «оживляются» F-1 как зависшие. | Реконсилер advance'ит активное ожидание. |
|
||||
|
||||
## Группа H — Инварианты и документация
|
||||
|
||||
| ID | Критерий | PASS | FAIL |
|
||||
|----|----------|------|------|
|
||||
| **AC-21** | `STAGE_TRANSITIONS` не изменён | `src/stages.py` `STAGE_TRANSITIONS` идентичен (diff пуст). | Любое изменение слоя A. |
|
||||
| **AC-22** | Реестры/контракты не изменены | `QG_CHECKS`, `check_deploy_status`, exit-коды хука, merge-gate, схема БД, `Confirm Deploy` — без изменений. | Любое изменение перечисленного. |
|
||||
| **AC-23** | Тесты зелёные | `pytest tests/ -q` проходит полностью; новые fail-closed тесты присутствуют и зелёные. | Любой красный тест. |
|
||||
| **AC-24** | Документация обновлена (golden source) | `CLAUDE.md`, `docs/architecture/README.md`, `CHANGELOG.md` обновлены; заведён `06-adr/ADR-001-*`. | Любой из артефактов не обновлён. |
|
||||
184
docs/work-items/ORCH-066/04-test-plan.yaml
Normal file
184
docs/work-items/ORCH-066/04-test-plan.yaml
Normal file
@@ -0,0 +1,184 @@
|
||||
work_item: ORCH-066
|
||||
description: >
|
||||
Тест-план статусной модели Plane (слой B). Покрывает осмысленные статусы этапов,
|
||||
возврат аналитика через To Analyse, фазы self-deploy, post-deploy monitor,
|
||||
fail-closed деградацию и reconciler. Слой A (STAGE_TRANSITIONS) проверяется на
|
||||
неизменность. Все тесты — pytest; Plane API мокается (httpx), как в существующих
|
||||
tests/test_plane_*.py / tests/test_orch10_states.py.
|
||||
|
||||
tests:
|
||||
# --- Группа A: вход и стадия анализа ---
|
||||
- id: TC-01
|
||||
type: unit
|
||||
description: "To Analyse без существующего task -> handle_status_start -> start_pipeline (старт конвейера)."
|
||||
module: tests/test_status_trigger.py
|
||||
covers: [AC-1]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-02
|
||||
type: integration
|
||||
description: "To Analyse при существующем task без active-job -> relaunch агента стадии (resume из Needs Input), новый task НЕ создаётся."
|
||||
module: tests/test_plane_to_analyse_resume.py
|
||||
covers: [AC-2, BR-11]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-03
|
||||
type: unit
|
||||
description: "Старт/relaunch аналитика ставит Plane-статус Analysis (а не In Progress) при наличии статуса в проекте."
|
||||
module: tests/test_plane_status_model.py
|
||||
covers: [AC-3]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-04
|
||||
type: unit
|
||||
description: "To Analyse при существующем task с active-job -> НЕ relaunch (busy-guard)."
|
||||
module: tests/test_plane_to_analyse_resume.py
|
||||
covers: [AC-4]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа B: Code-Review ---
|
||||
- id: TC-05
|
||||
type: unit
|
||||
description: "Вход в стадию review -> Plane-статус Code-Review (маппинг _STAGE_TO_STATE_KEY / STAGE_VISIBILITY_STATE)."
|
||||
module: tests/test_plane_status_model.py
|
||||
covers: [AC-5]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа C: self-deploy фазы ---
|
||||
- id: TC-06
|
||||
type: unit
|
||||
description: "_handle_self_deploy_phase_a ставит Awaiting Deploy (не In Review)."
|
||||
module: tests/test_deploy_approve.py
|
||||
covers: [AC-6, AC-13]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-07
|
||||
type: unit
|
||||
description: "_handle_self_deploy_phase_b при успешном initiate_deploy ставит Deploying."
|
||||
module: tests/test_deploy_approve.py
|
||||
covers: [AC-7]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-08
|
||||
type: integration
|
||||
description: "Phase C (finalizer SUCCESS) для self-hosting ставит Monitoring after Deploy, НЕ Done; армит post-deploy monitor."
|
||||
module: tests/test_deploy_terminal_sync.py
|
||||
covers: [AC-8]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-09
|
||||
type: integration
|
||||
description: "Не-self репо: deploy->done ставит Done (без регресса, Monitoring не применяется)."
|
||||
module: tests/test_deploy_terminal_sync.py
|
||||
covers: [AC-9]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа D: post-deploy monitor ---
|
||||
- id: TC-10
|
||||
type: unit
|
||||
description: "run_post_deploy_monitor HEALTHY + окно исчерпано -> Plane-статус Done."
|
||||
module: tests/test_post_deploy.py
|
||||
covers: [AC-10]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-11
|
||||
type: unit
|
||||
description: "run_post_deploy_monitor DEGRADED -> Plane-статус Blocked (+ ALERT_ONLY для self)."
|
||||
module: tests/test_post_deploy.py
|
||||
covers: [AC-11]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-12
|
||||
type: unit
|
||||
description: "Self-hosting тик НЕ рестартит/не откатывает прод-контейнер (ORCH-021 BR-5 сохранён)."
|
||||
module: tests/test_post_deploy.py
|
||||
covers: [AC-12]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа E: In Review / Needs Input / Cancelled ---
|
||||
- id: TC-13
|
||||
type: unit
|
||||
description: "In Review ставится только за approve-pending конвейера (analyst BRD ready), не Phase A."
|
||||
module: tests/test_analyst_status_only_regression.py
|
||||
covers: [AC-13]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-14
|
||||
type: unit
|
||||
description: "set_issue_needs_input (analyst 01-questions.md) поведение идентично прежнему; не расширено на других агентов."
|
||||
module: tests/test_plane_status_model.py
|
||||
covers: [AC-14, BR-10]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-15
|
||||
type: unit
|
||||
description: "Перевод в Cancelled -> handle_issue_updated не выполняет advance/rollback (индикация, не управление)."
|
||||
module: tests/test_plane_webhook.py
|
||||
covers: [AC-15]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа F: fail-closed (критично) ---
|
||||
- id: TC-16
|
||||
type: unit
|
||||
description: "Проект без новых статусов: get_project_states отдаёт default-алиасы (to_analyse=in_progress, code_review=review, awaiting_deploy=in_review, monitoring=done); исключений нет."
|
||||
module: tests/test_plane_status_failclosed.py
|
||||
covers: [AC-16, BR-12]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-17
|
||||
type: unit
|
||||
description: "Plane API down -> get_project_states fallback на _DEFAULT_STATES; set_issue_* never-raise."
|
||||
module: tests/test_plane_status_failclosed.py
|
||||
covers: [AC-16]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-18
|
||||
type: integration
|
||||
description: "enduro In Progress по-прежнему стартует конвейер через to_analyse-алиас."
|
||||
module: tests/test_plane_status_failclosed.py
|
||||
covers: [AC-17]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-19
|
||||
type: unit
|
||||
description: "Резолв по имени: при наличии статуса в проекте используется его UUID, а не default-алиас."
|
||||
module: tests/test_orch10_states.py
|
||||
covers: [AC-18]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа G: reconciler ---
|
||||
- id: TC-20
|
||||
type: integration
|
||||
description: "F-2 _reconcile_plane_project запрашивает to_analyse и маршрутизирует к handle_status_start (потерянный webhook старта/resume)."
|
||||
module: tests/test_reconciler_plane.py
|
||||
covers: [AC-19]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-21
|
||||
type: unit
|
||||
description: "Guard 2: задачи в Awaiting Deploy / Deploying / Monitoring after Deploy НЕ оживляются F-1 как зависшие."
|
||||
module: tests/test_reconciler.py
|
||||
covers: [AC-20, BR-13]
|
||||
expected: PASS
|
||||
|
||||
# --- Группа H: инварианты ---
|
||||
- id: TC-22
|
||||
type: unit
|
||||
description: "STAGE_TRANSITIONS не изменён (явная проверка ключей/значений слоя A)."
|
||||
module: tests/test_plane_status_model.py
|
||||
covers: [AC-21]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-23
|
||||
type: unit
|
||||
description: "QG_CHECKS реестр и check_deploy_status контракты не изменены."
|
||||
module: tests/test_plane_status_model.py
|
||||
covers: [AC-22]
|
||||
expected: PASS
|
||||
|
||||
- id: TC-24
|
||||
type: integration
|
||||
description: "Полный прогон pytest tests/ -q зелёный (регрессия)."
|
||||
module: tests/
|
||||
covers: [AC-23]
|
||||
expected: PASS
|
||||
287
docs/work-items/ORCH-066/06-adr/ADR-001-plane-status-model.md
Normal file
287
docs/work-items/ORCH-066/06-adr/ADR-001-plane-status-model.md
Normal file
@@ -0,0 +1,287 @@
|
||||
# ADR-001: Осмысленная статусная модель Plane (слой B)
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
**Стадия:** architecture
|
||||
**Автор:** Architect
|
||||
**Дата:** 2026-06-07
|
||||
**Статус:** Accepted
|
||||
|
||||
> Контракт резолвера, алиасинга и разводки точек простановки статуса. Опирается на
|
||||
> BRD (`01-brd.md`), ТЗ (`02-trz.md`), критерии приёмки (`03-acceptance-criteria.md`).
|
||||
> Инфра-предусловие (статусы, создаваемые оператором) — `07-infra-requirements.md`,
|
||||
> риски — `10-tech-risks.md`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Контекст
|
||||
|
||||
Plane-доска оркестратора семантически перегружена: `In Progress` одновременно
|
||||
означает «человек запускает конвейер», «идёт анализ», «идёт прод-деплой» и «возврат
|
||||
из Needs Input». Оператор не различает реальный этап задачи → риск ошибочного ручного
|
||||
перевода статуса. ORCH-059 уже разгрузил `Approved` отдельным `Confirm Deploy`;
|
||||
ORCH-066 завершает наведение порядка по утверждённой Owner модели.
|
||||
|
||||
**Жёсткое разделение двух слоёв (инвариант проекта):**
|
||||
|
||||
| Слой | Что | Источник | ORCH-066 |
|
||||
|------|-----|----------|----------|
|
||||
| **A** | `STAGE_TRANSITIONS` — машина стадий | `src/stages.py` | **НЕ трогаем** |
|
||||
| **B** | Plane-статусы — индикация на доске | `src/plane_sync.py` + точки простановки | **меняем только это** |
|
||||
|
||||
Статус — **индикация, не управление**. Машинные вердикты по-прежнему читаются только
|
||||
из YAML-frontmatter артефактов (канон гейтов). Конвейер движут гейты слоя A; смена
|
||||
Plane-статуса не может продвинуть/откатить задачу (кроме существующих человеческих
|
||||
триггеров `To Analyse`/`Approved`/`Rejected`, которые и раньше были входами).
|
||||
|
||||
Целевая модель Owner:
|
||||
|
||||
```
|
||||
Backlog → Todo → [To Analyse] → Analysis → [In Review → Approved] → Architecture →
|
||||
Development → Code-Review → Testing → Awaiting Deploy → [Confirm Deploy] → Deploying →
|
||||
Monitoring after Deploy → Done
|
||||
```
|
||||
`[...]` = действие человека (вход-триггер); остальное ставит орк (индикация).
|
||||
Ветки: **Rejected** (откат), **Needs Input** (только аналитик), **Blocked** (затык/фейл
|
||||
деплоя/деградация), **Cancelled** (человек отменил задачу).
|
||||
|
||||
---
|
||||
|
||||
## 2. Решение
|
||||
|
||||
### 2.1. Реестр логических статусов (`src/plane_sync.py`)
|
||||
|
||||
Вводим 6 новых **логических ключей**. Имена в `_PLANE_NAME_TO_KEY` (резолв по имени из
|
||||
Plane API):
|
||||
|
||||
| Логический ключ | Plane name | Назначение |
|
||||
|-----------------|-----------|------------|
|
||||
| `to_analyse` | `To Analyse` | Вход-триггер: старт нового конвейера **и** resume аналитика из Needs Input. |
|
||||
| `analysis` | `Analysis` | Индикация стадии analysis (орк). |
|
||||
| `code_review` | `Code-Review` | Индикация стадии review (орк). Заменяет `review` как видимый статус. |
|
||||
| `awaiting_deploy` | `Awaiting Deploy` | Phase A approval-pending (орк). |
|
||||
| `deploying` | `Deploying` | Phase B прод-деплой идёт (орк). |
|
||||
| `monitoring` | `Monitoring after Deploy` | Phase C / post-deploy окно (орк). |
|
||||
|
||||
Существующие ключи сохраняются: `backlog`, `todo`, `in_progress`, `needs_input`,
|
||||
`in_review`, `blocked`, `done`, `cancelled`, `architecture`, `development`, `review`,
|
||||
`testing`, `approved`, `rejected`. `Cancelled` уже присутствует.
|
||||
|
||||
### 2.2. Fail-closed резолюция — **project-relative alias-fallback** (КРИТИЧНО, BR-12)
|
||||
|
||||
ТЗ §2.2 предложил статические алиасы на enduro-UUID в `_DEFAULT_STATES`. Архитектурное
|
||||
уточнение: для **частично сконфигурированного** проекта (оператор создал не все новые
|
||||
статусы) статический enduro-UUID в orchestrator-проекте даст невалидный `state` → PATCH
|
||||
422/404. Поэтому деградация делается **относительно того же проекта**, а не на чужой
|
||||
UUID.
|
||||
|
||||
**Два уровня fallback в `get_project_states()` (success-path), строго в порядке:**
|
||||
|
||||
1. Резолв по имени из Plane API (как сейчас).
|
||||
2. **Alias-fallback (новый):** для каждого отсутствующего нового ключа — UUID его
|
||||
**базового ключа из этого же проекта**:
|
||||
|
||||
```python
|
||||
_STATE_ALIAS_FALLBACK = {
|
||||
"to_analyse": "in_progress",
|
||||
"analysis": "in_progress",
|
||||
"code_review": "review",
|
||||
"awaiting_deploy": "in_review",
|
||||
"deploying": "in_progress",
|
||||
"monitoring": "done",
|
||||
}
|
||||
# после резолва по имени, ДО _DEFAULT_STATES.setdefault:
|
||||
for new_key, base_key in _STATE_ALIAS_FALLBACK.items():
|
||||
if new_key not in resolved and resolved.get(base_key):
|
||||
resolved[new_key] = resolved[base_key]
|
||||
```
|
||||
3. `_DEFAULT_STATES.setdefault(...)` (как сейчас) — последний резерв для путей, где
|
||||
API недоступен целиком (`if not project_id: return _DEFAULT_STATES`, полный провал
|
||||
запроса). В `_DEFAULT_STATES` новые ключи ТОЖЕ добавляются (= enduro-UUID базового
|
||||
ключа), чтобы любой caller всегда получал полный словарь и `states[key]` не кидал
|
||||
`KeyError`.
|
||||
|
||||
**Эффект деградации:**
|
||||
|
||||
| Сценарий | Поведение |
|
||||
|----------|-----------|
|
||||
| Orchestrator: все новые статусы созданы | резолв по имени → новые UUID (целевая модель). |
|
||||
| Orchestrator: создана ЧАСТЬ новых статусов | отсутствующие → **собственный** базовый UUID проекта → индикация деградирует до текущего статуса, PATCH валиден. |
|
||||
| Enduro (новые статусы не создаются никогда) | alias-fallback → собственные enduro базовые UUID → строго прежнее поведение (`In Progress`/`Review`/`Done`). |
|
||||
| Plane API down целиком | `_DEFAULT_STATES` (enduro-UUID) — без регресса относительно сегодняшнего поведения. |
|
||||
|
||||
Это паттерн ORCH-059 AC-7, усиленный project-relative разрешением. Все `set_issue_*` и
|
||||
`_set_issue_state_direct` остаются **never-raise** (PATCH-исключение логируется, не
|
||||
пробрасывается) — индикация деградирует, слой A не затрагивается.
|
||||
|
||||
### 2.3. Маппинг стадия → статус
|
||||
|
||||
- `_STAGE_TO_STATE_KEY` (живой путь `update_issue_state`→`stage_to_state`):
|
||||
`analysis` → `analysis` (было `in_progress`); `review` → `code_review` (было `review`).
|
||||
`deploy` остаётся `in_progress` (управляется Phase A/B/C напрямую). Остальные — без
|
||||
изменений.
|
||||
- `STAGE_VISIBILITY_STATE`: `review` → `code_review`; добавить `analysis` → `analysis`
|
||||
(для консистентности; `set_issue_stage_state` сейчас dormant, но карта обновляется).
|
||||
- `STAGE_TO_STATE` (legacy/test-only) — обновить `analysis`→`_DEFAULT_STATES["analysis"]`,
|
||||
`review`→`_DEFAULT_STATES["code_review"]`. UUID-значения **байт-в-байт прежние** (это
|
||||
алиасы на те же in_progress/review UUID) → тесты на конкретные UUID не краснеют.
|
||||
|
||||
### 2.4. Новые хелперы `src/plane_sync.py`
|
||||
|
||||
Тонкие обёртки по образцу `set_issue_in_review` (per-project резолв + `_set_issue_state_direct`,
|
||||
never-raise):
|
||||
|
||||
- `set_issue_analysis(work_item_id, project_id=None)`
|
||||
- `set_issue_code_review(work_item_id, project_id=None)`
|
||||
- `set_issue_awaiting_deploy(work_item_id, project_id=None)`
|
||||
- `set_issue_deploying(work_item_id, project_id=None)`
|
||||
- `set_issue_monitoring(work_item_id, project_id=None)`
|
||||
|
||||
`get_project_states` всегда возвращает полный словарь (см. §2.2), поэтому `[key]` не
|
||||
кидает `KeyError`.
|
||||
|
||||
### 2.5. Точки простановки статуса (разводка)
|
||||
|
||||
| Файл:место | Сейчас | Должно стать | AC |
|
||||
|------------|--------|--------------|----|
|
||||
| `webhooks/plane.py` `handle_issue_updated` | `new_state == in_progress` → `handle_status_start` | `new_state == to_analyse` → `handle_status_start` (при алиасе совпадает с `in_progress`) | AC-1, AC-17 |
|
||||
| `webhooks/plane.py` `start_pipeline` (успешный старт) | статус остаётся `In Progress` | в конце старта орк ставит `set_issue_analysis` | AC-3 |
|
||||
| `webhooks/plane.py` `handle_status_start` (resume-ветка) | relaunch агента стадии | при relaunch орк ставит `set_issue_analysis`; fork «старт vs resume» (`get_task_by_plane_id` + `has_active_job_for_task`) — **без изменений** | AC-2, AC-4 |
|
||||
| `webhooks/plane.py` `_rollback_stage` (reject@analysis, ~583) | `set_issue_in_progress` | `set_issue_analysis` | AC-3 |
|
||||
| `stage_engine.py` `_handle_analysis_approved_flow` (artifacts ready) | `set_issue_in_review` | **без изменений** (BR-9) | AC-13 |
|
||||
| `stage_engine.py` `_handle_analysis_approved_flow` (questions) | `set_issue_needs_input` | **без изменений** (BR-10) | AC-14 |
|
||||
| `stage_engine.py` rollback@analysis (architect conflict, ~669) | `set_issue_in_progress` | `set_issue_analysis` | AC-3 |
|
||||
| `stage_engine.py` `_handle_self_deploy_phase_a` (~1012) | `set_issue_in_review` | `set_issue_awaiting_deploy` | AC-6, AC-13 |
|
||||
| `stage_engine.py` `_handle_self_deploy_phase_b` (после `INITIATED` marker) | статус не меняет | `set_issue_deploying` | AC-7 |
|
||||
| `stage_engine.py` terminal-sync `deploy → done` (~338) | `set_issue_done` для всех | **self (`post_deploy_applies`):** `set_issue_monitoring`; **не-self:** `set_issue_done` как сейчас | AC-8, AC-9 |
|
||||
| `stage_engine.py` `run_post_deploy_monitor` HEALTHY+окно закрыто (~1260) | статус не трогает | `set_issue_done` (явно) | AC-10 |
|
||||
| `stage_engine.py` `run_post_deploy_monitor` DEGRADED (~1273) | alert/log | `set_issue_blocked` (+ существующий ALERT_ONLY) | AC-11 |
|
||||
|
||||
**Разводка terminal-sync (детально, AC-8/AC-9).** Текущий код безусловно зовёт
|
||||
`set_issue_done` на `next_stage == "done"`, затем (для self) армит post-deploy monitor.
|
||||
Разводим по `post_deploy.post_deploy_applies(repo)`:
|
||||
|
||||
```python
|
||||
if next_stage == "done" and work_item_id:
|
||||
if post_deploy.post_deploy_applies(repo):
|
||||
set_issue_monitoring(work_item_id) # self: окно наблюдения, НЕ Done сразу
|
||||
else:
|
||||
set_issue_done(work_item_id) # не-self: терминальный Done как сейчас
|
||||
# арм монитора (существующий блок ~361) — без изменений
|
||||
```
|
||||
Финальный `Done`/`Blocked` для self-hosting перекладывается на `run_post_deploy_monitor`.
|
||||
При деградированном алиасе `monitoring==done` self-hosting показывает `Done` и затем
|
||||
монитор держит `Done`/флипает `Blocked` — поведение идентично сегодняшнему.
|
||||
|
||||
**AC-12 (инвариант ORCH-021):** добавление `set_issue_blocked` в DEGRADED-ветку —
|
||||
**только индикация**; тик по-прежнему НИКОГДА не рестартит/откатывает прод-контейнер
|
||||
(self-hosting остаётся `ALERT_ONLY`). `set_issue_blocked` — Plane-PATCH, не действие над
|
||||
контейнером.
|
||||
|
||||
**Cancelled (AC-15):** изменений кода НЕ требует. `handle_issue_updated` реагирует только
|
||||
на `to_analyse`/`approved`/`rejected`; `Cancelled` падает в `else` → «no pipeline action».
|
||||
Орк не делает advance/rollback — индикация, не управление. Критерий выполнен существующим
|
||||
кодом.
|
||||
|
||||
### 2.6. Reconciler (`src/reconciler.py`)
|
||||
|
||||
- **F-2 `_reconcile_plane_project`:** заменить триггер `in_progress` → `to_analyse` в
|
||||
списке запрашиваемых статусов (`list_issues_by_state([to_analyse, approved, rejected])`)
|
||||
и в `_reconcile_plane_issue` маршрутизировать `new_state == to_analyse` →
|
||||
`handle_status_start`. При алиасе `to_analyse == in_progress` (enduro) поведение
|
||||
идентично текущему (один UUID; `list_issues_by_state` дедуплицирует через `set`). AC-19.
|
||||
- **Guard 2 `_is_blocked_or_needs_input`:** расширить skip-множество активными ожиданиями
|
||||
`awaiting_deploy`/`deploying`/`monitoring` (BR-13, AC-20). **Анти-регресс enduro
|
||||
(КРИТИЧНО):** новые ключи алиасятся на `in_review`/`in_progress`/`done`; добавить их в
|
||||
skip «как есть» → на enduro `In Progress`/`Done`-задачи начнут ошибочно пропускаться
|
||||
F-1 (регресс ORCH-053/060). Поэтому активные ожидания включаются в skip **только когда
|
||||
они РАЗЛИЧНЫ от базовых рабочих статусов проекта** (т.е. реально созданы):
|
||||
|
||||
```python
|
||||
base_working = {states.get(k) for k in (
|
||||
"backlog","todo","in_progress","in_review","review",
|
||||
"architecture","development","testing","approved","rejected","done")}
|
||||
extra_waits = {states.get("awaiting_deploy"),
|
||||
states.get("deploying"),
|
||||
states.get("monitoring")} - base_working - {None}
|
||||
skip_set = {states.get("blocked"), states.get("needs_input")} | extra_waits
|
||||
return cur in skip_set
|
||||
```
|
||||
Enduro (алиасы схлопываются в base) → `extra_waits == {}` → нулевой регресс. Orchestrator
|
||||
(отдельные UUID) → три реальных статуса в skip → BR-13. Семантику метода обобщаем до
|
||||
«human-or-active-wait»; флаг `reconcile_skip_blocked_enabled` продолжает гасить этот
|
||||
networked-чек. F-1 и так структурно не оживляет эти состояния (Phase A: `check_deploy_status`
|
||||
red → silent; Deploying: active finalizer job → active-job guard; Monitoring: стадия
|
||||
`done` → не итерируется) — Guard 2 это defense-in-depth по требованию Owner.
|
||||
|
||||
### 2.7. Без kill-switch
|
||||
|
||||
Отдельный env-флаг новой модели **не вводится**. Раскат естественно гейтится
|
||||
**инфра-предусловием**: пока оператор не создал новые статусы — alias-fallback (§2.2)
|
||||
держит строго прежнее поведение; создал — резолв по имени включает новую модель. Это
|
||||
проще отдельного флага и соответствует принципу «минимум зависимостей». (ТЗ §6 допускает
|
||||
флаг как опциональный — сознательно отказываемся.)
|
||||
|
||||
---
|
||||
|
||||
## 3. Затронутые модули (карта изменений)
|
||||
|
||||
| Модуль | Изменение |
|
||||
|--------|-----------|
|
||||
| `src/plane_sync.py` | `_PLANE_NAME_TO_KEY` +6; `_DEFAULT_STATES` +6 (enduro-alias UUID); `_STATE_ALIAS_FALLBACK` (новое) + применение в `get_project_states`; `_STAGE_TO_STATE_KEY` (analysis/review); `STAGE_VISIBILITY_STATE`; `STAGE_TO_STATE` (legacy); 5 новых `set_issue_*`. |
|
||||
| `src/webhooks/plane.py` | триггер `in_progress`→`to_analyse` в `handle_issue_updated`; `set_issue_analysis` в `start_pipeline` и resume-ветке `handle_status_start`; `_rollback_stage` reject@analysis → `set_issue_analysis`. |
|
||||
| `src/stage_engine.py` | Phase A → `set_issue_awaiting_deploy`; Phase B → `set_issue_deploying`; terminal-sync split (`monitoring` vs `done`); post-deploy monitor HEALTHY→`set_issue_done`, DEGRADED→`set_issue_blocked`; rollback@analysis (architect conflict) `set_issue_in_progress`→`set_issue_analysis`. |
|
||||
| `src/reconciler.py` | F-2 триггер `to_analyse`; Guard 2 skip-set + анти-регресс subtraction. |
|
||||
| `src/stages.py` | **НЕ трогаем** (инвариант слоя A). |
|
||||
| `src/config.py` | Без изменений (kill-switch не вводится). |
|
||||
|
||||
---
|
||||
|
||||
## 4. Инварианты (проверяемые, AC-21/AC-22)
|
||||
|
||||
- `src/stages.py` `STAGE_TRANSITIONS` — diff пуст (байт-в-байт).
|
||||
- `QG_CHECKS`, `check_deploy_status`/`_parse_deploy_status`, exit-коды хука (0/1/2),
|
||||
merge-gate, `check_branch_mergeable`/`check_staging_image_fresh`, схема БД — без изменений.
|
||||
- `Confirm Deploy` (ORCH-059), механизм `Needs Input` (analyst-only) — без изменений.
|
||||
- Новых HTTP-эндпоинтов нет; `GET /queue`/`GET /status` контракт без изменений.
|
||||
- Миграций БД нет (`tasks` не хранит Plane-статус; источник истины — стадия в БД + Plane API).
|
||||
- Все новые `set_issue_*` / резолв — never-raise.
|
||||
- Не-self (enduro) терминальный `deploy → Done` — без регресса.
|
||||
|
||||
---
|
||||
|
||||
## 5. Последствия
|
||||
|
||||
**Плюсы**
|
||||
- Доска читаема: каждый этап = осмысленный статус; человеческие входы визуально отделены
|
||||
от индикации.
|
||||
- `In Progress` разгружен: больше не «всё подряд».
|
||||
- Fail-closed усилен (project-relative): частичная конфигурация не ломает ни индикацию,
|
||||
ни конвейер.
|
||||
- Слой A нетронут → нулевой риск для машины стадий и гейтов всех проектов (self-hosting).
|
||||
- Нет нового флага/таблицы → меньше движущихся частей.
|
||||
|
||||
**Минусы / ограничения**
|
||||
- Требуется ручное инфра-действие оператора (создать 6 статусов в проекте ORCH) — до
|
||||
этого orchestrator деградирует до старой индикации (см. `07-infra-requirements.md`).
|
||||
- Статусы кэшируются per-process (`_STATES_CACHE`): после создания статусов нужен
|
||||
`reload_project_states()` или рестарт **staging** (не прод — см. self-hosting риск).
|
||||
- Guard-2 subtraction добавляет немного логики; покрывается тестами (enduro-алиас → пустой
|
||||
extra; orchestrator → три статуса).
|
||||
|
||||
**Self-hosting (⚠️):** изменения — слой B (Plane-индикация) + reconciler-гварды; машина
|
||||
стадий и контракты деплоя нетронуты. Выкладка ОБЯЗАТЕЛЬНО через `deploy-staging` (8501)
|
||||
до прод-деплоя орка. Прод-контейнер не рестартить в рамках задачи вне штатного staging-гейта.
|
||||
|
||||
---
|
||||
|
||||
## 6. Альтернативы (отклонены)
|
||||
|
||||
- **Статический enduro-UUID алиас (ТЗ §2.2 буквально):** ломается на частичной
|
||||
конфигурации orchestrator-проекта (чужой UUID → PATCH 422). Заменён project-relative
|
||||
alias-fallback (§2.2).
|
||||
- **Глобальный env kill-switch новой модели:** избыточен — инфра-предусловие уже даёт
|
||||
естественный гейт раската (§2.7).
|
||||
- **Хранить Plane-статус в `tasks` (миграция БД):** не нужно; источник истины — стадия +
|
||||
живой Plane API. Нарушило бы инвариант «без лишних зависимостей».
|
||||
- **Менять `STAGE_TRANSITIONS` ради новых статусов:** запрещено (инвариант слоя A);
|
||||
статусы — индикация, отделены от машины стадий.
|
||||
96
docs/work-items/ORCH-066/07-infra-requirements.md
Normal file
96
docs/work-items/ORCH-066/07-infra-requirements.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# 07 — Требования к инфраструктуре
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
**Автор:** Architect
|
||||
**Дата:** 2026-06-07
|
||||
|
||||
> ORCH-066 не меняет топологию (контейнеры/порты/сеть — без изменений, см.
|
||||
> `docs/operations/INFRA.md`). Единственное инфра-действие — создание новых
|
||||
> Plane-статусов в проекте **ORCH** руками оператора через Plane API. Это
|
||||
> **предусловие эксплуатации**, не часть кодового PR.
|
||||
|
||||
---
|
||||
|
||||
## 1. Что нужно сделать оператору (ДО эксплуатации новой модели)
|
||||
|
||||
Создать в Plane-проекте **ORCH** следующие статусы (states) с точными именами —
|
||||
резолвер сопоставляет их по `name` (`_PLANE_NAME_TO_KEY`):
|
||||
|
||||
| Plane name (точно) | Логический ключ | Группа Plane (рекомендуемая) | Назначение |
|
||||
|--------------------|-----------------|------------------------------|------------|
|
||||
| `To Analyse` | `to_analyse` | unstarted / started | Человеческий вход: старт конвейера + resume аналитика из Needs Input. |
|
||||
| `Analysis` | `analysis` | started | Индикация стадии анализа. |
|
||||
| `Code-Review` | `code_review` | started | Индикация стадии review. |
|
||||
| `Awaiting Deploy` | `awaiting_deploy` | started | Phase A: ожидание ручного approve на прод-деплой. |
|
||||
| `Deploying` | `deploying` | started | Phase B: идёт прод-деплой. |
|
||||
| `Monitoring after Deploy` | `monitoring` | started | Phase C / окно пост-деплой наблюдения. |
|
||||
|
||||
`Confirm Deploy` (ORCH-059) и базовые статусы (`Backlog`, `Todo`, `In Progress`,
|
||||
`Architecture`, `Development`, `Review`, `Testing`, `Approved`, `Rejected`, `Done`,
|
||||
`Cancelled`, `Needs Input`, `In Review`, `Blocked`) уже существуют — **не трогать**.
|
||||
|
||||
> ⚠️ **Точность имён критична.** Резолв идёт по строковому `name`. Опечатка/иной регистр
|
||||
> → статус не сопоставится → ключ деградирует на собственный базовый UUID проекта
|
||||
> (alias-fallback, ADR §2.2): индикация откатится к старому статусу, но конвейер
|
||||
> продолжит работать. Дефис в `Code-Review` — обязателен.
|
||||
|
||||
---
|
||||
|
||||
## 2. Plane API — как создать статус
|
||||
|
||||
Эндпоинт (как в `src/plane_sync.py`, `PLANE_BASE = {plane_api_url}/api/v1`):
|
||||
|
||||
```
|
||||
POST {PLANE_BASE}/workspaces/{WORKSPACE}/projects/{ORCH_PROJECT_ID}/states/
|
||||
Headers: X-API-Key: <PLANE_API_TOKEN> (или соответствующий бот-токен с правами)
|
||||
Body (JSON):
|
||||
{ "name": "To Analyse", "group": "started", "color": "#3f76ff" }
|
||||
```
|
||||
|
||||
Повторить для каждого имени из таблицы §1. `group` влияет только на колонку доски;
|
||||
оркестратор `group` не читает (резолв строго по `name`). `color` — на вкус оператора.
|
||||
|
||||
Проверка после создания:
|
||||
|
||||
```
|
||||
GET {PLANE_BASE}/workspaces/{WORKSPACE}/projects/{ORCH_PROJECT_ID}/states/
|
||||
```
|
||||
В ответе должны присутствовать все 6 имён.
|
||||
|
||||
---
|
||||
|
||||
## 3. Сброс кэша статусов (важно)
|
||||
|
||||
`get_project_states` кэширует резолв per-process (`_STATES_CACHE`). После создания
|
||||
статусов оркестратор подхватит их **только** после сброса кэша:
|
||||
|
||||
- штатно — `plane_sync.reload_project_states(project_id)` (или рестарт процесса);
|
||||
- на **staging** (8501) — безопасный рестарт песочницы;
|
||||
- на **прод** (8500) — **НЕ рестартить контейнер ради этого** в рамках задачи
|
||||
(self-hosting: общий контейнер всех проектов). Кэш заполняется при первом обращении к
|
||||
проекту; если статусы созданы ДО первого PATCH в цикле новой версии — отдельный сброс не
|
||||
нужен. Если созданы позже — дождаться штатного цикла обновления/деплоя орка.
|
||||
|
||||
---
|
||||
|
||||
## 4. Порядок раската (рекомендация)
|
||||
|
||||
1. Слить кодовый PR ORCH-066 через `deploy-staging` (8501).
|
||||
2. Создать 6 статусов в проекте ORCH (§1–§2).
|
||||
3. Сбросить кэш / поднять staging, прогнать sandbox-задачу — убедиться, что доска
|
||||
показывает `Analysis` / `Code-Review` / `Awaiting Deploy` / `Deploying` /
|
||||
`Monitoring after Deploy` / `Done` на соответствующих этапах.
|
||||
4. Прод-деплой орка штатным self-deploy (Phase A → approve → Phase B/C).
|
||||
|
||||
**До шага 2** система работает строго как до ORCH-066 (alias-fallback) — раскат
|
||||
безопасно обратим: не создавать/удалить статусы = откат индикации к старой модели,
|
||||
без изменения кода.
|
||||
|
||||
---
|
||||
|
||||
## 5. Что НЕ требуется
|
||||
|
||||
- Никаких изменений docker-compose, портов, сети, томов, `.env`/`.env.staging`.
|
||||
- Никаких миграций БД (`tasks` не хранит Plane-статус).
|
||||
- Никаких изменений в проекте **enduro-trails** — там новые статусы не создаются;
|
||||
alias-fallback держит прежнюю индикацию (`In Progress`/`Review`/`Done`).
|
||||
31
docs/work-items/ORCH-066/10-tech-risks.md
Normal file
31
docs/work-items/ORCH-066/10-tech-risks.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# 10 — Технические риски
|
||||
|
||||
**Work Item:** ORCH-066
|
||||
**Автор:** Architect
|
||||
**Дата:** 2026-06-07
|
||||
|
||||
Риски слоя B (Plane-индикация). Слой A (`STAGE_TRANSITIONS`/гейты) не затрагивается, поэтому
|
||||
класс «сломали конвейер» структурно исключён — худший исход любого риска ниже = неверная
|
||||
**индикация**, не остановка конвейера.
|
||||
|
||||
| ID | Риск | Вероятность | Влияние | Митигация |
|
||||
|----|------|-------------|---------|-----------|
|
||||
| **R1** | Частичная конфигурация: оператор создал не все 6 статусов в ORCH → отсутствующий ключ деградирует. Наивный статический enduro-UUID дал бы невалидный `state` (PATCH 422) на orchestrator-issue. | Средняя | Средн. | **Project-relative alias-fallback** (ADR §2.2): отсутствующий ключ → собственный базовый UUID проекта → PATCH валиден, индикация откатывается к текущему статусу. Покрыть тестом partial-config. |
|
||||
| **R2** | Enduro-регресс через Guard 2: новые ключи алиасятся на `in_progress`/`in_review`/`done`; наивное добавление в skip-set заставит F-1 пропускать enduro `In Progress`/`Done` → сломанная реконсиляция (ORCH-053/060). | Средняя | Высок. | **Subtraction базовых рабочих статусов** (ADR §2.6): `extra_waits -= base_working`. На enduro (алиасы схлопнуты) `extra_waits == {}` → нулевой регресс. Тест: enduro-алиас не добавляет skip, orchestrator-distinct добавляет. |
|
||||
| **R3** | Двойной триггер старта: F-2 reconciler и webhook оба маршрутизируют `to_analyse`; при алиасе `to_analyse == in_progress` возможен повтор. | Низкая | Низк. | `list_issues_by_state` дедуплицирует UUID через `set`; active-job guard + atomic create-claim в `handle_status_start` (`get_task_by_plane_id` + `has_active_job_for_task`) — без двойного старта (AC-4). Сохранить fork как есть. |
|
||||
| **R4** | Кэш статусов: после создания статусов `_STATES_CACHE` отдаёт старый резолв до сброса → доска не обновляется. | Средняя | Низк. | `reload_project_states()` / рестарт **staging**. Документировано в `07-infra-requirements.md §3`. Прод-рестарт ради кэша — запрещён (self-hosting). |
|
||||
| **R5** | Опечатка в имени статуса оператором (`Code Review` без дефиса и т.п.) → ключ не резолвится. | Средняя | Низк. | Резолв по точному `name`; при промахе — alias-fallback (деградация, не падение). Точные имена и проверка в `07-infra-requirements.md §1–2`. |
|
||||
| **R6** | Terminal-sync split: ошибка ветвления `post_deploy_applies` → enduro получает `Monitoring after Deploy` вместо `Done` (регресс AC-9) или self уходит в `Done` минуя окно (AC-8). | Низкая | Средн. | Единый источник условности — `post_deploy.post_deploy_applies(repo)` (та же функция, что армит монитор). Тесты AC-8 (self→monitoring) и AC-9 (не-self→done). |
|
||||
| **R7** | Phase B: `set_issue_deploying` поставлен до фактического старта детача → ложная индикация при провале `initiate_deploy`. | Низкая | Низк. | Ставить `set_issue_deploying` **после** успешного `initiate_deploy` и записи `INITIATED` marker (ADR §2.5); провал `initiate_deploy` оставляет `Awaiting Deploy` + просьбу повторить approve. |
|
||||
| **R8** | Post-deploy DEGRADED → `set_issue_blocked` ошибочно трактуется как «действие над продом». | Низкая | Высок.(если) | `set_issue_blocked` — только Plane-PATCH. Тик остаётся `ALERT_ONLY`, НИКОГДА не рестартит/откатывает прод-контейнер (AC-12, ORCH-021 BR-5). Явный тест: self DEGRADED не трогает контейнер. |
|
||||
| **R9** | Plane API недоступен в момент простановки статуса → PATCH падает. | Низкая | Низк. | Все `set_issue_*`/`_set_issue_state_direct` — never-raise (логируют, не пробрасывают). Индикация пропускается, слой A не затронут. |
|
||||
| **R10** | Регресс на тестах, читающих `STAGE_TO_STATE`/`PLANE_STATES` конкретные UUID. | Низкая | Низк. | Новые ключи в `_DEFAULT_STATES` = алиасы на те же in_progress/review/done UUID → значения байт-в-байт; `STAGE_TO_STATE` analysis/review остаются прежними UUID (ADR §2.3). |
|
||||
| **R11** | Self-hosting: выкладка орка минуя staging. | Низкая | Высок. | Обязательный `deploy-staging` гейт (8501); прод не рестартить вне штатного self-deploy. Раскат обратим (не создавать статусы = старое поведение). |
|
||||
|
||||
## Сводный вывод
|
||||
|
||||
Все риски снижаемы в рамках принятой архитектуры; ни один не способен остановить конвейер
|
||||
(слой A инвариантен). Два ключевых требуют аккуратной реализации и обязательных тестов:
|
||||
**R1** (project-relative alias-fallback) и **R2** (Guard-2 anti-regress subtraction) —
|
||||
оба зафиксированы в ADR §2.2 и §2.6 как явные контракты. Эскалации `arch:major-change` не
|
||||
требуется: изменение локализовано в слое B, без новых компонентов/стадий/QG/миграций.
|
||||
89
docs/work-items/ORCH-066/12-review.md
Normal file
89
docs/work-items/ORCH-066/12-review.md
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
type: review
|
||||
work_item_id: ORCH-066
|
||||
verdict: APPROVED
|
||||
version: 1
|
||||
---
|
||||
|
||||
# Review ORCH-066
|
||||
|
||||
## Summary
|
||||
Осмысленная статусная модель Plane (слой B — индикация). Реализация затрагивает
|
||||
строго слой B (`src/plane_sync.py`, точки простановки в `src/stage_engine.py` /
|
||||
`src/webhooks/plane.py` / `src/reconciler.py`) и **не трогает слой A**
|
||||
(`src/stages.py::STAGE_TRANSITIONS` — diff пуст). Все 4 оси проверки (ТЗ, ADR,
|
||||
качество кода, тесты) и проверка документации — пройдены. `pytest tests/ -q`:
|
||||
**774 passed**. Вердикт — **APPROVED**.
|
||||
|
||||
## Соответствие ТЗ (02-trz.md)
|
||||
- §2.1 — 6 новых логических ключей в `_PLANE_NAME_TO_KEY` + `_DEFAULT_STATES`. ✔
|
||||
- §2.2 — fail-closed резолюция (BR-12). ✔ (реализована усиленная project-relative
|
||||
версия — см. ADR ниже).
|
||||
- §2.3 — `_STAGE_TO_STATE_KEY` (analysis→analysis, review→code_review),
|
||||
`STAGE_VISIBILITY_STATE`, legacy `STAGE_TO_STATE` (UUID байт-в-байт прежние). ✔
|
||||
- §2.4 — точки простановки разведены (handle_issue_updated триггер `to_analyse`,
|
||||
start_pipeline/resume → Analysis, Phase A → Awaiting Deploy, Phase B → Deploying,
|
||||
terminal-sync split, post-deploy HEALTHY→Done / DEGRADED→Blocked,
|
||||
rollback@analysis → Analysis). ✔
|
||||
- §2.5 — 5 новых never-raise хелперов `set_issue_*`. ✔
|
||||
- §3 — reconciler F-2 триггер `to_analyse` (+ resume-ветка), Guard 2 skip-set с
|
||||
вычитанием base_working. ✔
|
||||
- §4/§5/§6 — нет новых эндпоинтов, нет миграций БД, `QG_CHECKS` не расширен. ✔
|
||||
|
||||
## Соответствие ADR (06-adr/ADR-001)
|
||||
- §2.2 project-relative alias-fallback (`_STATE_ALIAS_FALLBACK`, применён ДО
|
||||
`_DEFAULT_STATES.setdefault`) — реализован точно по контракту, деградация на
|
||||
собственный базовый UUID проекта, PATCH остаётся валидным на частичной
|
||||
конфигурации. ✔
|
||||
- §2.5 terminal-sync split по `post_deploy.post_deploy_applies(repo)` — реализован
|
||||
как в ADR (self → Monitoring, не-self → Done). ✔
|
||||
- §2.6 Guard 2 анти-регресс (extra_waits − base_working − {None}) — реализован
|
||||
дословно, enduro-алиасы схлопываются → нулевой регресс. ✔
|
||||
- §2.7 без kill-switch — config.py не изменён (diff пуст). ✔
|
||||
|
||||
## Качество кода
|
||||
- Все новые `set_issue_*` следуют образцу `set_issue_in_review` (per-project резолв
|
||||
+ `_set_issue_state_direct`), контракт never-raise сохранён, есть docstrings. ✔
|
||||
- Post-deploy/terminal-sync простановки обёрнуты в try/except с warning-логом
|
||||
(never break the tick). ✔
|
||||
- Переменные в scope корректны (`work_item_id` определён до всех новых вызовов в
|
||||
`start_pipeline`/`handle_status_start`/stage_engine). ✔
|
||||
- AC-12 соблюдён: `set_issue_blocked` в DEGRADED-ветке — только индикация, тик
|
||||
прод-контейнер не трогает. ✔
|
||||
|
||||
## Качество тестов
|
||||
- Содержательные, не тривиальные: `test_plane_status_failclosed.py`
|
||||
(TC-16/17/18 — partial project, API down, never-raise сеттеров, enduro alias
|
||||
старт), `test_plane_to_analyse_resume.py`, `test_plane_status_model.py`,
|
||||
`test_deploy_terminal_sync.py` (self/не-self split), `test_post_deploy_integration.py`,
|
||||
`test_reconciler*.py` (F-2 to_analyse + Guard 2). ✔
|
||||
|
||||
## Инварианты (AC-21/AC-22)
|
||||
- `src/stages.py` — diff 0 строк (STAGE_TRANSITIONS байт-в-байт). ✔
|
||||
- `src/qg/checks.py` — diff 0 строк (QG_CHECKS, check_deploy_status). ✔
|
||||
- `src/config.py` — diff 0 строк. ✔
|
||||
- Схема БД — без миграций. ✔
|
||||
|
||||
## Findings
|
||||
|
||||
### P0 — Blocker
|
||||
- нет
|
||||
|
||||
### P1 — Must fix
|
||||
- нет
|
||||
|
||||
### P2 — Should fix
|
||||
- нет
|
||||
|
||||
## Документация
|
||||
Обновлена в том же PR (golden source соблюдён):
|
||||
- `CLAUDE.md` — добавлена секция «Статусная модель Plane (ORCH-066)». ✔
|
||||
- `docs/architecture/README.md` — секция «Осмысленная статусная модель Plane
|
||||
(ORCH-066)» + обновлён статусный footer. ✔
|
||||
- `CHANGELOG.md` — подробная запись в [Unreleased]/Added. ✔
|
||||
- `06-adr/ADR-001-plane-status-model.md` — заведён. ✔
|
||||
- `07-infra-requirements.md` — присутствует (инфра-предусловие: 6 Plane-статусов
|
||||
создаёт оператор). ✔
|
||||
|
||||
Изменения `src/` полностью отражены в документации → требование
|
||||
«документация обновлена при изменении src/» выполнено.
|
||||
77
docs/work-items/ORCH-066/13-test-report.md
Normal file
77
docs/work-items/ORCH-066/13-test-report.md
Normal file
@@ -0,0 +1,77 @@
|
||||
---
|
||||
type: test-report
|
||||
work_item_id: ORCH-066
|
||||
result: PASS
|
||||
---
|
||||
|
||||
# Test Report — ORCH-066
|
||||
|
||||
Осмысленная статусная модель Plane (слой B — индикация). Прогон полного регресса +
|
||||
покрытие тест-плана `04-test-plan.yaml` + проверка инвариантов слоя A.
|
||||
|
||||
## Окружение
|
||||
- Python: 3.12.13
|
||||
- pytest: 8.3.3
|
||||
- Ветка: feature/ORCH-066-plane
|
||||
- Дата: 2026-06-07
|
||||
|
||||
## Результаты по тест-плану (04-test-plan.yaml)
|
||||
|
||||
| TC ID | Покрывает | Описание | Модуль | Результат |
|
||||
|-------|-----------|----------|--------|-----------|
|
||||
| TC-01 | AC-1 | To Analyse без task → start_pipeline | test_status_trigger.py | PASS |
|
||||
| TC-02 | AC-2,BR-11 | To Analyse resume аналитика, без двойного task | test_plane_to_analyse_resume.py | PASS |
|
||||
| TC-03 | AC-3 | Старт/relaunch → статус Analysis | test_plane_status_model.py | PASS |
|
||||
| TC-04 | AC-4 | Busy-guard: active-job → не relaunch | test_plane_to_analyse_resume.py | PASS |
|
||||
| TC-05 | AC-5 | review → статус Code-Review | test_plane_status_model.py | PASS |
|
||||
| TC-06 | AC-6,AC-13 | Phase A → Awaiting Deploy (не In Review) | test_deploy_approve.py | PASS |
|
||||
| TC-07 | AC-7 | Phase B → Deploying | test_deploy_approve.py | PASS |
|
||||
| TC-08 | AC-8 | Phase C self → Monitoring after Deploy | test_deploy_terminal_sync.py | PASS |
|
||||
| TC-09 | AC-9 | Не-self deploy→done → Done (без регресса) | test_deploy_terminal_sync.py | PASS |
|
||||
| TC-10 | AC-10 | Post-deploy HEALTHY → Done | test_post_deploy.py | PASS |
|
||||
| TC-11 | AC-11 | Post-deploy DEGRADED → Blocked | test_post_deploy.py | PASS |
|
||||
| TC-12 | AC-12 | Self-тик не рестартит прод | test_post_deploy.py | PASS |
|
||||
| TC-13 | AC-13 | In Review только за approve-pending | test_analyst_status_only_regression.py | PASS |
|
||||
| TC-14 | AC-14,BR-10 | Needs Input без изменений | test_plane_status_model.py | PASS |
|
||||
| TC-15 | AC-15 | Cancelled → нет действий конвейера | test_plane_webhook.py | PASS |
|
||||
| TC-16 | AC-16,BR-12 | Fail-closed default-алиасы, нет исключений | test_plane_status_failclosed.py | PASS |
|
||||
| TC-17 | AC-16 | Plane API down → fallback, never-raise | test_plane_status_failclosed.py | PASS |
|
||||
| TC-18 | AC-17 | enduro In Progress стартует через алиас | test_plane_status_failclosed.py | PASS |
|
||||
| TC-19 | AC-18 | Резолв по имени → корректный UUID | test_orch10_states.py | PASS |
|
||||
| TC-20 | AC-19 | F-2 реконсилирует To Analyse | test_reconciler_plane.py | PASS |
|
||||
| TC-21 | AC-20,BR-13 | Guard 2 skip активных ожиданий | test_reconciler.py | PASS |
|
||||
| TC-22 | AC-21 | STAGE_TRANSITIONS не изменён | test_plane_status_model.py | PASS |
|
||||
| TC-23 | AC-22 | QG_CHECKS/check_deploy_status не изменены | test_plane_status_model.py | PASS |
|
||||
| TC-24 | AC-23 | Полный регресс pytest зелёный | tests/ | PASS |
|
||||
|
||||
Все 24 тест-кейса — PASS.
|
||||
|
||||
## Инварианты слоя A (AC-21 / AC-22)
|
||||
Diff против `origin/main` (merge-base `4815e378`):
|
||||
- `src/stages.py` (STAGE_TRANSITIONS) — diff пуст ✔
|
||||
- `src/qg/checks.py` (QG_CHECKS, check_deploy_status) — diff пуст ✔
|
||||
- `src/config.py` (без kill-switch) — diff пуст ✔
|
||||
|
||||
## Smoke test API (TestClient — прод-контейнер 8500 не трогался)
|
||||
> `curl` в окружении недоступен; smoke прогнан через FastAPI TestClient (lifespan),
|
||||
> без рестарта/обращения к прод-контейнеру (self-hosting safety).
|
||||
|
||||
| Endpoint | Статус | Тело (фрагмент) |
|
||||
|----------|--------|-----------------|
|
||||
| GET /health | 200 | `{"status":"ok","service":"orchestrator"}` |
|
||||
| GET /status | 200 | `{"active_tasks":[...]}` |
|
||||
| GET /queue | 200 | `{"counts":{...},"max_concurrency":1,...}` |
|
||||
|
||||
## Вывод pytest
|
||||
```
|
||||
======================= 774 passed, 1 warning in 17.68s ========================
|
||||
```
|
||||
(единственный warning — PydanticDeprecatedSince20 в src/config.py, предсуществующий,
|
||||
не связан с ORCH-066)
|
||||
|
||||
Прогон по модулям тест-плана: `117 passed` (ORCH-066-специфичные файлы).
|
||||
|
||||
## Итог
|
||||
PASS — все тесты зелёные (774 passed), все 24 TC покрыты, инварианты слоя A
|
||||
сохранены (diff пуст), smoke-эндпоинты отвечают 200. Review-вердикт APPROVED.
|
||||
Задача готова к переходу на стадию deploy-staging.
|
||||
12
docs/work-items/ORCH-066/14-deploy-log.md
Normal file
12
docs/work-items/ORCH-066/14-deploy-log.md
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
deploy_status: SUCCESS
|
||||
work_item: ORCH-066
|
||||
hook_exit_code: 0
|
||||
deployed_by: deploy-finalizer
|
||||
---
|
||||
|
||||
# Deploy log — ORCH-036 executable self-deploy
|
||||
|
||||
Прод-деплой завершён хост-хуком с exit-code `0` -> `deploy_status: SUCCESS`.
|
||||
|
||||
Вердикт зафиксирован детерминированным finalizer'ом (Фаза C), не LLM.
|
||||
39
docs/work-items/ORCH-066/15-staging-log.md
Normal file
39
docs/work-items/ORCH-066/15-staging-log.md
Normal file
@@ -0,0 +1,39 @@
|
||||
---
|
||||
staging_status: SUCCESS
|
||||
timestamp: 2026-06-07T22:01:57Z
|
||||
base_url: http://localhost:8501
|
||||
---
|
||||
|
||||
# Staging Gate Log
|
||||
|
||||
Staging test suite completed against the live `orchestrator-staging` instance (port 8501),
|
||||
run canonically via `docker exec orchestrator-staging python3 /repos/orchestrator/scripts/staging_check.py --base-url http://localhost:8501 --mode stub`.
|
||||
|
||||
**Result: 8/10 checks PASS — exit code 0 (advance).**
|
||||
|
||||
All REAL (pipeline) checks are green. The two failing checks are the known
|
||||
SANDBOX_INFRA-only checks C9a/C9b (sandbox branch / analyst-job — depend on
|
||||
SANDBOX bot accounts being project members, not on the pipeline), which are
|
||||
waived under ORCH-061 since every REAL check passed.
|
||||
|
||||
```
|
||||
INFRA-WAIVED: C9a Branch appears in orchestrator-sandbox, C9b Analyst job enqueued in staging queue (known sandbox-infra; real checks green)
|
||||
VERDICT: SUCCESS (exit 0) — SUCCESS (infra-waived): ['C9a Branch appears in orchestrator-sandbox', 'C9b Analyst job enqueued in staging queue'] are known sandbox-infra checks; all real checks green
|
||||
```
|
||||
|
||||
## Check breakdown
|
||||
|
||||
| Block | Check | Result |
|
||||
|-------|-------|--------|
|
||||
| A SMOKE | A1 GET /health → 200 status=ok | PASS |
|
||||
| A SMOKE | A2 GET /queue → 200 with counts/max_concurrency/resilience | PASS |
|
||||
| A SMOKE | A3 ORCH_STAGING=true (not prod) | PASS |
|
||||
| B ACCESS | B4 Plane: sandbox project accessible | PASS |
|
||||
| B ACCESS | B5 Gitea: orchestrator-sandbox accessible, push=true | PASS |
|
||||
| B ACCESS | B6 Registry: sandbox present, prod ET/ORCH absent | PASS |
|
||||
| C E2E | C7 Create issue in Plane SANDBOX | PASS |
|
||||
| C E2E | C8 Trigger pipeline via /webhook/plane | PASS |
|
||||
| C E2E | C9a Branch appears in orchestrator-sandbox | FAIL (waived — sandbox-infra) |
|
||||
| C E2E | C9b Analyst job enqueued in staging queue | FAIL (waived — sandbox-infra) |
|
||||
|
||||
CLEANUP completed: test Plane issue deleted (HTTP 204); no branch to delete.
|
||||
14
docs/work-items/ORCH-066/16-post-deploy-log.md
Normal file
14
docs/work-items/ORCH-066/16-post-deploy-log.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
post_deploy_status: HEALTHY
|
||||
action_taken: NONE
|
||||
work_item: ORCH-066
|
||||
window_s: 900
|
||||
checks_total: 30
|
||||
checks_failed: 0
|
||||
---
|
||||
|
||||
# Post-deploy log — ORCH-021 post-deploy monitor
|
||||
|
||||
Наблюдение прода завершено: `post_deploy_status: HEALTHY`, `action_taken: NONE`.
|
||||
|
||||
Окно наблюдения: 900s; опросов всего: 30, из них с провалом: 0.
|
||||
@@ -417,6 +417,14 @@ class AgentLauncher:
|
||||
"UPDATE agent_runs SET output_path = ? WHERE id = ?",
|
||||
(output_path, run_id),
|
||||
)
|
||||
# ORCH-065: stamp the agent process pid onto the job row so the job-reaper
|
||||
# can probe liveness (os.kill(pid, 0)). proc.pid only exists after Popen,
|
||||
# so this is a second UPDATE next to run_id/started_at (set above in _spawn).
|
||||
if job_id is not None:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET pid = ? WHERE id = ?",
|
||||
(proc.pid, job_id),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
@@ -296,6 +296,42 @@ class Settings(BaseSettings):
|
||||
post_deploy_auto_rollback: bool = False
|
||||
post_deploy_base_url: str = "http://localhost:8500"
|
||||
|
||||
# ORCH-065: job-reaper + proactive merge-lease reclaim. A background daemon
|
||||
# thread (modelled on the reconciler) makes "the monitor thread / process died
|
||||
# while a job/lease was held" self-heal WITHOUT a restart. Status (done/queued/
|
||||
# failed) is otherwise only ever set by launcher._monitor_agent -> _finalize_job
|
||||
# inside the live process; a death there left the jobs row 'running' forever and
|
||||
# (at max_concurrency=1) wedged the queue of EVERY project (incidents 07.06: jobs
|
||||
# 236/239/242/254). The same thread proactively reclaims a stale/dead merge-lease
|
||||
# (ORCH-043) instead of waiting for the lazy TTL on the next foreign acquire. See
|
||||
# docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md.
|
||||
# reaper_enabled -> global kill-switch (false -> strictly prior behaviour;
|
||||
# only the startup requeue_running_jobs remains).
|
||||
# reaper_interval_s -> background scan period (seconds).
|
||||
# reaper_dead_ticks -> Tier-1: consecutive ticks a job's pid must be dead
|
||||
# before it is reaped (>=2 anti-false-positive; a live
|
||||
# long-running agent is NEVER reaped).
|
||||
# reaper_max_running_s -> Tier-3 backstop ceiling: a job 'running' longer than
|
||||
# this is reaped even when liveness is unknowable. MUST be
|
||||
# > max agent_timeout + grace so a legit agent is safe.
|
||||
# reaper_finalize_grace_s -> Tier-2 anti-false-positive: a LIVE monitor writes
|
||||
# agent_runs.exit_code FIRST, THEN does git commit/push +
|
||||
# PR + Plane usage comments (seconds..minutes) and only
|
||||
# then _finalize_job. The agent pid is already dead in
|
||||
# that window, so pid cannot tell "monitor died" from
|
||||
# "monitor still finalizing". A job is reaped via Tier-2
|
||||
# only once exit_code has been recorded for at least this
|
||||
# many seconds (MUST be > the max finalization window).
|
||||
# lease_reclaim_enabled -> kill-switch for the proactive stale/dead lease reclaim
|
||||
# (false -> only the legacy lazy TTL reclaim in acquire).
|
||||
# (reuse) merge_lock_timeout_s -> lease TTL; merge_gate_repos -> reclaim scope.
|
||||
reaper_enabled: bool = True
|
||||
reaper_interval_s: int = 60
|
||||
reaper_dead_ticks: int = 2
|
||||
reaper_max_running_s: int = 3600
|
||||
reaper_finalize_grace_s: int = 300
|
||||
lease_reclaim_enabled: bool = True
|
||||
|
||||
# Telegram notifications
|
||||
telegram_bot_token: str = ""
|
||||
telegram_chat_id: str = ""
|
||||
|
||||
81
src/db.py
81
src/db.py
@@ -76,6 +76,11 @@ def init_db():
|
||||
# (CREATE TABLE IF NOT EXISTS won't add columns to an already-created table).
|
||||
_ensure_column(conn, "jobs", "transient_attempts", "INTEGER NOT NULL DEFAULT 0")
|
||||
_ensure_column(conn, "jobs", "available_at", "TEXT")
|
||||
# ORCH-065: pid of the spawned agent process, stamped in launcher._spawn next to
|
||||
# run_id/started_at. The job-reaper uses it for Tier-1 liveness (os.kill(pid, 0))
|
||||
# to detect a 'running' job whose process died before _finalize_job. Idempotent
|
||||
# ALTER (no-op once present) -> safe on the live prod DB.
|
||||
_ensure_column(conn, "jobs", "pid", "INTEGER")
|
||||
# ORCH-5 (M-7): webhook delivery de-dup. Add events.delivery_id and a PARTIAL
|
||||
# unique index. Partial (WHERE delivery_id IS NOT NULL) so pre-existing rows
|
||||
# (which have NULL delivery_id) never collide with each other. Restart-safe:
|
||||
@@ -593,6 +598,82 @@ def requeue_running_jobs() -> int:
|
||||
return int(n)
|
||||
|
||||
|
||||
def get_running_jobs() -> list[dict]:
|
||||
"""ORCH-065: snapshot of every 'running' job for the job-reaper scan.
|
||||
|
||||
Each row carries the job columns plus four reaper inputs:
|
||||
* ``running_age_s`` — seconds since ``started_at`` (Tier-3 backstop);
|
||||
* ``exit_code`` — the linked ``agent_runs.exit_code`` (Tier-2: process
|
||||
finished but the job is still 'running' -> monitor died mid-finalize);
|
||||
* ``finished_at_run`` — the linked ``agent_runs.finished_at``;
|
||||
* ``finished_age_s`` — seconds since ``agent_runs.finished_at`` (Tier-2
|
||||
finalization grace: a LIVE monitor writes exit_code, THEN does git
|
||||
push / PR / Plane comments before _finalize_job, so a freshly-finished
|
||||
run is NOT yet a zombie — the reaper waits ``reaper_finalize_grace_s``).
|
||||
|
||||
A LEFT JOIN on ``run_id`` keeps jobs with no agent_runs row (exit_code NULL).
|
||||
Read-only; never mutates. The reaper applies liveness/streak/backstop on top.
|
||||
"""
|
||||
conn = get_db()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT j.*, "
|
||||
"CAST(strftime('%s','now') - strftime('%s', j.started_at) AS INTEGER) "
|
||||
" AS running_age_s, "
|
||||
"r.exit_code AS exit_code, r.finished_at AS finished_at_run, "
|
||||
"CAST(strftime('%s','now') - strftime('%s', r.finished_at) AS INTEGER) "
|
||||
" AS finished_age_s "
|
||||
"FROM jobs j LEFT JOIN agent_runs r ON r.id = j.run_id "
|
||||
"WHERE j.status='running'"
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def reap_running_job(
|
||||
job_id: int,
|
||||
status: str,
|
||||
run_id: int | None = None,
|
||||
error: str | None = None,
|
||||
) -> bool:
|
||||
"""ORCH-065: atomic terminal flip of a RUNNING job by the job-reaper.
|
||||
|
||||
Mirrors ``mark_job`` but carries the ``status='running'`` guard in the WHERE
|
||||
clause and reports ``rowcount`` so a late-arriving monitor / the startup
|
||||
``requeue_running_jobs`` / a second reaper tick can never double-process the
|
||||
same row (AC-5, restart-safe). Returns True iff THIS call won the flip
|
||||
(rowcount == 1); False -> someone else already moved the row.
|
||||
|
||||
Status semantics match ``mark_job``: done/failed stamp ``finished_at``; queued
|
||||
clears ``started_at``/``finished_at`` so the next claim treats it as fresh.
|
||||
"""
|
||||
conn = get_db()
|
||||
try:
|
||||
sets = ["status = ?"]
|
||||
params: list = [status]
|
||||
if run_id is not None:
|
||||
sets.append("run_id = ?")
|
||||
params.append(run_id)
|
||||
if error is not None:
|
||||
sets.append("error = ?")
|
||||
params.append(error)
|
||||
if status in ("done", "failed"):
|
||||
sets.append("finished_at = datetime('now')")
|
||||
elif status == "queued":
|
||||
sets.append("started_at = NULL")
|
||||
sets.append("finished_at = NULL")
|
||||
params.append(job_id)
|
||||
cur = conn.execute(
|
||||
f"UPDATE jobs SET {', '.join(sets)} WHERE id = ? AND status='running'",
|
||||
params,
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount == 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_job(job_id: int) -> dict | None:
|
||||
"""Fetch a single job by id."""
|
||||
conn = get_db()
|
||||
|
||||
467
src/job_reaper.py
Normal file
467
src/job_reaper.py
Normal file
@@ -0,0 +1,467 @@
|
||||
"""ORCH-065: job-reaper + proactive merge-lease reclaim background daemon.
|
||||
|
||||
Three failure classes share one root cause — "the thread/process died while it
|
||||
still held captured state" — and one inert recovery layer
|
||||
(``requeue_running_jobs``) that only fires on a process restart:
|
||||
|
||||
* **A — zombie jobs.** A job's terminal status (``done``/``queued``/``failed``)
|
||||
is written ONLY inside ``launcher._monitor_agent -> _finalize_job`` in the
|
||||
live process. If that thread/process dies between ``proc.wait()`` and the
|
||||
status write (crash, OOM, self-restart mid-deploy) the ``jobs`` row stays
|
||||
``running`` forever. At ``max_concurrency=1`` one zombie blocks the claim of
|
||||
EVERY project's jobs -> the whole shared pipeline stalls.
|
||||
* **B — stuck merge-lease.** The file lease ``.merge-lease-<repo>.json``
|
||||
(ORCH-043) is reclaimed only lazily, by TTL, and only when ANOTHER task tries
|
||||
to acquire it. Holder liveness (pid) is never probed, so a death with the
|
||||
lease held blocks foreign merges until the TTL expires.
|
||||
|
||||
This module is a background daemon thread modelled on ``reconciler``
|
||||
(``threading.Thread(daemon=True)`` + ``threading.Event``, start/stop in
|
||||
``main.lifespan``, ``/queue`` snapshot, per-unit never-raise, kill-switch). Each
|
||||
tick: (1) scans ``running`` jobs and reaps the dead ones via three-tier liveness
|
||||
detection; (2) proactively reclaims dead/stale merge-leases (mechanism B) for the
|
||||
in-scope repos.
|
||||
|
||||
Liveness (defense in depth, ADR-001 Р-1):
|
||||
* **Tier-1 (primary): dead pid.** ``jobs.pid`` (stamped by ``launcher._spawn``)
|
||||
probed with ``merge_gate.pid_alive``. A job is reaped only after
|
||||
``reaper_dead_ticks`` (>=2) CONSECUTIVE dead-pid ticks — an in-memory streak
|
||||
counter kills false positives (AC-3); a live agent within its timeout is
|
||||
never reaped.
|
||||
* **Tier-2 (completion race): exit_code recorded but job still running.** This
|
||||
window is AMBIGUOUS — it is both "the monitor died between writing
|
||||
``agent_runs.exit_code`` and ``_finalize_job``" AND "a LIVE monitor is still
|
||||
finalizing" (``_monitor_agent`` writes ``exit_code`` FIRST, then git
|
||||
commit/push (+PR), the БАГ-8 check and network Plane usage comments — seconds
|
||||
to tens of seconds — and ONLY THEN ``_try_advance_stage`` -> ``_finalize_job``).
|
||||
The agent pid is already dead in BOTH cases, so it cannot disambiguate. The
|
||||
reaper therefore treats it as a dead monitor (KNOWN outcome) only after a
|
||||
finalization grace: ``exit_code`` recorded for >= ``reaper_finalize_grace_s``
|
||||
(a live finalizing monitor is NEVER reaped, FR-1.3/AC-3). Within the grace the
|
||||
row is left untouched.
|
||||
* **Tier-3 (backstop): age ceiling.** A job ``running`` longer than
|
||||
``reaper_max_running_s`` (deliberately > max ``agent_timeout`` + grace) is
|
||||
reaped even when liveness cannot be determined (pid reused / unknown).
|
||||
|
||||
Action on confirmed death reuses existing contracts (no new merge/stage logic):
|
||||
* The reaper's ONLY mutating write to a job row is the atomic terminal flip
|
||||
``db.reap_running_job(... WHERE status='running')`` — so a late-arriving
|
||||
monitor / the startup ``requeue_running_jobs`` / a second tick can never
|
||||
double-process a row (AC-5; the loser sees ``rowcount==0``).
|
||||
* **exit0 (Tier-2): claim-BEFORE-act (ADR-001 Р-1).** The source of truth is the
|
||||
canonical quality gate, NOT "exit0". If the stage already advanced -> atomic
|
||||
``done`` claim only (idempotent cleanup). Else evaluate the canonical QG
|
||||
READ-ONLY (no side effects, the reconciler pattern): red (e.g. the monitor died
|
||||
before git-push, so no artifact) -> failure path (no false ``done``); green ->
|
||||
atomically claim ``done`` FIRST, and only the claim winner then runs
|
||||
``launcher._try_advance_stage`` (advance + ``enqueue_job`` of the next stage).
|
||||
A tick that loses the claim performs NO side effects, so a late-finalizing
|
||||
monitor / the startup ``requeue_running_jobs`` can never be double-advanced or
|
||||
double-enqueued.
|
||||
* **exit!=0 (Tier-2) / unknown outcome (Tier-1 dead pid, Tier-3 backstop):**
|
||||
``attempts < max_attempts`` -> ``queued`` (mirrors ``requeue_running_jobs``);
|
||||
budget exhausted -> ``failed`` + Telegram. We never fabricate exit0.
|
||||
|
||||
Invariants (ТЗ §8 / ADR-001): never-raise per unit of work; idempotency (atomic
|
||||
guard + gate-driven advance); restart-safe (the reaper starts AFTER the startup
|
||||
``requeue_running_jobs``); silence when nothing is anomalous; the reaper NEVER
|
||||
restarts/kills the prod container and NEVER pushes ``main``. ``STAGE_TRANSITIONS``
|
||||
/ ``QG_CHECKS`` and every ``check_*`` signature are unchanged.
|
||||
|
||||
See docs/work-items/ORCH-065/06-adr/ADR-001-job-reaper-and-lease-reclaim.md and
|
||||
the cross-cutting docs/architecture/adr/adr-0011-job-reaper-lease-reclaim.md.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .config import settings
|
||||
from .db import (
|
||||
get_db,
|
||||
get_running_jobs,
|
||||
reap_running_job,
|
||||
)
|
||||
from .stages import STAGE_TRANSITIONS, get_agent_for_stage
|
||||
|
||||
logger = logging.getLogger("orchestrator.job_reaper")
|
||||
|
||||
|
||||
def reclaim_all_stale_leases() -> int:
|
||||
"""Proactively reclaim dead/stale merge-leases for every in-scope repo.
|
||||
|
||||
Used both at startup (``main.lifespan``, next to ``requeue_running_jobs``) and
|
||||
on every reaper tick (mechanism B). Iterates the merge-gate scope
|
||||
(``merge_gate_repos`` CSV, else self-hosting ``orchestrator``) and calls the
|
||||
never-raise ``merge_gate.reclaim_stale_lease`` per repo. Returns the number of
|
||||
leases actually reclaimed. Never raises (per-repo isolation).
|
||||
"""
|
||||
if not settings.lease_reclaim_enabled:
|
||||
return 0
|
||||
reclaimed = 0
|
||||
try:
|
||||
from . import merge_gate
|
||||
raw = (settings.merge_gate_repos or "").strip()
|
||||
if raw:
|
||||
repos = [r.strip() for r in raw.split(",") if r.strip()]
|
||||
else:
|
||||
from .qg.checks import SELF_HOSTING_REPO
|
||||
repos = [SELF_HOSTING_REPO]
|
||||
for repo in repos:
|
||||
try:
|
||||
if merge_gate.reclaim_stale_lease(repo):
|
||||
reclaimed += 1
|
||||
except Exception as e: # noqa: BLE001 - isolate one repo's failure
|
||||
logger.error("lease-reclaim failed for repo %s: %s", repo, e)
|
||||
except Exception as e: # noqa: BLE001 - never-raise contract
|
||||
logger.error("reclaim_all_stale_leases error: %s", e)
|
||||
return reclaimed
|
||||
|
||||
|
||||
class JobReaper:
|
||||
"""Background daemon that reaps zombie jobs and reclaims stale merge-leases.
|
||||
|
||||
Modelled on ``Reconciler``: a ``threading.Thread(daemon=True)`` + a
|
||||
``threading.Event`` for a clean stop. The only in-memory state is the
|
||||
best-effort Tier-1 dead-pid streak counter (``_streak``) and the
|
||||
observability counters (``reaped_total`` / ``last_reaped`` /
|
||||
``lease_reclaimed_total`` / ``last_run_ts``); all reset on restart, which is
|
||||
safe because the startup ``requeue_running_jobs`` covers the restart path.
|
||||
"""
|
||||
|
||||
def __init__(self, interval_s: float | None = None):
|
||||
self.interval_s = (
|
||||
interval_s if interval_s is not None else settings.reaper_interval_s
|
||||
)
|
||||
self._stop = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
# Tier-1 anti-false-positive: {job_id: consecutive dead-pid ticks}.
|
||||
self._streak: dict[int, int] = {}
|
||||
# Best-effort observability (Р-6).
|
||||
self.last_run_ts: float | None = None
|
||||
self.reaped_total: int = 0
|
||||
self.last_reaped: dict | None = None
|
||||
self.lease_reclaimed_total: int = 0
|
||||
|
||||
# -- A: zombie-job reaping --------------------------------------------
|
||||
def reap_once(self) -> None:
|
||||
"""One scan over all ``running`` jobs (per-job never-raise) + lease reclaim."""
|
||||
if settings.reaper_enabled:
|
||||
try:
|
||||
running = get_running_jobs()
|
||||
except Exception as e: # noqa: BLE001 - never break the tick
|
||||
logger.error("reaper: get_running_jobs failed: %s", e)
|
||||
running = []
|
||||
seen: set[int] = set()
|
||||
for job in running:
|
||||
jid = job.get("id")
|
||||
if jid is not None:
|
||||
seen.add(jid)
|
||||
try:
|
||||
self._reap_job(job)
|
||||
except Exception as e: # noqa: BLE001 - isolate one job's failure
|
||||
logger.error(
|
||||
"reaper: job %s (agent=%s) failed: %s",
|
||||
job.get("id"), job.get("agent"), e,
|
||||
)
|
||||
# Forget streaks for rows that are no longer running (reaped / requeued
|
||||
# / finished by the monitor) so the dict cannot grow unbounded.
|
||||
self._streak = {k: v for k, v in self._streak.items() if k in seen}
|
||||
# Mechanism B: proactive stale/dead lease reclaim (own kill-switch).
|
||||
try:
|
||||
self.lease_reclaimed_total += reclaim_all_stale_leases()
|
||||
except Exception as e: # noqa: BLE001 - never break the tick
|
||||
logger.error("reaper: lease reclaim sweep failed: %s", e)
|
||||
|
||||
def _reap_job(self, job: dict) -> None:
|
||||
"""Apply the three-tier liveness policy to a single running job."""
|
||||
from . import merge_gate
|
||||
|
||||
job_id = job["id"]
|
||||
pid = job.get("pid")
|
||||
age = int(job.get("running_age_s") or 0)
|
||||
exit_code = job.get("exit_code") # from the LEFT JOIN on agent_runs
|
||||
|
||||
# Tier-2: the process finished (exit_code recorded) but the job is still
|
||||
# 'running'. This is AMBIGUOUS: it is BOTH "the monitor died mid-finalize"
|
||||
# AND "a LIVE monitor is still finalizing" — _monitor_agent writes exit_code
|
||||
# FIRST, then does git commit/push (+PR), the БАГ-8 check, network Plane
|
||||
# usage comments (seconds..tens of seconds), and ONLY THEN _try_advance_stage
|
||||
# -> _finalize_job. The agent pid is already dead in BOTH cases, so pid can
|
||||
# NOT disambiguate. We treat it as a dead monitor (KNOWN outcome) only after
|
||||
# a finalization grace: exit_code must have been recorded for at least
|
||||
# `reaper_finalize_grace_s` (FR-1.3/AC-3 — a live finalizing monitor is never
|
||||
# reaped). Within the grace window we leave the row alone (and fall through to
|
||||
# the Tier-3 backstop only, which never trips before the grace given a sane
|
||||
# config where reaper_max_running_s > reaper_finalize_grace_s).
|
||||
if exit_code is not None:
|
||||
self._streak.pop(job_id, None)
|
||||
finished_age = job.get("finished_age_s")
|
||||
grace = int(settings.reaper_finalize_grace_s)
|
||||
if finished_age is not None and int(finished_age) >= grace:
|
||||
self._reap_known_outcome(job, int(exit_code))
|
||||
return
|
||||
logger.info(
|
||||
"reaper: job %s exit_code=%s recorded %ss ago (< grace %ss) — "
|
||||
"deferring (monitor may still be finalizing)",
|
||||
job_id, exit_code, finished_age, grace,
|
||||
)
|
||||
# fall through to the Tier-3 backstop guard below.
|
||||
else:
|
||||
# Tier-1: dead pid, only after `reaper_dead_ticks` consecutive dead ticks.
|
||||
if pid is not None and not merge_gate.pid_alive(pid):
|
||||
n = self._streak.get(job_id, 0) + 1
|
||||
self._streak[job_id] = n
|
||||
if n >= max(int(settings.reaper_dead_ticks), 1):
|
||||
self._streak.pop(job_id, None)
|
||||
self._reap_unknown_outcome(job, reason=f"dead pid={pid}")
|
||||
return
|
||||
logger.info(
|
||||
"reaper: job %s pid=%s dead (streak %d/%d) — deferring",
|
||||
job_id, pid, n, settings.reaper_dead_ticks,
|
||||
)
|
||||
else:
|
||||
# Alive / no pid -> reset the streak (must be CONSECUTIVE).
|
||||
self._streak.pop(job_id, None)
|
||||
|
||||
# Tier-3: backstop ceiling (one-shot; reaps even when liveness is unknown).
|
||||
if age >= int(settings.reaper_max_running_s):
|
||||
self._streak.pop(job_id, None)
|
||||
self._reap_unknown_outcome(
|
||||
job, reason=f"backstop age={age}s>={settings.reaper_max_running_s}s"
|
||||
)
|
||||
|
||||
# -- reap actions ------------------------------------------------------
|
||||
def _reap_known_outcome(self, job: dict, exit_code: int) -> None:
|
||||
"""Tier-2: the agent's exit_code is known; drive the job's terminal status."""
|
||||
if exit_code == 0:
|
||||
self._reap_exit0(job)
|
||||
else:
|
||||
self._reap_unknown_outcome(job, reason=f"exit={exit_code}")
|
||||
|
||||
def _reap_exit0(self, job: dict) -> None:
|
||||
"""Reap an exit0 Tier-2 job with claim-BEFORE-act (ADR-001 Р-1).
|
||||
|
||||
The atomic ``reap_running_job`` claim (guard ``WHERE status='running'``) MUST
|
||||
precede any ``advance_stage`` / ``enqueue_job`` side effect, so a reaper tick
|
||||
that LOSES the row (to a late-finalizing monitor or the startup
|
||||
``requeue_running_jobs``) performs NO side effects — no duplicate advance, no
|
||||
duplicate ``enqueue_job`` of the next stage (FR-1.2/AC-4).
|
||||
|
||||
Because the claim flips the row OUT of 'running', we cannot run the advance
|
||||
first to learn the gate colour. Instead we evaluate the canonical quality gate
|
||||
READ-ONLY (no side effects — the pattern the reconciler uses) to choose the
|
||||
terminal status BEFORE claiming:
|
||||
* already advanced past this agent -> idempotent clean ``done`` (no advance);
|
||||
* gate green -> claim ``done`` first, THEN advance exactly once;
|
||||
* gate red (e.g. monitor died before git-push -> no artifact) -> NOT a real
|
||||
success: route to the retry/fail contract (never a false ``done``).
|
||||
"""
|
||||
job_id = job["id"]
|
||||
run_id = job.get("run_id")
|
||||
agent = job.get("agent")
|
||||
branch, stage, work_item_id = self._task_meta(job)
|
||||
candidates = {s for s in STAGE_TRANSITIONS if get_agent_for_stage(s) == agent}
|
||||
|
||||
if stage is None or stage not in candidates:
|
||||
# Stage already advanced past this agent (or unknown) -> a clean 'done'
|
||||
# is correct WITHOUT re-advancing. Atomic claim only (idempotent cleanup).
|
||||
if reap_running_job(job_id, "done", run_id=run_id):
|
||||
self._note_reap(job, "done", reason="exit0, already advanced")
|
||||
return
|
||||
|
||||
if not branch or not self._gate_is_green(stage, job, branch, work_item_id):
|
||||
# exit0 but the gate is red -> do NOT fabricate 'done'; treat as failure
|
||||
# (retry within budget, else failed + Telegram).
|
||||
self._reap_unknown_outcome(job, reason="exit0 but gate red")
|
||||
return
|
||||
|
||||
# Gate green. CLAIM-BEFORE-ACT: own the row atomically FIRST.
|
||||
if not reap_running_job(job_id, "done", run_id=run_id):
|
||||
# Lost the race -> the winner (late monitor / startup requeue) owns the
|
||||
# advance; we do NOTHING (no duplicate side effects).
|
||||
return
|
||||
# We exclusively own the row now -> drive the gate-based advance exactly once.
|
||||
self._gate_driven_advance(job)
|
||||
self._note_reap(job, "done", reason="exit0, gate green")
|
||||
|
||||
def _gate_is_green(
|
||||
self, stage: str, job: dict, branch: str, work_item_id: str | None
|
||||
) -> bool:
|
||||
"""Read-only canonical-QG evaluation for a reaped exit0 job (no side effects).
|
||||
|
||||
Mirrors the reconciler's cheap pre-evaluation: dispatch the stage's QG via
|
||||
the SAME ``_run_qg`` the webhook path uses, returning its pass/fail WITHOUT
|
||||
running ``advance_stage`` (so no stage move / enqueue / notification happens
|
||||
here). A stage with no registered gate is treated as green (nothing blocks a
|
||||
clean 'done'). Never raises -> any error returns False (conservative: route
|
||||
to retry, never a false 'done').
|
||||
"""
|
||||
try:
|
||||
from .stages import get_qg_for_stage
|
||||
from .stage_engine import _run_qg
|
||||
qg_name = get_qg_for_stage(stage)
|
||||
if not qg_name:
|
||||
return True
|
||||
passed, _reason = _run_qg(qg_name, job.get("repo"), work_item_id, branch)
|
||||
return bool(passed)
|
||||
except Exception as e: # noqa: BLE001 - never break the reap
|
||||
logger.warning(
|
||||
"reaper: gate pre-eval failed for job %s (stage=%s): %s",
|
||||
job.get("id"), stage, e,
|
||||
)
|
||||
return False
|
||||
|
||||
def _reap_unknown_outcome(self, job: dict, reason: str) -> None:
|
||||
"""Tier-1/Tier-3 (or exit!=0): outcome not a clean success.
|
||||
|
||||
Mirrors ``requeue_running_jobs`` / the permanent-failure contract:
|
||||
``attempts < max_attempts`` -> ``queued`` (a retry); budget exhausted ->
|
||||
``failed`` + Telegram. The terminal flip is the atomic ``reap_running_job``
|
||||
guard, so a racing requeue/monitor never double-processes the row.
|
||||
"""
|
||||
job_id = job["id"]
|
||||
run_id = job.get("run_id")
|
||||
attempts = int(job.get("attempts") or 0)
|
||||
max_attempts = int(job.get("max_attempts") or 2)
|
||||
err = f"reaped: {reason} (run_id={run_id})"
|
||||
if attempts < max_attempts:
|
||||
if reap_running_job(job_id, "queued", run_id=run_id, error=err):
|
||||
self._note_reap(job, "queued", reason=reason)
|
||||
else:
|
||||
if reap_running_job(job_id, "failed", run_id=run_id, error=err):
|
||||
self._note_reap(job, "failed", reason=reason)
|
||||
self._notify_failed(job, reason)
|
||||
|
||||
def _gate_driven_advance(self, job: dict) -> bool:
|
||||
"""Idempotent, gate-driven stage advance for a reaped exit0 job.
|
||||
|
||||
Returns True iff the stage is (or has become) advanced past this agent's
|
||||
stage — i.e. the canonical quality gate is satisfied and a clean ``done``
|
||||
is correct. Returns False when the gate is still red (the caller then
|
||||
routes the job to the failure path instead of a false ``done``).
|
||||
|
||||
The advance itself reuses the UNCHANGED ``launcher._try_advance_stage``
|
||||
(which runs the canonical QG and the unified ``advance_stage``); the
|
||||
reaper never duplicates ``update_task_stage`` / ``enqueue_job``.
|
||||
"""
|
||||
agent = job.get("agent")
|
||||
repo = job.get("repo")
|
||||
run_id = job.get("run_id")
|
||||
branch, stage, _wid = self._task_meta(job)
|
||||
# Candidate stages whose finishing agent is THIS agent (deployer maps to
|
||||
# both 'testing' and 'deploy-staging', hence a set).
|
||||
candidates = {s for s in STAGE_TRANSITIONS if get_agent_for_stage(s) == agent}
|
||||
if stage is None or stage not in candidates:
|
||||
# Stage already advanced past this agent (or unknown) -> idempotent
|
||||
# cleanup: a clean 'done' is correct without re-advancing.
|
||||
return True
|
||||
if not branch:
|
||||
return False
|
||||
try:
|
||||
from .agents.launcher import launcher
|
||||
launcher._try_advance_stage(run_id, agent, repo, branch)
|
||||
except Exception as e: # noqa: BLE001 - never break the reap
|
||||
logger.error("reaper: gate-driven advance failed for job %s: %s",
|
||||
job.get("id"), e)
|
||||
return False
|
||||
# Re-read the stage: advanced out of the candidate set -> gate was green.
|
||||
_branch, new_stage, _wid2 = self._task_meta(job)
|
||||
return new_stage is None or new_stage not in candidates
|
||||
|
||||
@staticmethod
|
||||
def _task_meta(job: dict) -> tuple[str | None, str | None, str | None]:
|
||||
"""Resolve (branch, stage, work_item_id) for the job's task. Never raises."""
|
||||
task_id = job.get("task_id")
|
||||
if not task_id:
|
||||
return None, None, None
|
||||
try:
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT branch, stage, work_item_id FROM tasks WHERE id = ?",
|
||||
(task_id,),
|
||||
).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
return None, None, None
|
||||
return row["branch"], row["stage"], row["work_item_id"]
|
||||
except Exception as e: # noqa: BLE001 - never-raise contract
|
||||
logger.warning("reaper: task lookup failed for job %s: %s",
|
||||
job.get("id"), e)
|
||||
return None, None, None
|
||||
|
||||
def _notify_failed(self, job: dict, reason: str) -> None:
|
||||
try:
|
||||
from .notifications import send_telegram
|
||||
send_telegram(
|
||||
f"\U0001f6a8 reaper: job {job.get('id')} ({job.get('agent')}, "
|
||||
f"repo {job.get('repo')}) reaped as FAILED: {reason}"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - telegram best-effort
|
||||
logger.warning("reaper: failed-notify telegram error: %s", e)
|
||||
|
||||
def _note_reap(self, job: dict, outcome: str, reason: str) -> None:
|
||||
"""Record + log one successful reap (Р-6 observability)."""
|
||||
self.reaped_total += 1
|
||||
self.last_reaped = {
|
||||
"job_id": job.get("id"),
|
||||
"agent": job.get("agent"),
|
||||
"outcome": outcome,
|
||||
}
|
||||
logger.warning(
|
||||
"reaper: job %s (agent=%s, repo=%s, run_id=%s, pid=%s) reaped -> %s (%s)",
|
||||
job.get("id"), job.get("agent"), job.get("repo"),
|
||||
job.get("run_id"), job.get("pid"), outcome, reason,
|
||||
)
|
||||
|
||||
# -- loop / lifecycle --------------------------------------------------
|
||||
def _tick(self) -> None:
|
||||
try:
|
||||
self.reap_once()
|
||||
finally:
|
||||
self.last_run_ts = datetime.now(timezone.utc).timestamp()
|
||||
|
||||
def _run(self) -> None:
|
||||
logger.info(
|
||||
"JobReaper started (interval=%ss, enabled=%s, dead_ticks=%s, "
|
||||
"max_running_s=%s, lease_reclaim=%s)",
|
||||
self.interval_s, settings.reaper_enabled, settings.reaper_dead_ticks,
|
||||
settings.reaper_max_running_s, settings.lease_reclaim_enabled,
|
||||
)
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
self._tick()
|
||||
except Exception as e: # noqa: BLE001 - outer never-raise
|
||||
logger.error("JobReaper loop error: %s", e)
|
||||
self._stop.wait(self.interval_s)
|
||||
logger.info("JobReaper stopped")
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the daemon thread (idempotent: a live thread is a no-op)."""
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(
|
||||
target=self._run, name="job-reaper", daemon=True
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, timeout: float = 5.0) -> None:
|
||||
self._stop.set()
|
||||
if self._thread:
|
||||
self._thread.join(timeout=timeout)
|
||||
|
||||
def status(self) -> dict:
|
||||
"""Reaper snapshot for /queue observability (Р-6)."""
|
||||
return {
|
||||
"enabled": settings.reaper_enabled,
|
||||
"interval": self.interval_s,
|
||||
"last_run_ts": self.last_run_ts,
|
||||
"reaped_total": self.reaped_total,
|
||||
"last_reaped": self.last_reaped,
|
||||
"lease_reclaimed_total": self.lease_reclaimed_total,
|
||||
}
|
||||
|
||||
|
||||
# Module-level singleton used by the FastAPI lifespan.
|
||||
reaper = JobReaper()
|
||||
32
src/main.py
32
src/main.py
@@ -60,6 +60,19 @@ async def lifespan(app: FastAPI):
|
||||
if requeued:
|
||||
log.warning(f"Queue-recovery: requeued {requeued} running job(s) after restart")
|
||||
|
||||
# ORCH-065: proactive startup reclaim of dead/stale merge-leases, next to the
|
||||
# queue-recovery above. A lease held by the previous (now dead) process pid is
|
||||
# released at once instead of waiting for the TTL / a foreign acquire so the
|
||||
# next merge is not blocked. Conditional (merge_gate_repos / self-hosting) and
|
||||
# gated by ORCH_LEASE_RECLAIM_ENABLED; never raises.
|
||||
try:
|
||||
from .job_reaper import reclaim_all_stale_leases
|
||||
reclaimed = reclaim_all_stale_leases()
|
||||
if reclaimed:
|
||||
log.warning(f"Startup lease-reclaim: reclaimed {reclaimed} stale merge-lease(s)")
|
||||
except Exception as e:
|
||||
log.warning(f"Startup lease-reclaim skipped: {e}")
|
||||
|
||||
# L-2: rotate old per-run logs at startup (best-effort; never fatal).
|
||||
try:
|
||||
import os as _os
|
||||
@@ -85,13 +98,22 @@ async def lifespan(app: FastAPI):
|
||||
from .reconciler import reconciler
|
||||
reconciler.start()
|
||||
|
||||
# ORCH-065: start the job-reaper LAST (after requeue_running_jobs + the worker
|
||||
# + the reconciler) so its atomic status='running' guard never races the
|
||||
# startup requeue. It reaps zombie jobs and periodically reclaims stale
|
||||
# merge-leases. Kill-switch: ORCH_REAPER_ENABLED.
|
||||
from .job_reaper import reaper
|
||||
reaper.start()
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
# Graceful shutdown order mirrors startup in reverse: stop the reconciler
|
||||
# first (it must not enqueue new work while the worker is winding down),
|
||||
# then the worker. Running agents keep going; their jobs are requeued on
|
||||
# next start via queue-recovery if the process dies.
|
||||
# Graceful shutdown order mirrors startup in reverse: stop the reaper
|
||||
# first, then the reconciler (it must not enqueue new work while the
|
||||
# worker is winding down), then the worker. Running agents keep going;
|
||||
# their jobs are requeued on next start via queue-recovery if the
|
||||
# process dies.
|
||||
reaper.stop()
|
||||
reconciler.stop()
|
||||
worker.stop()
|
||||
|
||||
@@ -123,6 +145,7 @@ async def queue():
|
||||
from .db import job_status_counts, recent_jobs
|
||||
from .queue_worker import worker
|
||||
from .reconciler import reconciler
|
||||
from .job_reaper import reaper
|
||||
from . import post_deploy
|
||||
return {
|
||||
"counts": job_status_counts(),
|
||||
@@ -130,6 +153,7 @@ async def queue():
|
||||
"poll_interval": worker.poll_interval,
|
||||
"resilience": worker.status(),
|
||||
"reconcile": reconciler.status(),
|
||||
"reaper": reaper.status(),
|
||||
"post_deploy": post_deploy.status(),
|
||||
"recent": recent_jobs(10),
|
||||
}
|
||||
|
||||
@@ -338,3 +338,150 @@ def release_merge_lease(repo: str, branch: str | None = None) -> None:
|
||||
return
|
||||
except OSError as e:
|
||||
logger.warning("merge-lease release error for %s: %s", repo, e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065: proactive stale/dead merge-lease reclaim (Problem B)
|
||||
# ---------------------------------------------------------------------------
|
||||
def pid_alive(pid) -> bool:
|
||||
"""Return True iff process ``pid`` is alive (``os.kill(pid, 0)`` liveness probe).
|
||||
|
||||
Semantics (ADR-001 Р-2, never-raise):
|
||||
* ``ProcessLookupError`` -> the process is gone -> ``False`` (reclaimable).
|
||||
* ``PermissionError`` -> the pid exists but is owned by another user ->
|
||||
``True`` (alive; conservatively do NOT reclaim).
|
||||
* missing / invalid pid -> ``True`` (conservative: a lease that predates the
|
||||
pid field, or a malformed pid, is NOT reclaimed on the liveness signal —
|
||||
the TTL backstop still catches it).
|
||||
Never raises; any unexpected OS/type error -> conservative ``True``.
|
||||
"""
|
||||
if not pid:
|
||||
return True
|
||||
try:
|
||||
os.kill(int(pid), 0)
|
||||
return True
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
except (OSError, ValueError, TypeError):
|
||||
return True
|
||||
|
||||
|
||||
def _lease_reclaim_applies(repo: str) -> bool:
|
||||
"""Whether proactive lease-reclaim is REAL for ``repo`` (same scope as merge-gate).
|
||||
|
||||
Reuses ``qg.checks._merge_gate_applies`` (``merge_gate_repos`` CSV, else the
|
||||
self-hosting ``orchestrator``) so reclaim and the gate share one predicate
|
||||
(ADR-001 Р-2 / FR-2.4). Imported lazily to avoid an import cycle (qg.checks
|
||||
imports merge_gate lazily inside ``check_branch_mergeable``). Never raises:
|
||||
any error -> ``False`` (no-op, the safe default).
|
||||
"""
|
||||
try:
|
||||
from .qg.checks import _merge_gate_applies
|
||||
return _merge_gate_applies(repo)
|
||||
except Exception as e: # noqa: BLE001 - never-raise contract
|
||||
logger.warning("lease-reclaim applicability check failed for %s: %s", repo, e)
|
||||
return False
|
||||
|
||||
|
||||
def reclaim_stale_lease(repo: str) -> bool:
|
||||
"""Proactively reclaim a dead/stale merge-lease for ``repo`` (ADR-001 Р-2).
|
||||
|
||||
Unlike the lazy TTL reclaim inside ``acquire_merge_lease`` (which only fires
|
||||
when ANOTHER task tries to acquire), this releases the lease as soon as the
|
||||
holder is provably gone — without waiting for the TTL or a foreign acquire:
|
||||
|
||||
* holder pid is dead (``pid_alive`` is False) -> reclaim, OR
|
||||
* lease age >= ``merge_lock_timeout_s`` (TTL) -> reclaim (AC-7).
|
||||
|
||||
A LIVE holder within its TTL is never touched (AC-8 — protects a legitimate
|
||||
in-flight merge). Reclaim is holder-aware (``release_merge_lease(repo,
|
||||
branch=holder)``) so it can never delete a lease a different task acquired in
|
||||
the meantime. Conditional (FR-2.4): real only for ``merge_gate_repos`` /
|
||||
self-hosting; other repos -> no-op. Kill-switch ``lease_reclaim_enabled``.
|
||||
|
||||
Returns True iff a lease was reclaimed. Never raises (AC-9): any read/remove
|
||||
error is logged and swallowed so a single bad lease never kills the reaper
|
||||
thread. Does NOT run any git operation — only the lease file is removed.
|
||||
"""
|
||||
try:
|
||||
if not settings.lease_reclaim_enabled:
|
||||
return False
|
||||
if not _lease_reclaim_applies(repo):
|
||||
return False
|
||||
path = _lease_path(repo)
|
||||
existing = _read_lease(path)
|
||||
if existing is None:
|
||||
return False # no lease (or unreadable -> _read_lease already logged)
|
||||
holder = existing.get("branch")
|
||||
pid = existing.get("pid")
|
||||
age = time.time() - float(existing.get("acquired_at") or 0)
|
||||
dead = not pid_alive(pid)
|
||||
expired = age >= settings.merge_lock_timeout_s
|
||||
if not (dead or expired):
|
||||
return False # live holder within TTL -> protect legitimate merge
|
||||
why = f"dead pid={pid}" if dead else f"stale age={age:.0f}s>=TTL"
|
||||
release_merge_lease(repo, branch=holder)
|
||||
logger.warning(
|
||||
"merge-lease for %s reclaimed proactively (%s, holder=%s)",
|
||||
repo, why, holder,
|
||||
)
|
||||
try:
|
||||
from .notifications import send_telegram
|
||||
send_telegram(
|
||||
f"\U0001f527 merge-lease для {repo} освобождён проактивно "
|
||||
f"({why}, holder={holder})"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - telegram best-effort, never fatal
|
||||
logger.warning("lease-reclaim telegram failed for %s: %s", repo, e)
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 - never-raise contract
|
||||
logger.warning("reclaim_stale_lease unexpected error for %s: %s", repo, e)
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065: idempotent merge finalization guard (Problem C)
|
||||
# ---------------------------------------------------------------------------
|
||||
def pr_already_merged(repo: str, branch: str) -> bool:
|
||||
"""Return True iff the PR for ``branch`` is ALREADY merged (ADR-001 Р-3, FR-3.2).
|
||||
|
||||
A deterministic, read-only guard the merge path consults BEFORE attempting a
|
||||
(second) merge so a re-driven / reaped task is idempotent: an already-merged
|
||||
PR -> no-op, never a duplicate merge and never an error. This is the ONLY new
|
||||
merge-related helper and it does NOT merge — it only READS the PR state via
|
||||
the existing Gitea client, so it does not introduce duplicate merge logic.
|
||||
|
||||
Consultation point: the actual merge actor is the **deployer agent** (it merges
|
||||
the feature PR at the start of the ``deploy`` stage — see webhooks/gitea.py),
|
||||
so the wiring lives in the deployer prompt (``.openclaw/agents/deployer.md``),
|
||||
which runs this exact function before any (re-)merge. The merge-gate quality
|
||||
check (``qg.checks.check_branch_mergeable``) is intentionally NOT modified
|
||||
(ORCH-065 AC-13: ``check_*`` behaviour unchanged) — it runs on the FIRST
|
||||
deploy-staging -> deploy edge and does not re-run on a ``deploy``-stage re-drive,
|
||||
which is exactly where the second-merge risk lives.
|
||||
|
||||
Queries Gitea ``GET /repos/{owner}/{repo}/pulls?state=all&head=<branch>`` and
|
||||
reports True when any matching PR has ``merged == True``. Never raises (AC-9):
|
||||
any HTTP/parse error -> ``False`` (conservative: "not known-merged" lets the
|
||||
normal gate re-evaluate rather than silently skipping a real merge).
|
||||
"""
|
||||
try:
|
||||
import httpx
|
||||
owner = settings.gitea_owner
|
||||
headers = {"Authorization": f"token {settings.gitea_token}"}
|
||||
resp = httpx.get(
|
||||
f"{settings.gitea_url}/api/v1/repos/{owner}/{repo}/pulls",
|
||||
params={"state": "all", "head": branch},
|
||||
headers=headers, timeout=_SHORT_TIMEOUT,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
return False
|
||||
for pr in resp.json() or []:
|
||||
if pr.get("merged") is True:
|
||||
return True
|
||||
return False
|
||||
except Exception as e: # noqa: BLE001 - never-raise contract
|
||||
logger.warning("pr_already_merged check failed for %s/%s: %s", repo, branch, e)
|
||||
return False
|
||||
|
||||
@@ -107,6 +107,19 @@ _DEFAULT_STATES = {
|
||||
# Feature 2 (verdict statuses) — Approved / Rejected.
|
||||
"approved": "a519a341-dada-4a91-8910-7604f82b79c5",
|
||||
"rejected": "ba958f3c-5db5-461d-8f82-89425e413b97",
|
||||
# ORCH-066 (meaningful Plane status model, layer B): six new logical keys.
|
||||
# Their _DEFAULT_STATES values alias the enduro-trails UUID of their BASE key
|
||||
# (see _STATE_ALIAS_FALLBACK) so a project without these statuses created
|
||||
# (enduro / Plane down / partial config) degrades to the current behaviour
|
||||
# instead of producing an invalid PATCH state. The project-relative
|
||||
# alias-fallback in get_project_states() overrides these with the *project's
|
||||
# own* base UUID on the success path; these defaults are the last resort.
|
||||
"to_analyse": "b873d9eb-993c-48cd-97ac-99a9b1623967", # = in_progress
|
||||
"analysis": "b873d9eb-993c-48cd-97ac-99a9b1623967", # = in_progress
|
||||
"code_review": "ba0d802c-5218-41d4-ab43-978b0ea123ed", # = review
|
||||
"awaiting_deploy": "38fb1f64-aa1e-48a3-92e0-0b109679046b", # = in_review
|
||||
"deploying": "b873d9eb-993c-48cd-97ac-99a9b1623967", # = in_progress
|
||||
"monitoring": "381a2833-3c4e-4be5-bd0f-be84cb946ad8", # = done
|
||||
}
|
||||
|
||||
# Backward-compat alias — do NOT remove (tests + webhooks/plane.py import it).
|
||||
@@ -128,6 +141,29 @@ _PLANE_NAME_TO_KEY: dict[str, str] = {
|
||||
"Needs Input": "needs_input",
|
||||
"In Review": "in_review",
|
||||
"Blocked": "blocked",
|
||||
# ORCH-066: meaningful per-stage / human-input statuses (layer B).
|
||||
"To Analyse": "to_analyse",
|
||||
"Analysis": "analysis",
|
||||
"Code-Review": "code_review",
|
||||
"Awaiting Deploy": "awaiting_deploy",
|
||||
"Deploying": "deploying",
|
||||
"Monitoring after Deploy": "monitoring",
|
||||
}
|
||||
|
||||
# ORCH-066 (BR-12): project-relative alias-fallback for the new logical keys.
|
||||
# After resolving states by name from the Plane API, any NEW key the project did
|
||||
# not define degrades to the UUID of its BASE key **from the same project** — so
|
||||
# the indication falls back to the current status and the PATCH stays valid even
|
||||
# for a partially-configured project. Enduro (none of the new statuses created)
|
||||
# collapses every new key onto its base, i.e. strictly the pre-ORCH-066
|
||||
# behaviour. Strengthened ORCH-059 AC-7 pattern.
|
||||
_STATE_ALIAS_FALLBACK: dict[str, str] = {
|
||||
"to_analyse": "in_progress",
|
||||
"analysis": "in_progress",
|
||||
"code_review": "review",
|
||||
"awaiting_deploy": "in_review",
|
||||
"deploying": "in_progress",
|
||||
"monitoring": "done",
|
||||
}
|
||||
|
||||
# Per-project state cache: {project_id: {logical_key: state_uuid}}
|
||||
@@ -175,6 +211,16 @@ def get_project_states(project_id: str) -> dict[str, str]:
|
||||
if not resolved:
|
||||
raise ValueError("no recognisable states in API response")
|
||||
|
||||
# ORCH-066 (BR-12): project-relative alias-fallback. For each NEW key the
|
||||
# project did not define, reuse the UUID of its BASE key FROM THIS SAME
|
||||
# PROJECT (never a foreign/enduro UUID — that would yield an invalid PATCH
|
||||
# state on a partially-configured orchestrator project). Runs BEFORE the
|
||||
# _DEFAULT_STATES.setdefault below so a project's own base UUID wins over
|
||||
# the static enduro default.
|
||||
for new_key, base_key in _STATE_ALIAS_FALLBACK.items():
|
||||
if new_key not in resolved and resolved.get(base_key):
|
||||
resolved[new_key] = resolved[base_key]
|
||||
|
||||
# Fill any missing keys from _DEFAULT_STATES so callers always get a
|
||||
# complete mapping (defensive against partial Plane configs).
|
||||
for k, v in _DEFAULT_STATES.items():
|
||||
@@ -210,14 +256,16 @@ def reload_project_states(project_id: str = None) -> None:
|
||||
|
||||
|
||||
# Feature 3: map an orchestrator stage -> the Plane status to show on the board
|
||||
# when the pipeline ENTERS that stage. analysis stays driven by the existing
|
||||
# in_progress/in_review/needs_input logic (no dedicated status). deploy keeps
|
||||
# in_progress until done. Needs Input / In Review / Blocked remain higher
|
||||
# priority and are set explicitly elsewhere — do NOT override them from here.
|
||||
# when the pipeline ENTERS that stage. ORCH-066: analysis -> Analysis and
|
||||
# review -> Code-Review now have dedicated statuses. deploy keeps in_progress
|
||||
# until its own Phase A/B/C statuses drive it. Needs Input / In Review / Blocked
|
||||
# remain higher priority and are set explicitly elsewhere — do NOT override them
|
||||
# from here.
|
||||
STAGE_VISIBILITY_STATE = {
|
||||
"analysis": "analysis", # ORCH-066: analysis stage -> Analysis status
|
||||
"architecture": "architecture",
|
||||
"development": "development",
|
||||
"review": "review",
|
||||
"review": "code_review", # ORCH-066: review stage -> Code-Review status
|
||||
"testing": "testing",
|
||||
}
|
||||
|
||||
@@ -225,22 +273,27 @@ STAGE_VISIBILITY_STATE = {
|
||||
# update_issue_state now calls stage_to_state() instead of looking up here.
|
||||
STAGE_TO_STATE = {
|
||||
"created": _DEFAULT_STATES["todo"],
|
||||
"analysis": _DEFAULT_STATES["in_progress"],
|
||||
# ORCH-066: analysis -> Analysis, review -> Code-Review. The new keys alias
|
||||
# the same in_progress / review UUIDs in _DEFAULT_STATES, so legacy callers /
|
||||
# tests that compare against concrete UUIDs see byte-identical values.
|
||||
"analysis": _DEFAULT_STATES["analysis"],
|
||||
"architecture": _DEFAULT_STATES["architecture"],
|
||||
"development": _DEFAULT_STATES["development"],
|
||||
"review": _DEFAULT_STATES["review"],
|
||||
"review": _DEFAULT_STATES["code_review"],
|
||||
"testing": _DEFAULT_STATES["testing"],
|
||||
"deploy": _DEFAULT_STATES["in_progress"],
|
||||
"done": _DEFAULT_STATES["done"],
|
||||
}
|
||||
|
||||
# Map orchestrator stage -> logical state key (project-independent).
|
||||
# ORCH-066: analysis -> analysis, review -> code_review (was in_progress/review).
|
||||
# deploy stays in_progress (Phase A/B/C drive it directly, not update_issue_state).
|
||||
_STAGE_TO_STATE_KEY = {
|
||||
"created": "todo",
|
||||
"analysis": "in_progress",
|
||||
"analysis": "analysis",
|
||||
"architecture": "architecture",
|
||||
"development": "development",
|
||||
"review": "review",
|
||||
"review": "code_review",
|
||||
"testing": "testing",
|
||||
"deploy": "in_progress",
|
||||
"done": "done",
|
||||
@@ -575,6 +628,58 @@ def set_issue_in_progress(work_item_id: str, project_id: str = None):
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_analysis(work_item_id: str, project_id: str = None):
|
||||
"""ORCH-066: set issue to 'Analysis' — analyst is working (start / resume).
|
||||
|
||||
Degrades to the project's In Progress UUID when the 'Analysis' status is not
|
||||
created (alias-fallback). never-raise (via _set_issue_state_direct).
|
||||
"""
|
||||
project_id = _resolve_project_id(work_item_id, project_id)
|
||||
state_id = get_project_states(project_id)["analysis"]
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_code_review(work_item_id: str, project_id: str = None):
|
||||
"""ORCH-066: set issue to 'Code-Review' — review stage indication.
|
||||
|
||||
Degrades to the project's Review UUID when 'Code-Review' is not created.
|
||||
"""
|
||||
project_id = _resolve_project_id(work_item_id, project_id)
|
||||
state_id = get_project_states(project_id)["code_review"]
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_awaiting_deploy(work_item_id: str, project_id: str = None):
|
||||
"""ORCH-066: set issue to 'Awaiting Deploy' — self-deploy Phase A approval-pending.
|
||||
|
||||
Degrades to the project's In Review UUID when 'Awaiting Deploy' is not created.
|
||||
"""
|
||||
project_id = _resolve_project_id(work_item_id, project_id)
|
||||
state_id = get_project_states(project_id)["awaiting_deploy"]
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_deploying(work_item_id: str, project_id: str = None):
|
||||
"""ORCH-066: set issue to 'Deploying' — self-deploy Phase B prod deploy in flight.
|
||||
|
||||
Degrades to the project's In Progress UUID when 'Deploying' is not created.
|
||||
"""
|
||||
project_id = _resolve_project_id(work_item_id, project_id)
|
||||
state_id = get_project_states(project_id)["deploying"]
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_monitoring(work_item_id: str, project_id: str = None):
|
||||
"""ORCH-066: set issue to 'Monitoring after Deploy' — post-deploy window open.
|
||||
|
||||
Degrades to the project's Done UUID when 'Monitoring after Deploy' is not
|
||||
created (so the board shows Done, exactly as before ORCH-066).
|
||||
"""
|
||||
project_id = _resolve_project_id(work_item_id, project_id)
|
||||
state_id = get_project_states(project_id)["monitoring"]
|
||||
_set_issue_state_direct(work_item_id, state_id, project_id)
|
||||
|
||||
|
||||
def set_issue_stage_state(work_item_id: str, stage: str, project_id: str = None):
|
||||
"""Feature 3: move the issue to the board status for a pipeline stage.
|
||||
|
||||
|
||||
@@ -193,12 +193,22 @@ class Reconciler:
|
||||
self._note_unblock(task.get("work_item_id") or str(task_id), stage)
|
||||
|
||||
def _is_blocked_or_needs_input(self, task: dict) -> bool:
|
||||
"""ORCH-060 Guard 2: is this issue in an explicit human Plane gate?
|
||||
"""Guard 2 (ORCH-060 + ORCH-066): is this issue waiting for a human OR in
|
||||
an active orchestrator wait that F-1 must not "revive"?
|
||||
|
||||
Variant A (no schema migration): resolve the task's Plane project, fetch
|
||||
the issue's current state uuid and compare against the project's
|
||||
``blocked`` / ``needs_input`` states. ``tasks`` has no status column, so
|
||||
the live Plane state is the source of truth.
|
||||
the issue's current state uuid and compare against a skip-set. ``tasks``
|
||||
has no status column, so the live Plane state is the source of truth.
|
||||
|
||||
Skip-set = explicit human gates (``blocked`` / ``needs_input``) PLUS the
|
||||
ORCH-066 active waits (``awaiting_deploy`` / ``deploying`` / ``monitoring``,
|
||||
BR-13). **Anti-regress (CRITICAL):** the active-wait keys alias onto
|
||||
``in_review`` / ``in_progress`` / ``done`` on a project that did not create
|
||||
them. Adding them verbatim would make F-1 wrongly skip enduro
|
||||
In Progress / Done tasks (regression of ORCH-053/060). So they are
|
||||
included ONLY when DISTINCT from the project's base working statuses
|
||||
(i.e. actually created as separate statuses): enduro collapses them to {}
|
||||
-> zero regress; orchestrator keeps three real statuses -> BR-13.
|
||||
|
||||
**Never-raise, conservative fallback.** Any error / unresolved project /
|
||||
missing state -> return ``True`` (treat as "possibly blocked" -> skip):
|
||||
@@ -219,7 +229,22 @@ class Reconciler:
|
||||
cur = fetch_issue_state(issue_id, pid)
|
||||
if cur is None:
|
||||
return True # Plane unreachable / no state -> conservative skip
|
||||
return cur in {states.get("blocked"), states.get("needs_input")}
|
||||
# ORCH-066 BR-13: active orchestrator waits, minus base working
|
||||
# statuses so aliased (enduro) keys never widen the skip-set.
|
||||
base_working = {
|
||||
states.get(k) for k in (
|
||||
"backlog", "todo", "in_progress", "in_review", "review",
|
||||
"architecture", "development", "testing",
|
||||
"approved", "rejected", "done",
|
||||
)
|
||||
}
|
||||
extra_waits = {
|
||||
states.get("awaiting_deploy"),
|
||||
states.get("deploying"),
|
||||
states.get("monitoring"),
|
||||
} - base_working - {None}
|
||||
skip_set = {states.get("blocked"), states.get("needs_input")} | extra_waits
|
||||
return cur in skip_set
|
||||
except Exception as e: # noqa: BLE001 - never break the tick
|
||||
logger.warning(
|
||||
f"reconciler Guard 2: blocked-check failed for task "
|
||||
@@ -241,15 +266,19 @@ class Reconciler:
|
||||
def _reconcile_plane_project(self, proj) -> None:
|
||||
pid = proj.plane_project_id
|
||||
# Resolve the actionable state uuids per-project (never hardcode).
|
||||
# ORCH-066 (AC-19): the start/resume trigger is `To Analyse` (was
|
||||
# In Progress). On a project without that status, `to_analyse` aliases to
|
||||
# the project's own `in_progress` UUID, so enduro behaviour is identical
|
||||
# (and `list_issues_by_state` deduplicates the uuid via its internal set).
|
||||
states = get_project_states(pid)
|
||||
in_progress = states["in_progress"]
|
||||
to_analyse = states["to_analyse"]
|
||||
approved = states["approved"]
|
||||
rejected = states["rejected"]
|
||||
issues = list_issues_by_state(pid, [in_progress, approved, rejected])
|
||||
issues = list_issues_by_state(pid, [to_analyse, approved, rejected])
|
||||
for issue in issues:
|
||||
try:
|
||||
self._reconcile_plane_issue(
|
||||
issue, pid, in_progress, approved, rejected
|
||||
issue, pid, to_analyse, approved, rejected
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - isolate one issue's failure
|
||||
logger.error(
|
||||
@@ -258,7 +287,7 @@ class Reconciler:
|
||||
|
||||
def _reconcile_plane_issue(
|
||||
self, issue: dict, project_id: str,
|
||||
in_progress: str, approved: str, rejected: str,
|
||||
to_analyse: str, approved: str, rejected: str,
|
||||
) -> None:
|
||||
issue_id = str(issue.get("id") or "")
|
||||
if not issue_id:
|
||||
@@ -288,10 +317,16 @@ class Reconciler:
|
||||
"description_stripped": issue.get("description_stripped", ""),
|
||||
}
|
||||
|
||||
if new_state == in_progress and task is None:
|
||||
# In Progress without a task -> start the pipeline (lost start webhook).
|
||||
if new_state == to_analyse and task is None:
|
||||
# To Analyse without a task -> start the pipeline (lost start webhook).
|
||||
self._dispatch(handle_status_start, issue_data, project_id)
|
||||
self._note_unblock(issue_id, "analysis")
|
||||
elif new_state == to_analyse and task is not None:
|
||||
# To Analyse with an existing (idle) task -> resume the analyst from
|
||||
# Needs Input (lost resume webhook). handle_status_start applies its
|
||||
# own busy-guard / start-vs-resume fork.
|
||||
self._dispatch(handle_status_start, issue_data, project_id)
|
||||
self._note_unblock(task.get("work_item_id") or issue_id, task["stage"])
|
||||
elif new_state == approved and task is not None:
|
||||
# Approved but the stage never advanced -> replay the verdict.
|
||||
self._dispatch(handle_verdict, issue_data, project_id, approved=True)
|
||||
|
||||
@@ -53,6 +53,10 @@ from .plane_sync import (
|
||||
set_issue_in_progress,
|
||||
set_issue_blocked,
|
||||
set_issue_done,
|
||||
set_issue_analysis,
|
||||
set_issue_awaiting_deploy,
|
||||
set_issue_deploying,
|
||||
set_issue_monitoring,
|
||||
)
|
||||
from .config import settings
|
||||
|
||||
@@ -335,14 +339,28 @@ def advance_stage(
|
||||
# here, so explicitly drive the Plane issue into the terminal Done state
|
||||
# (PLANE_STATES['done'] — mapping unchanged) in addition to the
|
||||
# stage-change comment above.
|
||||
# ORCH-066 (AC-8/AC-9): split terminal-sync by whether post-deploy
|
||||
# monitoring applies. For self-hosting (post_deploy_applies==True) the
|
||||
# task enters a `Monitoring after Deploy` window, NOT terminal Done yet —
|
||||
# the monitor finalises Done/Blocked (run_post_deploy_monitor). For
|
||||
# non-self repos the behaviour is unchanged: terminal Done immediately.
|
||||
# Where the `Monitoring after Deploy` status is absent, set_issue_monitoring
|
||||
# degrades to the project's Done UUID -> identical to today.
|
||||
if next_stage == "done" and work_item_id:
|
||||
try:
|
||||
set_issue_done(work_item_id)
|
||||
logger.info(
|
||||
f"Task {task_id}: deploy->done, Plane state forced to Done"
|
||||
)
|
||||
if post_deploy.post_deploy_applies(repo):
|
||||
set_issue_monitoring(work_item_id)
|
||||
logger.info(
|
||||
f"Task {task_id}: deploy->done (self), Plane state -> "
|
||||
f"Monitoring after Deploy (post-deploy window)"
|
||||
)
|
||||
else:
|
||||
set_issue_done(work_item_id)
|
||||
logger.info(
|
||||
f"Task {task_id}: deploy->done, Plane state forced to Done"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Task {task_id}: failed to set Plane Done: {e}")
|
||||
logger.error(f"Task {task_id}: failed to set Plane terminal state: {e}")
|
||||
|
||||
# ORCH-043: the merge has landed (deploy->done). Release the merge lease as
|
||||
# a backstop in case the PR-merged webhook was lost (holder-aware no-op if a
|
||||
@@ -666,7 +684,9 @@ def _handle_qg_failure_rollbacks(
|
||||
notify_stage_change(task_id, current_stage, "analysis")
|
||||
plane_notify_stage(work_item_id, current_stage, "analysis")
|
||||
result.rolled_back_to = "analysis"
|
||||
set_issue_in_progress(work_item_id)
|
||||
# ORCH-066 (AC-3): rolled back to analysis -> indicate `Analysis`
|
||||
# (degrades to In Progress where the status is not created).
|
||||
set_issue_analysis(work_item_id)
|
||||
with open(conflict_path, "r") as cf:
|
||||
conflict_text = cf.read()[:500]
|
||||
plane_add_comment(
|
||||
@@ -1009,7 +1029,11 @@ def _handle_self_deploy_phase_a(
|
||||
result.note = "self-deploy-approval-pending"
|
||||
|
||||
if work_item_id:
|
||||
set_issue_in_review(work_item_id)
|
||||
# ORCH-066 (AC-6/AC-13): Phase A approval-pending is now `Awaiting Deploy`,
|
||||
# which discharges `In Review` of the deploy-approval meaning (In Review
|
||||
# stays for analyst BRD/review approve-pending only). Degrades to In Review
|
||||
# where the status is not created.
|
||||
set_issue_awaiting_deploy(work_item_id)
|
||||
# ORCH-036: belt-and-suspenders — wipe any STALE deploy-state markers before
|
||||
# arming a fresh approve. A prior FAILED pass clears on rollback, but clearing
|
||||
# here too guarantees the entry to every new prod-deploy pass starts clean
|
||||
@@ -1069,6 +1093,10 @@ def _handle_self_deploy_phase_b(task_id, repo, work_item_id, branch, result: Adv
|
||||
self_deploy.write_marker(
|
||||
repo, work_item_id, self_deploy.INITIATED, content=str(time.time())
|
||||
)
|
||||
# ORCH-066 (AC-7): the prod deploy is now in flight -> indicate `Deploying`
|
||||
# (degrades to In Progress where the status is not created).
|
||||
if work_item_id:
|
||||
set_issue_deploying(work_item_id)
|
||||
task_desc = (
|
||||
f"Work item: {work_item_id}\nRepo: {repo}\nBranch: {branch}\n"
|
||||
f"Stage: deploy\nNote: deploy-finalize poll (prod self-deploy initiated)."
|
||||
@@ -1263,6 +1291,12 @@ def run_post_deploy_monitor(job: dict):
|
||||
settings.post_deploy_window_s, checks_total, checks_failed,
|
||||
)
|
||||
post_deploy.mark_done(repo, work_item_id)
|
||||
# ORCH-066 (AC-10): the post-deploy window closed clean -> terminal Done.
|
||||
if work_item_id:
|
||||
try:
|
||||
set_issue_done(work_item_id)
|
||||
except Exception as e: # noqa: BLE001 - never break the tick
|
||||
logger.warning(f"post-deploy: set Done failed for {work_item_id}: {e}")
|
||||
_notify_post_deploy(
|
||||
work_item_id,
|
||||
f"✅ {work_item_id}: пост-деплой окно завершено чисто "
|
||||
@@ -1303,6 +1337,15 @@ def run_post_deploy_monitor(job: dict):
|
||||
f"self-hosting запрещён (BR-5).",
|
||||
)
|
||||
|
||||
# ORCH-066 (AC-11/AC-12): a confirmed degradation -> indicate `Blocked` for
|
||||
# manual intervention. This is INDICATION ONLY — the tick NEVER restarts /
|
||||
# rolls back the prod container (self-hosting stays ALERT_ONLY, BR-5).
|
||||
if work_item_id:
|
||||
try:
|
||||
set_issue_blocked(work_item_id)
|
||||
except Exception as e: # noqa: BLE001 - never break the tick
|
||||
logger.warning(f"post-deploy: set Blocked failed for {work_item_id}: {e}")
|
||||
|
||||
post_deploy.write_post_deploy_log(
|
||||
repo, work_item_id, branch, post_deploy.DEGRADED, action_taken,
|
||||
settings.post_deploy_window_s, checks_total, checks_failed,
|
||||
|
||||
@@ -147,10 +147,15 @@ async def handle_issue_updated(data: dict, project_id: str = ""):
|
||||
return
|
||||
|
||||
# ORCH-10: resolve expected state UUIDs per the incoming issue's project so
|
||||
# both enduro (b873d9eb) and orchestrator (e331bfb3) In Progress trigger the
|
||||
# both enduro (b873d9eb) and orchestrator (e331bfb3) statuses trigger the
|
||||
# pipeline. Using PLANE_STATES["in_progress"] here was the root-cause blocker.
|
||||
# ORCH-066: the start/resume trigger is now `To Analyse` (human entry-point),
|
||||
# which discharges `In Progress` of its overloaded "start the pipeline"
|
||||
# meaning. Fail-closed: on a project without the `To Analyse` status,
|
||||
# `to_analyse` aliases to the project's own `in_progress` UUID, so moving an
|
||||
# enduro issue to In Progress still triggers start/resume (AC-17).
|
||||
proj_states = get_project_states(project_id)
|
||||
if new_state == proj_states["in_progress"]:
|
||||
if new_state == proj_states["to_analyse"]:
|
||||
await handle_status_start(data, project_id)
|
||||
elif new_state == proj_states["approved"]:
|
||||
await handle_verdict(data, project_id, approved=True)
|
||||
@@ -235,9 +240,14 @@ async def handle_status_start(data: dict, project_id: str = ""):
|
||||
)
|
||||
job_id = enqueue_job(stage_agent, repo, task_desc, task_id=task_id)
|
||||
logger.info(
|
||||
f"Task {task_id}: returned to In Progress (Needs Input answered), "
|
||||
f"Task {task_id}: returned to To Analyse (Needs Input answered), "
|
||||
f"relaunched {stage_agent} for stage {current_stage} (job_id={job_id})"
|
||||
)
|
||||
# ORCH-066 (AC-3): a resume of the analyst (the only Needs-Input owner) is
|
||||
# re-indicated as `Analysis`; other stages keep their own indication.
|
||||
if current_stage == "analysis":
|
||||
from ..plane_sync import set_issue_analysis as _set_analysis
|
||||
_set_analysis(work_item_id)
|
||||
try:
|
||||
_add_comment(
|
||||
work_item_id,
|
||||
@@ -538,6 +548,10 @@ async def start_pipeline(data: dict, project_id: str = ""):
|
||||
)
|
||||
job_id = enqueue_job("analyst", repo, task_desc, task_id=task_id)
|
||||
logger.info(f"Task {task_id}: enqueued analyst (job_id={job_id})")
|
||||
# ORCH-066 (AC-3): indicate the analysis stage with the dedicated
|
||||
# `Analysis` status (degrades to In Progress where it is not created).
|
||||
from ..plane_sync import set_issue_analysis as _set_analysis
|
||||
_set_analysis(work_item_id, plane_project_id)
|
||||
# Post start comment to Plane
|
||||
from ..plane_sync import add_comment as _add_comment
|
||||
_add_comment(work_item_id, "\U0001f50d Analyst \u0437\u0430\u043f\u0443\u0449\u0435\u043d. BRD/\u0422\u0417/AC/TestPlan \u0432 \u0440\u0430\u0431\u043e\u0442\u0435 (\u043e\u0436\u0438\u0434\u0430\u0439\u0442\u0435 8-15 \u043c\u0438\u043d).", author="analyst")
|
||||
@@ -579,9 +593,11 @@ async def _rollback_stage(
|
||||
(via the existing rollback notify + an enqueue of the prev-stage agent).
|
||||
"""
|
||||
if current_stage == "analysis":
|
||||
# Already in analysis — just relaunch analyst with rejection reason
|
||||
from ..plane_sync import set_issue_in_progress
|
||||
set_issue_in_progress(work_item_id)
|
||||
# Already in analysis — just relaunch analyst with rejection reason.
|
||||
# ORCH-066 (AC-3): indicate `Analysis` (degrades to In Progress where the
|
||||
# status is not created).
|
||||
from ..plane_sync import set_issue_analysis
|
||||
set_issue_analysis(work_item_id)
|
||||
task_desc = (
|
||||
f"Work item: {work_item_id}\nRepo: {repo}\nBranch: {branch}\n"
|
||||
f"Stage: analysis\nNote: Stakeholder REJECTED your artifacts. "
|
||||
|
||||
@@ -165,3 +165,82 @@ def test_staging_infra_tolerance_env_override_true(monkeypatch):
|
||||
"""The field is read verbatim from its ORCH_* env var."""
|
||||
monkeypatch.setenv("ORCH_STAGING_INFRA_TOLERANCE_ENABLED", "true")
|
||||
assert Settings().staging_infra_tolerance_enabled is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065 / TC-20: reaper_* + lease_reclaim_* settings defaults + env override.
|
||||
# ---------------------------------------------------------------------------
|
||||
_REAPER_ENV = (
|
||||
"ORCH_REAPER_ENABLED",
|
||||
"ORCH_REAPER_INTERVAL_S",
|
||||
"ORCH_REAPER_DEAD_TICKS",
|
||||
"ORCH_REAPER_MAX_RUNNING_S",
|
||||
"ORCH_LEASE_RECLAIM_ENABLED",
|
||||
)
|
||||
|
||||
|
||||
def test_reaper_settings_defaults(monkeypatch):
|
||||
"""TC-20 / §5: documented defaults when no env is set."""
|
||||
for name in _REAPER_ENV:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
s = Settings()
|
||||
assert s.reaper_enabled is True
|
||||
assert s.reaper_interval_s == 60
|
||||
assert s.reaper_dead_ticks == 2
|
||||
assert s.reaper_max_running_s == 3600
|
||||
assert s.lease_reclaim_enabled is True
|
||||
|
||||
|
||||
def test_reaper_settings_env_override(monkeypatch):
|
||||
"""TC-20 / §5 / AC-14: each field is read from its ORCH_* env var."""
|
||||
monkeypatch.setenv("ORCH_REAPER_ENABLED", "false")
|
||||
monkeypatch.setenv("ORCH_REAPER_INTERVAL_S", "30")
|
||||
monkeypatch.setenv("ORCH_REAPER_DEAD_TICKS", "5")
|
||||
monkeypatch.setenv("ORCH_REAPER_MAX_RUNNING_S", "1200")
|
||||
monkeypatch.setenv("ORCH_LEASE_RECLAIM_ENABLED", "false")
|
||||
s = Settings()
|
||||
assert s.reaper_enabled is False
|
||||
assert s.reaper_interval_s == 30
|
||||
assert s.reaper_dead_ticks == 5
|
||||
assert s.reaper_max_running_s == 1200
|
||||
assert s.lease_reclaim_enabled is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065 / TC-19: contracts unchanged — no new stages / QG checks; the
|
||||
# check_branch_mergeable signature is intact (AC-13).
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc19_stage_transitions_unchanged():
|
||||
"""No new pipeline stage was introduced by ORCH-065."""
|
||||
from src.stages import STAGE_TRANSITIONS
|
||||
assert set(STAGE_TRANSITIONS) == {
|
||||
"created", "analysis", "architecture", "development", "review",
|
||||
"testing", "deploy-staging", "deploy", "done",
|
||||
}
|
||||
|
||||
|
||||
def test_tc19_qg_checks_registry_unchanged():
|
||||
"""No new quality-gate check was added to the registry by ORCH-065."""
|
||||
from src.qg.checks import QG_CHECKS
|
||||
assert set(QG_CHECKS) == {
|
||||
"check_analysis_approved",
|
||||
"check_analysis_complete",
|
||||
"check_architecture_done",
|
||||
"check_ci_green",
|
||||
"check_review_approved",
|
||||
"check_tests_passed",
|
||||
"check_reviewer_verdict",
|
||||
"check_tests_local",
|
||||
"check_deploy_status",
|
||||
"check_staging_status",
|
||||
"check_branch_mergeable",
|
||||
"check_staging_image_fresh",
|
||||
}
|
||||
|
||||
|
||||
def test_tc19_check_branch_mergeable_signature_intact():
|
||||
"""check_branch_mergeable still takes exactly (repo, work_item_id, branch)."""
|
||||
import inspect
|
||||
from src.qg.checks import check_branch_mergeable
|
||||
params = list(inspect.signature(check_branch_mergeable).parameters)
|
||||
assert params == ["repo", "work_item_id", "branch"]
|
||||
|
||||
@@ -48,6 +48,9 @@ def silence_side_effects(monkeypatch):
|
||||
"send_telegram", "plane_notify_stage", "plane_notify_qg", "plane_add_comment",
|
||||
"set_issue_in_review", "set_issue_needs_input", "set_issue_in_progress",
|
||||
"set_issue_blocked", "set_issue_done",
|
||||
# ORCH-066 status setters.
|
||||
"set_issue_analysis", "set_issue_awaiting_deploy", "set_issue_deploying",
|
||||
"set_issue_monitoring",
|
||||
):
|
||||
monkeypatch.setattr(stage_engine, name, MagicMock())
|
||||
|
||||
@@ -127,6 +130,9 @@ def test_tc05_no_approve_does_not_call_prod_hook(monkeypatch):
|
||||
assert _jobs() == []
|
||||
# The restart-safe approve-requested marker was written.
|
||||
assert self_deploy.has_marker("orchestrator", "ORCH-036", self_deploy.APPROVE_REQUESTED)
|
||||
# ORCH-066 AC-6/AC-13: Phase A indicates `Awaiting Deploy`, NOT `In Review`.
|
||||
stage_engine.set_issue_awaiting_deploy.assert_called_once_with("ORCH-036")
|
||||
stage_engine.set_issue_in_review.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -151,6 +157,8 @@ def test_tc06_approved_calls_prod_hook_exactly_once(monkeypatch):
|
||||
# The finalizer was enqueued.
|
||||
assert any(j["agent"] == "deploy-finalizer" for j in _jobs())
|
||||
assert self_deploy.has_marker("orchestrator", "ORCH-036", self_deploy.INITIATED)
|
||||
# ORCH-066 AC-7: Phase B indicates `Deploying` on a successful initiate.
|
||||
stage_engine.set_issue_deploying.assert_called_once_with("ORCH-036")
|
||||
|
||||
# 2nd (duplicate) Approved -> idempotent no-op, hook NOT called again.
|
||||
res2 = advance_stage(
|
||||
|
||||
@@ -45,6 +45,9 @@ def silence_side_effects(monkeypatch):
|
||||
"send_telegram", "plane_notify_stage", "plane_notify_qg", "plane_add_comment",
|
||||
"set_issue_in_review", "set_issue_needs_input", "set_issue_in_progress",
|
||||
"set_issue_blocked", "set_issue_done",
|
||||
# ORCH-066 status setters.
|
||||
"set_issue_analysis", "set_issue_awaiting_deploy", "set_issue_deploying",
|
||||
"set_issue_monitoring",
|
||||
):
|
||||
monkeypatch.setattr(stage_engine, name, MagicMock())
|
||||
|
||||
@@ -106,3 +109,56 @@ def test_tc17_success_deploy_syncs_terminal_done(monkeypatch):
|
||||
release.assert_called_once_with("orchestrator", "feature/ORCH-036-x")
|
||||
# No agent is launched leaving deploy (terminal).
|
||||
assert _jobs() == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-08 (AC-8): self-hosting deploy->done -> Monitoring after Deploy,
|
||||
# NOT terminal Done. The post-deploy monitor finalises.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc08_self_deploy_done_sets_monitoring_not_done(monkeypatch):
|
||||
self_deploy.write_marker("orchestrator", "ORCH-036", self_deploy.RESULT, "0")
|
||||
monkeypatch.setattr(
|
||||
stage_engine, "QG_CHECKS",
|
||||
{**stage_engine.QG_CHECKS, "check_deploy_status": _pass},
|
||||
)
|
||||
monkeypatch.setattr(stage_engine.merge_gate, "release_merge_lease", MagicMock())
|
||||
# post_deploy applies for the self-hosting repo with the monitor enabled.
|
||||
monkeypatch.setattr(stage_engine.post_deploy.settings, "post_deploy_monitor_enabled", True)
|
||||
monkeypatch.setattr(stage_engine.post_deploy.settings, "post_deploy_repos", "")
|
||||
# arm_monitor is orthogonal; stub it so this test stays on the status contract.
|
||||
monkeypatch.setattr(stage_engine.post_deploy, "arm_monitor", MagicMock(return_value=True))
|
||||
|
||||
task_id = _make_task("deploy")
|
||||
stage_engine.run_deploy_finalizer(
|
||||
{"task_id": task_id, "repo": "orchestrator", "id": 1, "agent": "deploy-finalizer"}
|
||||
)
|
||||
|
||||
assert _stage(task_id) == "done"
|
||||
# Self-hosting: the issue enters the Monitoring window, NOT terminal Done yet.
|
||||
stage_engine.set_issue_monitoring.assert_called_once_with("ORCH-036")
|
||||
stage_engine.set_issue_done.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-09 (AC-9): non-self repo deploy->done -> terminal Done (no regress).
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc09_non_self_deploy_done_sets_done(monkeypatch):
|
||||
self_deploy.write_marker("enduro-trails", "ET-042", self_deploy.RESULT, "0")
|
||||
monkeypatch.setattr(
|
||||
stage_engine, "QG_CHECKS",
|
||||
{**stage_engine.QG_CHECKS, "check_deploy_status": _pass},
|
||||
)
|
||||
monkeypatch.setattr(stage_engine.merge_gate, "release_merge_lease", MagicMock())
|
||||
# Monitor enabled, but the empty CSV means it applies ONLY to the self repo;
|
||||
# a non-self repo therefore takes the unchanged terminal-Done path.
|
||||
monkeypatch.setattr(stage_engine.post_deploy.settings, "post_deploy_monitor_enabled", True)
|
||||
monkeypatch.setattr(stage_engine.post_deploy.settings, "post_deploy_repos", "")
|
||||
|
||||
task_id = _make_task("deploy", repo="enduro-trails", branch="feature/ET-042-x", wi="ET-042")
|
||||
stage_engine.run_deploy_finalizer(
|
||||
{"task_id": task_id, "repo": "enduro-trails", "id": 1, "agent": "deploy-finalizer"}
|
||||
)
|
||||
|
||||
assert _stage(task_id) == "done"
|
||||
stage_engine.set_issue_done.assert_called_once_with("ET-042")
|
||||
stage_engine.set_issue_monitoring.assert_not_called()
|
||||
|
||||
388
tests/test_job_reaper.py
Normal file
388
tests/test_job_reaper.py
Normal file
@@ -0,0 +1,388 @@
|
||||
"""ORCH-065: job-reaper unit tests (TC-01..TC-08, TC-21).
|
||||
|
||||
The reaper never spawns claude; we drive the DB directly (a 'running' jobs row +
|
||||
optional agent_runs exit_code/pid) and assert the terminal flip + side-effects.
|
||||
``os.kill`` liveness is monkeypatched so a 'dead'/'alive' pid is deterministic.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
# Override env before importing app modules (same convention as test_queue.py).
|
||||
os.environ["ORCH_DB_PATH"] = os.path.join(tempfile.gettempdir(), "test_orch_reaper.db")
|
||||
os.environ["ORCH_REPOS_DIR"] = tempfile.gettempdir()
|
||||
os.environ["ORCH_GITEA_TOKEN"] = "test-token"
|
||||
os.environ["ORCH_PLANE_API_TOKEN"] = "test-token"
|
||||
|
||||
import src.db as db
|
||||
from src.db import init_db, get_db, enqueue_job, get_job
|
||||
import src.job_reaper as jr
|
||||
from src.job_reaper import JobReaper
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_db(tmp_path, monkeypatch):
|
||||
dbfile = tmp_path / "reaper.db"
|
||||
monkeypatch.setattr(db.settings, "db_path", str(dbfile))
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
# --- helpers ----------------------------------------------------------------
|
||||
def _make_running_job(agent="developer", repo="orchestrator", task_id=None,
|
||||
pid=None, age_s=0, attempts=0, max_attempts=2,
|
||||
run_id=None, exit_code=None, finished_age_s=600):
|
||||
"""Insert a job already in 'running' with the given pid/age/attempts.
|
||||
|
||||
started_at is back-dated by ``age_s`` seconds so running_age_s reflects it.
|
||||
When ``exit_code`` is given an agent_runs row is created and linked (Tier-2);
|
||||
its ``finished_at`` is back-dated by ``finished_age_s`` seconds so the
|
||||
Tier-2 finalization grace (``reaper_finalize_grace_s``, default 300) is
|
||||
satisfied by default — pass a small ``finished_age_s`` to exercise the
|
||||
"monitor may still be finalizing" deferral.
|
||||
"""
|
||||
conn = get_db()
|
||||
if run_id is None and exit_code is not None:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO agent_runs (task_id, agent, finished_at, exit_code) "
|
||||
"VALUES (?, ?, datetime('now', ?), ?)",
|
||||
(task_id, agent, f"-{int(finished_age_s)} seconds", exit_code),
|
||||
)
|
||||
run_id = cur.lastrowid
|
||||
cur = conn.execute(
|
||||
"INSERT INTO jobs (agent, repo, task_id, status, attempts, max_attempts, "
|
||||
"run_id, pid, started_at) "
|
||||
"VALUES (?, ?, ?, 'running', ?, ?, ?, ?, datetime('now', ?))",
|
||||
(agent, repo, task_id, attempts, max_attempts, run_id, pid,
|
||||
f"-{int(age_s)} seconds"),
|
||||
)
|
||||
job_id = cur.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return job_id
|
||||
|
||||
|
||||
def _make_task(repo="orchestrator", branch="feature/x", stage="development",
|
||||
work_item_id="ORCH-1"):
|
||||
conn = get_db()
|
||||
cur = conn.execute(
|
||||
"INSERT INTO tasks (plane_id, work_item_id, repo, branch, stage) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
(work_item_id, work_item_id, repo, branch, stage),
|
||||
)
|
||||
tid = cur.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return tid
|
||||
|
||||
|
||||
def _dead_pid(monkeypatch):
|
||||
"""Force merge_gate.pid_alive -> False (process gone) for the reaper."""
|
||||
import src.merge_gate as mg
|
||||
monkeypatch.setattr(mg, "pid_alive", lambda pid: False)
|
||||
|
||||
|
||||
def _alive_pid(monkeypatch):
|
||||
import src.merge_gate as mg
|
||||
monkeypatch.setattr(mg, "pid_alive", lambda pid: True)
|
||||
|
||||
|
||||
# --- TC-01: dead executor -> reaped without process restart -----------------
|
||||
def test_tc01_dead_pid_reaped_to_queued(monkeypatch):
|
||||
_dead_pid(monkeypatch)
|
||||
jid = _make_running_job(pid=999999, attempts=0, max_attempts=2)
|
||||
r = JobReaper()
|
||||
r.reap_once() # tick 1 (streak=1, dead_ticks default 2 -> not yet)
|
||||
assert get_job(jid)["status"] == "running"
|
||||
r.reap_once() # tick 2 -> reaped
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
assert r.reaped_total == 1
|
||||
assert r.last_reaped["job_id"] == jid
|
||||
|
||||
|
||||
# --- TC-02: live agent within timeout is NEVER reaped -----------------------
|
||||
def test_tc02_alive_pid_never_reaped(monkeypatch):
|
||||
_alive_pid(monkeypatch)
|
||||
jid = _make_running_job(pid=4321, age_s=10)
|
||||
r = JobReaper()
|
||||
for _ in range(5):
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "running"
|
||||
assert r.reaped_total == 0
|
||||
|
||||
|
||||
def test_tc02_alive_within_max_running_not_reaped(monkeypatch):
|
||||
_alive_pid(monkeypatch)
|
||||
monkeypatch.setattr(db.settings, "reaper_max_running_s", 3600)
|
||||
jid = _make_running_job(pid=4321, age_s=1800) # < ceiling, alive
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "running"
|
||||
|
||||
|
||||
# --- TC-03: zombie only after reaper_dead_ticks consecutive ticks -----------
|
||||
def test_tc03_requires_consecutive_dead_ticks(monkeypatch):
|
||||
monkeypatch.setattr(db.settings, "reaper_dead_ticks", 3)
|
||||
import src.merge_gate as mg
|
||||
# Dead, dead, ALIVE (resets), dead, dead, dead -> reaped only on the 6th tick.
|
||||
seq = iter([False, False, True, False, False, False])
|
||||
monkeypatch.setattr(mg, "pid_alive", lambda pid: next(seq))
|
||||
jid = _make_running_job(pid=999998)
|
||||
r = JobReaper()
|
||||
for _ in range(5):
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "running"
|
||||
r.reap_once() # 6th tick: third CONSECUTIVE dead -> reaped
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
|
||||
|
||||
# --- TC-04: backstop ceiling reaps even when liveness is unknown ------------
|
||||
def test_tc04_backstop_ceiling(monkeypatch):
|
||||
_alive_pid(monkeypatch) # liveness says "alive", but age exceeds the ceiling
|
||||
monkeypatch.setattr(db.settings, "reaper_max_running_s", 100)
|
||||
jid = _make_running_job(pid=4321, age_s=500)
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
assert r.reaped_total == 1
|
||||
|
||||
|
||||
def test_tc04_backstop_no_pid(monkeypatch):
|
||||
monkeypatch.setattr(db.settings, "reaper_max_running_s", 100)
|
||||
jid = _make_running_job(pid=None, age_s=500)
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
|
||||
|
||||
# --- TC-05: correct outcome by exit_code (Tier-2) ---------------------------
|
||||
def _gate(monkeypatch, green: bool):
|
||||
"""Force the reaper's READ-ONLY gate pre-evaluation to green/red."""
|
||||
monkeypatch.setattr(
|
||||
JobReaper, "_gate_is_green",
|
||||
lambda self, stage, job, branch, wid: green,
|
||||
)
|
||||
|
||||
|
||||
def test_tc05_exit0_gate_green_done(monkeypatch):
|
||||
# A developer job runs to LEAVE the 'architecture' stage (-> 'development').
|
||||
tid = _make_task(stage="architecture")
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0)
|
||||
_gate(monkeypatch, green=True)
|
||||
# gate green -> the claim flips 'done' FIRST, then the advance runs.
|
||||
import src.agents.launcher as L
|
||||
monkeypatch.setattr(
|
||||
L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: db.update_task_stage(tid, "development"),
|
||||
)
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "done"
|
||||
|
||||
|
||||
def test_tc05_exit0_gate_red_requeues(monkeypatch):
|
||||
tid = _make_task(stage="architecture")
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0,
|
||||
attempts=0, max_attempts=2)
|
||||
_gate(monkeypatch, green=False) # read-only pre-eval says red
|
||||
# The advance path must NEVER run when the gate is red (claim-before-act).
|
||||
import src.agents.launcher as L
|
||||
called = []
|
||||
monkeypatch.setattr(L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: called.append(1))
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "queued" # exit0 but gate red -> not 'done'
|
||||
assert not called, "no advance/side-effects on a red gate"
|
||||
|
||||
|
||||
def test_tc05_exit0_already_advanced_done_no_side_effects(monkeypatch):
|
||||
# Stage already past the developer candidate set -> idempotent clean 'done'
|
||||
# with NO advance call (the monitor already advanced before dying).
|
||||
tid = _make_task(stage="development") # developer's candidate is 'architecture'
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0)
|
||||
import src.agents.launcher as L
|
||||
called = []
|
||||
monkeypatch.setattr(L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: called.append(1))
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "done"
|
||||
assert not called, "already-advanced reap must not re-advance"
|
||||
|
||||
|
||||
def test_tc05_nonzero_exit_requeue_then_failed(monkeypatch):
|
||||
sent = []
|
||||
monkeypatch.setattr(jr, "JobReaper", JobReaper)
|
||||
tid = _make_task(stage="development")
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=1,
|
||||
attempts=1, max_attempts=2)
|
||||
r = JobReaper()
|
||||
import src.notifications as notif
|
||||
monkeypatch.setattr(notif, "send_telegram", lambda *a, **k: sent.append(a))
|
||||
r.reap_once() # attempts(1) < max(2) -> queued
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
|
||||
# Now exhaust the budget.
|
||||
jid2 = _make_running_job(agent="developer", task_id=tid, exit_code=1,
|
||||
attempts=2, max_attempts=2)
|
||||
r.reap_once()
|
||||
assert get_job(jid2)["status"] == "failed"
|
||||
assert sent, "failed reap must send a Telegram alert"
|
||||
|
||||
|
||||
# --- TC-05b: Tier-2 finalization grace (live monitor still finalizing) -------
|
||||
def test_tc05_tier2_within_grace_not_reaped(monkeypatch):
|
||||
"""exit_code freshly recorded -> a LIVE monitor may still be finalizing.
|
||||
|
||||
The reaper must NOT reap it within ``reaper_finalize_grace_s`` (FR-1.3/AC-3:
|
||||
a live finalizing monitor — git push / PR / Plane comments — is never reaped,
|
||||
no dup advance / enqueue).
|
||||
"""
|
||||
monkeypatch.setattr(db.settings, "reaper_finalize_grace_s", 300)
|
||||
tid = _make_task(stage="architecture")
|
||||
# exit_code recorded only 5s ago -> still inside the finalization grace.
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0,
|
||||
finished_age_s=5)
|
||||
import src.agents.launcher as L
|
||||
called = []
|
||||
monkeypatch.setattr(L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: called.append(1))
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "running" # deferred, NOT reaped
|
||||
assert r.reaped_total == 0
|
||||
assert not called, "a live finalizing monitor must not be advanced by the reaper"
|
||||
|
||||
|
||||
def test_tc05_tier2_after_grace_reaped(monkeypatch):
|
||||
"""Once exit_code has been recorded longer than the grace, the monitor is
|
||||
genuinely dead and the Tier-2 reap proceeds."""
|
||||
monkeypatch.setattr(db.settings, "reaper_finalize_grace_s", 300)
|
||||
tid = _make_task(stage="architecture")
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0,
|
||||
finished_age_s=600) # well past the grace
|
||||
_gate(monkeypatch, green=True)
|
||||
import src.agents.launcher as L
|
||||
monkeypatch.setattr(
|
||||
L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: db.update_task_stage(tid, "development"),
|
||||
)
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "done"
|
||||
|
||||
|
||||
def test_tc05_tier2_lost_claim_no_side_effects(monkeypatch):
|
||||
"""claim-BEFORE-act: when another actor (a late monitor / startup requeue)
|
||||
moves the row out of 'running' AFTER the reaper read it but BEFORE the atomic
|
||||
claim, the reaper's claim loses (rowcount==0) and it performs NO advance side
|
||||
effects (no dup advance / dup enqueue) — ADR-001 Р-1."""
|
||||
monkeypatch.setattr(db.settings, "reaper_finalize_grace_s", 0)
|
||||
tid = _make_task(stage="architecture")
|
||||
jid = _make_running_job(agent="developer", task_id=tid, exit_code=0,
|
||||
finished_age_s=10)
|
||||
import src.agents.launcher as L
|
||||
called = []
|
||||
monkeypatch.setattr(L.launcher, "_try_advance_stage",
|
||||
lambda run_id, agent, repo, branch: called.append(1))
|
||||
|
||||
# The read-only gate pre-eval reports green, but the row is concurrently
|
||||
# claimed by someone else right before the reaper's atomic claim runs.
|
||||
def green_then_steal(self, stage, job, branch, wid):
|
||||
db.requeue_running_jobs() # another actor wins the 'running' row first
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(JobReaper, "_gate_is_green", green_then_steal)
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
# Reaper lost the atomic claim -> no advance, no double work. The row stays
|
||||
# where the winner left it ('queued'), not flipped to 'done' by the reaper.
|
||||
assert not called, "reaper that lost the claim must not advance/enqueue"
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
assert r.reaped_total == 0
|
||||
|
||||
|
||||
# --- TC-06: atomicity — reaper vs requeue_running_jobs (status guard) --------
|
||||
def test_tc06_atomic_no_double_reap(monkeypatch):
|
||||
_dead_pid(monkeypatch)
|
||||
monkeypatch.setattr(db.settings, "reaper_dead_ticks", 1)
|
||||
jid = _make_running_job(pid=999997, attempts=0, max_attempts=2)
|
||||
# Simulate the startup requeue winning the row first.
|
||||
n = db.requeue_running_jobs()
|
||||
assert n == 1
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
# The reaper now scans: the row is no longer 'running' -> reap_running_job's
|
||||
# WHERE status='running' guard yields rowcount 0 -> no second processing.
|
||||
r = JobReaper()
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
assert r.reaped_total == 0
|
||||
|
||||
|
||||
def test_tc06_reap_running_job_guard_returns_false_when_not_running():
|
||||
jid = enqueue_job("developer", "orchestrator") # status 'queued', not running
|
||||
assert db.reap_running_job(jid, "done") is False
|
||||
assert get_job(jid)["status"] == "queued"
|
||||
|
||||
|
||||
# --- TC-07: kill-switch reaper_enabled=False -> no-op -----------------------
|
||||
def test_tc07_kill_switch(monkeypatch):
|
||||
_dead_pid(monkeypatch)
|
||||
monkeypatch.setattr(db.settings, "reaper_enabled", False)
|
||||
monkeypatch.setattr(db.settings, "lease_reclaim_enabled", False)
|
||||
jid = _make_running_job(pid=999996, age_s=99999)
|
||||
r = JobReaper()
|
||||
for _ in range(3):
|
||||
r.reap_once()
|
||||
assert get_job(jid)["status"] == "running"
|
||||
assert r.reaped_total == 0
|
||||
|
||||
|
||||
# --- TC-08: never-raise — a DB/OS error in one tick does not propagate -------
|
||||
def test_tc08_never_raise_isolates_per_job(monkeypatch):
|
||||
_dead_pid(monkeypatch)
|
||||
monkeypatch.setattr(db.settings, "reaper_dead_ticks", 1)
|
||||
good = _make_running_job(pid=111, attempts=0, max_attempts=2)
|
||||
bad = _make_running_job(pid=222, attempts=0, max_attempts=2)
|
||||
|
||||
r = JobReaper()
|
||||
orig = r._reap_job
|
||||
|
||||
def boom(job):
|
||||
if job["id"] == bad:
|
||||
raise RuntimeError("simulated per-job failure")
|
||||
return orig(job)
|
||||
|
||||
monkeypatch.setattr(r, "_reap_job", boom)
|
||||
# Must not raise despite the bad job blowing up.
|
||||
r.reap_once()
|
||||
# The good job is still reaped; the bad one is isolated (stays running).
|
||||
assert get_job(good)["status"] == "queued"
|
||||
assert get_job(bad)["status"] == "running"
|
||||
|
||||
|
||||
def test_tc08_reap_once_outer_never_raises(monkeypatch):
|
||||
monkeypatch.setattr(jr, "get_running_jobs",
|
||||
lambda: (_ for _ in ()).throw(RuntimeError("db down")))
|
||||
r = JobReaper()
|
||||
# reap_once swallows... actually get_running_jobs is iterated in the for; the
|
||||
# _tick wrapper guarantees the loop never dies. Assert _tick is safe.
|
||||
r._tick()
|
||||
assert r.last_run_ts is not None
|
||||
|
||||
|
||||
# --- TC-21: startup lease-reclaim + reaper start/stop smoke -----------------
|
||||
def test_tc21_reaper_start_stop_smoke():
|
||||
r = JobReaper(interval_s=0.05)
|
||||
r.start()
|
||||
assert r._thread is not None and r._thread.is_alive()
|
||||
r.stop(timeout=2)
|
||||
assert not r._thread.is_alive()
|
||||
|
||||
|
||||
def test_tc21_reclaim_all_stale_leases_callable(monkeypatch):
|
||||
# No lease files present -> 0 reclaimed, never raises (registration smoke).
|
||||
monkeypatch.setattr(db.settings, "lease_reclaim_enabled", True)
|
||||
assert jr.reclaim_all_stale_leases() == 0
|
||||
@@ -40,11 +40,15 @@ ENDURO_PLANE_ID = "7a79f0a9-5278-49cd-9007-9a338f238f9c"
|
||||
_PROJECT_STATES = {
|
||||
ENDURO_PLANE_ID: {
|
||||
"in_progress": "b873d9eb-993c-48cd-97ac-99a9b1623967",
|
||||
# ORCH-066: To Analyse is the start trigger; with the status absent it
|
||||
# aliases to in_progress (the real get_project_states fallback).
|
||||
"to_analyse": "b873d9eb-993c-48cd-97ac-99a9b1623967",
|
||||
"approved": "a519a341-dada-4a91-8910-7604f82b79c5",
|
||||
"rejected": "ba958f3c-5db5-461d-8f82-89425e413b97",
|
||||
},
|
||||
ORCH_PLANE_ID: {
|
||||
"in_progress": "e331bfb3-e17e-4699-ba48-4abb89c21b7b",
|
||||
"to_analyse": "e331bfb3-e17e-4699-ba48-4abb89c21b7b",
|
||||
"approved": "63f2c8fe-dcda-4ace-952f-dd88bd0118ff",
|
||||
"rejected": "4c769e90-bf80-4a52-b97a-e1c84904bfc3",
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
# Env before importing app modules (same convention as the other suites).
|
||||
@@ -299,3 +300,85 @@ def test_tc11_release_missing_is_noop(lease_dir):
|
||||
# Releasing a non-existent lease never raises.
|
||||
merge_gate.release_merge_lease("orchestrator", "feature/none")
|
||||
merge_gate.release_merge_lease("orchestrator") # force form
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065 / TC-16: idempotent merge finalization — pr_already_merged guard.
|
||||
# ---------------------------------------------------------------------------
|
||||
class _FakeResp:
|
||||
def __init__(self, status_code, payload):
|
||||
self.status_code = status_code
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def test_tc16_pr_already_merged_true(monkeypatch):
|
||||
"""A merged PR -> True so a re-driven/reaped task is a no-op (no second merge)."""
|
||||
monkeypatch.setattr(
|
||||
httpx, "get",
|
||||
lambda *a, **k: _FakeResp(200, [{"number": 7, "merged": True}]),
|
||||
)
|
||||
assert merge_gate.pr_already_merged("orchestrator", "feature/x") is True
|
||||
|
||||
|
||||
def test_tc16_pr_open_not_merged_false(monkeypatch):
|
||||
"""An open / not-yet-merged PR -> False (the normal merge path proceeds)."""
|
||||
monkeypatch.setattr(
|
||||
httpx, "get",
|
||||
lambda *a, **k: _FakeResp(200, [{"number": 7, "merged": False}]),
|
||||
)
|
||||
assert merge_gate.pr_already_merged("orchestrator", "feature/x") is False
|
||||
|
||||
|
||||
def test_tc16_pr_no_pr_false(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
httpx, "get", lambda *a, **k: _FakeResp(200, []),
|
||||
)
|
||||
assert merge_gate.pr_already_merged("orchestrator", "feature/x") is False
|
||||
|
||||
|
||||
def test_tc16_pr_already_merged_never_raises(monkeypatch):
|
||||
"""Any HTTP/parse error -> False (conservative), never an exception (AC-9)."""
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("gitea down")
|
||||
|
||||
monkeypatch.setattr(httpx, "get", boom)
|
||||
assert merge_gate.pr_already_merged("orchestrator", "feature/x") is False
|
||||
|
||||
|
||||
def test_tc16_pr_non_200_false(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
httpx, "get", lambda *a, **k: _FakeResp(500, None),
|
||||
)
|
||||
assert merge_gate.pr_already_merged("orchestrator", "feature/x") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065 / TC-16 (wiring): the merge path consults the guard.
|
||||
#
|
||||
# pr_already_merged is consulted by the actual merge actor — the deployer agent
|
||||
# (webhooks/gitea.py: "the deployer merges the PR at the START of its run"). The
|
||||
# `deploy` stage can be re-driven by the job-reaper, so the deployer prompt MUST
|
||||
# instruct an idempotent pre-merge consult of pr_already_merged (ADR-001 Р-3 /
|
||||
# README / CHANGELOG). This test fails if that wiring regresses, so the guard can
|
||||
# never silently become dead code again while the docs claim it is consulted.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc16_deployer_prompt_consults_guard():
|
||||
"""The deployer prompt (merge path) wires the idempotent merge guard."""
|
||||
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
prompt_path = os.path.join(repo_root, ".openclaw", "agents", "deployer.md")
|
||||
with open(prompt_path, "r", encoding="utf-8") as f:
|
||||
prompt = f.read()
|
||||
|
||||
# The guard function is named and the prompt instructs consulting it BEFORE merge.
|
||||
assert "pr_already_merged" in prompt, "deployer prompt must name the guard"
|
||||
lowered = prompt.lower()
|
||||
assert "before" in lowered and "merge" in lowered, (
|
||||
"deployer prompt must instruct consulting the guard BEFORE merging"
|
||||
)
|
||||
# The idempotent no-op contract (already merged -> no second merge) is documented.
|
||||
assert "no second merge" in lowered, (
|
||||
"deployer prompt must document the already-merged no-op (AC-11)"
|
||||
)
|
||||
|
||||
@@ -148,3 +148,63 @@ def test_tc24_red_catch_up_fails_and_releases_main_stays_green(race_repo, monkey
|
||||
assert _origin_main_sha(origin) == main_before
|
||||
# The lease was released on failure (a later task can proceed).
|
||||
assert merge_gate._read_lease(merge_gate._lease_path(repo)) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065 / TC-17: recovery — "rebase+re-test green, merge not done, process
|
||||
# died" -> reaper requeues -> the merge re-drives the STANDARD path WITHOUT a
|
||||
# second expensive re-test when safe (the branch is already up-to-date). AC-10.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc17_redrive_skips_expensive_retest_when_already_caught_up(
|
||||
race_repo, monkeypatch
|
||||
):
|
||||
repo, origin = race_repo
|
||||
main_before = _origin_main_sha(origin)
|
||||
|
||||
# First pass: B catches up (real rebase onto C1) with a GREEN re-test. This is
|
||||
# the work that completed before the process died — the lease is held, the
|
||||
# branch is now caught up on origin.
|
||||
retest_calls = []
|
||||
|
||||
def _retest(r, b):
|
||||
retest_calls.append((r, b))
|
||||
return True, "re-test green"
|
||||
|
||||
monkeypatch.setattr(merge_gate, "retest_branch", _retest)
|
||||
passed, reason = check_branch_mergeable(repo, "ORCH-B", "feature/B")
|
||||
assert passed is True
|
||||
assert reason == "rebased onto main, re-test green"
|
||||
assert len(retest_calls) == 1 # the expensive re-test ran ONCE
|
||||
|
||||
# The process "died" before the merge: release the lease the way the reaper /
|
||||
# reconciler recovery path would (the row is requeued; the branch stays caught
|
||||
# up because the rebase was already pushed).
|
||||
merge_gate.release_merge_lease(repo, "feature/B")
|
||||
|
||||
# Re-drive (standard path) after recovery: the branch already contains
|
||||
# origin/main, so branch_is_behind_main is False and the gate short-circuits to
|
||||
# the up-to-date pass WITHOUT re-running the expensive rebase+re-test.
|
||||
assert merge_gate.branch_is_behind_main(repo, "feature/B") is False
|
||||
passed2, reason2 = check_branch_mergeable(repo, "ORCH-B", "feature/B")
|
||||
assert passed2 is True
|
||||
assert reason2 == "branch up-to-date with main"
|
||||
assert len(retest_calls) == 1 # NOT re-run on the re-drive (no double cost)
|
||||
# origin/main was never pushed by the gate across the whole recovery.
|
||||
assert _origin_main_sha(origin) == main_before
|
||||
|
||||
|
||||
def test_tc17_pr_already_merged_makes_redrive_a_noop(race_repo, monkeypatch):
|
||||
"""If the PR actually merged before the process died, the idempotency guard
|
||||
reports it so the re-drive is a no-op (no second merge)."""
|
||||
import httpx
|
||||
repo, _ = race_repo
|
||||
|
||||
class _R:
|
||||
status_code = 200
|
||||
|
||||
@staticmethod
|
||||
def json():
|
||||
return [{"merged": True}]
|
||||
|
||||
monkeypatch.setattr(httpx, "get", lambda *a, **k: _R())
|
||||
assert merge_gate.pr_already_merged(repo, "feature/B") is True
|
||||
|
||||
138
tests/test_merge_lease_reclaim.py
Normal file
138
tests/test_merge_lease_reclaim.py
Normal file
@@ -0,0 +1,138 @@
|
||||
"""ORCH-065: proactive stale/dead merge-lease reclaim (TC-10..TC-15).
|
||||
|
||||
Exercises merge_gate.reclaim_stale_lease / pid_alive directly with lease files
|
||||
written into a tmp repos_dir. No git ops run (reclaim only removes the lease
|
||||
file). pid liveness is monkeypatched so 'dead'/'alive' are deterministic.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ["ORCH_DB_PATH"] = os.path.join(tempfile.gettempdir(), "test_orch_lease.db")
|
||||
os.environ["ORCH_REPOS_DIR"] = tempfile.gettempdir()
|
||||
os.environ["ORCH_GITEA_TOKEN"] = "test-token"
|
||||
os.environ["ORCH_PLANE_API_TOKEN"] = "test-token"
|
||||
|
||||
from src import merge_gate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repos_dir(tmp_path, monkeypatch):
|
||||
d = tmp_path / "repos"
|
||||
d.mkdir()
|
||||
monkeypatch.setattr(merge_gate.settings, "repos_dir", str(d))
|
||||
monkeypatch.setattr(merge_gate.settings, "lease_reclaim_enabled", True)
|
||||
monkeypatch.setattr(merge_gate.settings, "merge_gate_repos", "") # self-hosting only
|
||||
monkeypatch.setattr(merge_gate.settings, "merge_lock_timeout_s", 300)
|
||||
return d
|
||||
|
||||
|
||||
def _write_lease(repos_dir, repo, branch="feature/x", pid=1234, age_s=0):
|
||||
path = os.path.join(str(repos_dir), f".merge-lease-{repo}.json")
|
||||
holder = {
|
||||
"branch": branch,
|
||||
"work_item_id": "ORCH-1",
|
||||
"task_id": 1,
|
||||
"acquired_at": time.time() - age_s,
|
||||
"pid": pid,
|
||||
}
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps(holder))
|
||||
return path
|
||||
|
||||
|
||||
def _no_telegram(monkeypatch):
|
||||
import src.notifications as notif
|
||||
monkeypatch.setattr(notif, "send_telegram", lambda *a, **k: None)
|
||||
|
||||
|
||||
# --- TC-10: reclaim a lease with a DEAD pid, proactively --------------------
|
||||
def test_tc10_reclaim_dead_pid(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
path = _write_lease(repos_dir, "orchestrator", pid=999999, age_s=0)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: False)
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is True
|
||||
assert not os.path.exists(path) # lease removed
|
||||
|
||||
|
||||
# --- TC-11: reclaim by TTL is preserved -------------------------------------
|
||||
def test_tc11_reclaim_by_ttl(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
# pid alive, but the lease is older than the TTL -> still reclaimed.
|
||||
path = _write_lease(repos_dir, "orchestrator", pid=4321, age_s=999)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: True)
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is True
|
||||
assert not os.path.exists(path)
|
||||
|
||||
|
||||
# --- TC-12: a LIVE lease within TTL is NOT released -------------------------
|
||||
def test_tc12_live_lease_protected(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
path = _write_lease(repos_dir, "orchestrator", pid=4321, age_s=10)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: True)
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is False
|
||||
assert os.path.exists(path) # untouched
|
||||
|
||||
|
||||
# --- TC-13: conditional — non-self-hosting repos are a no-op ----------------
|
||||
def test_tc13_non_scope_repo_noop(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
path = _write_lease(repos_dir, "enduro-trails", pid=999999, age_s=999)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: False)
|
||||
assert merge_gate.reclaim_stale_lease("enduro-trails") is False
|
||||
assert os.path.exists(path) # out of scope -> untouched
|
||||
|
||||
|
||||
def test_tc13_merge_gate_repos_csv_scope(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
monkeypatch.setattr(merge_gate.settings, "merge_gate_repos", "enduro-trails")
|
||||
path = _write_lease(repos_dir, "enduro-trails", pid=999999, age_s=0)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: False)
|
||||
assert merge_gate.reclaim_stale_lease("enduro-trails") is True
|
||||
assert not os.path.exists(path)
|
||||
|
||||
|
||||
# --- TC-14: never-raise on a read/remove error ------------------------------
|
||||
def test_tc14_never_raise_on_read_error(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
_write_lease(repos_dir, "orchestrator", pid=1, age_s=999)
|
||||
|
||||
def boom(path):
|
||||
raise OSError("simulated read failure")
|
||||
|
||||
monkeypatch.setattr(merge_gate, "_read_lease", boom)
|
||||
# Must not raise; returns False (could not reclaim).
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is False
|
||||
|
||||
|
||||
def test_tc14_no_lease_file_is_noop(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is False
|
||||
|
||||
|
||||
# --- TC-15: kill-switch lease_reclaim_enabled=False -------------------------
|
||||
def test_tc15_kill_switch(repos_dir, monkeypatch):
|
||||
_no_telegram(monkeypatch)
|
||||
monkeypatch.setattr(merge_gate.settings, "lease_reclaim_enabled", False)
|
||||
path = _write_lease(repos_dir, "orchestrator", pid=999999, age_s=999)
|
||||
monkeypatch.setattr(merge_gate, "pid_alive", lambda pid: False)
|
||||
assert merge_gate.reclaim_stale_lease("orchestrator") is False
|
||||
assert os.path.exists(path) # proactive reclaim off -> untouched
|
||||
|
||||
|
||||
# --- pid_alive semantics ----------------------------------------------------
|
||||
def test_pid_alive_dead_process():
|
||||
# PID 999999999 almost certainly does not exist.
|
||||
assert merge_gate.pid_alive(999999999) is False
|
||||
|
||||
|
||||
def test_pid_alive_self():
|
||||
assert merge_gate.pid_alive(os.getpid()) is True
|
||||
|
||||
|
||||
def test_pid_alive_missing_pid_conservative():
|
||||
assert merge_gate.pid_alive(None) is True
|
||||
assert merge_gate.pid_alive(0) is True
|
||||
@@ -460,3 +460,59 @@ def test_default_states_et_values():
|
||||
assert ps._DEFAULT_STATES[key] == expected, (
|
||||
f"_DEFAULT_STATES['{key}']: expected {expected}, got {ps._DEFAULT_STATES.get(key)}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-19 (AC-18): resolve-by-name — when a project DEFINES one of the
|
||||
# new statuses, get_project_states must use its OWN UUID, not the default alias.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_orch066_tc19_name_resolution_beats_alias():
|
||||
"""A project that created 'Analysis' / 'Code-Review' / 'Awaiting Deploy' /
|
||||
'Deploying' / 'Monitoring after Deploy' resolves each to its own project
|
||||
UUID (via _PLANE_NAME_TO_KEY), NOT the aliased base-key UUID."""
|
||||
import src.plane_sync as ps
|
||||
|
||||
new_uuids = {
|
||||
"Analysis": "11111111-0000-0000-0000-000000000001",
|
||||
"Code-Review": "11111111-0000-0000-0000-000000000002",
|
||||
"Awaiting Deploy": "11111111-0000-0000-0000-000000000003",
|
||||
"Deploying": "11111111-0000-0000-0000-000000000004",
|
||||
"Monitoring after Deploy": "11111111-0000-0000-0000-000000000005",
|
||||
"To Analyse": "11111111-0000-0000-0000-000000000006",
|
||||
}
|
||||
# Start from the full ORCH base set, then add the dedicated new statuses.
|
||||
results = _make_states_response(ORCH_STATES)["results"]
|
||||
results += [{"id": uid, "name": name} for name, uid in new_uuids.items()]
|
||||
|
||||
with patch("src.plane_sync.httpx.get") as mock_get:
|
||||
mock_get.return_value = _fake_response({"results": results})
|
||||
states = ps.get_project_states(ORCH_PROJECT_ID)
|
||||
|
||||
# Each new key resolved to the project's OWN UUID, not the base-key alias.
|
||||
assert states["analysis"] == new_uuids["Analysis"]
|
||||
assert states["code_review"] == new_uuids["Code-Review"]
|
||||
assert states["awaiting_deploy"] == new_uuids["Awaiting Deploy"]
|
||||
assert states["deploying"] == new_uuids["Deploying"]
|
||||
assert states["monitoring"] == new_uuids["Monitoring after Deploy"]
|
||||
assert states["to_analyse"] == new_uuids["To Analyse"]
|
||||
# Sanity: they are NOT the aliased base UUIDs.
|
||||
assert states["analysis"] != states["in_progress"]
|
||||
assert states["code_review"] != states["review"]
|
||||
assert states["awaiting_deploy"] != states["in_review"]
|
||||
|
||||
|
||||
def test_orch066_tc19_missing_new_status_aliases_to_project_base():
|
||||
"""BR-12: a project WITHOUT the new statuses degrades each new key to its OWN
|
||||
base UUID (not a foreign enduro UUID) — keeping the PATCH state valid."""
|
||||
import src.plane_sync as ps
|
||||
with patch("src.plane_sync.httpx.get") as mock_get:
|
||||
mock_get.return_value = _fake_response(_make_states_response(ORCH_STATES))
|
||||
states = ps.get_project_states(ORCH_PROJECT_ID)
|
||||
|
||||
# No dedicated new statuses -> alias to THIS project's base UUIDs.
|
||||
assert states["analysis"] == ORCH_STATES["in_progress"]
|
||||
assert states["to_analyse"] == ORCH_STATES["in_progress"]
|
||||
assert states["code_review"] == ORCH_STATES["review"]
|
||||
assert states["awaiting_deploy"] == ORCH_STATES["in_review"]
|
||||
assert states["deploying"] == ORCH_STATES["in_progress"]
|
||||
assert states["monitoring"] == ORCH_STATES["done"]
|
||||
|
||||
131
tests/test_plane_status_failclosed.py
Normal file
131
tests/test_plane_status_failclosed.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""ORCH-066 fail-closed (CRITICAL) — the new status model must never wedge the
|
||||
pipeline when the 6 Plane statuses are absent or Plane is unreachable.
|
||||
|
||||
* TC-16 (AC-16, BR-12) — a project WITHOUT the new statuses resolves each new
|
||||
logical key to its OWN base UUID (to_analyse=in_progress, code_review=review,
|
||||
awaiting_deploy=in_review, monitoring=done); no exception.
|
||||
* TC-17 (AC-16) — Plane API down -> get_project_states falls back to
|
||||
_DEFAULT_STATES; every set_issue_* helper is never-raise.
|
||||
* TC-18 (AC-17) — enduro In Progress STILL starts the pipeline through
|
||||
the to_analyse alias (= in_progress UUID).
|
||||
|
||||
httpx is mocked; no network.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ.setdefault("ORCH_PLANE_API_URL", "http://plane.local")
|
||||
os.environ.setdefault("ORCH_PLANE_API_TOKEN", "test-token")
|
||||
os.environ.setdefault("ORCH_PLANE_WORKSPACE_SLUG", "test-ws")
|
||||
os.environ.setdefault("ORCH_GITEA_TOKEN", "test-token")
|
||||
|
||||
from unittest.mock import patch, MagicMock, AsyncMock # noqa: E402
|
||||
|
||||
import pytest # noqa: E402
|
||||
|
||||
from src import plane_sync as PS # noqa: E402
|
||||
|
||||
ENDURO_PROJECT_ID = "7a79f0a9-5278-49cd-9007-9a338f238f9c"
|
||||
|
||||
# An enduro-style states response: the 6 ORCH-066 statuses are NOT created.
|
||||
_ENDURO_BASE = {
|
||||
"Backlog": "backlog-u", "Todo": "todo-u", "In Progress": "ip-u",
|
||||
"Review": "review-u", "In Review": "inrev-u", "Approved": "appr-u",
|
||||
"Rejected": "rej-u", "Done": "done-u", "Needs Input": "ni-u",
|
||||
"Blocked": "blk-u",
|
||||
}
|
||||
|
||||
|
||||
def _states_response(name_to_uuid):
|
||||
return {"results": [{"id": uid, "name": name} for name, uid in name_to_uuid.items()]}
|
||||
|
||||
|
||||
def _fake_resp(data, status=200):
|
||||
m = MagicMock()
|
||||
m.status_code = status
|
||||
m.json.return_value = data
|
||||
m.raise_for_status.return_value = None
|
||||
return m
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_cache():
|
||||
PS.reload_project_states()
|
||||
yield
|
||||
PS.reload_project_states()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-16 (AC-16 / BR-12): partial project -> alias to its own base UUIDs, no raise.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc16_partial_project_aliases_to_base_uuids():
|
||||
with patch("src.plane_sync.httpx.get") as mock_get:
|
||||
mock_get.return_value = _fake_resp(_states_response(_ENDURO_BASE))
|
||||
states = PS.get_project_states(ENDURO_PROJECT_ID)
|
||||
|
||||
# The new keys degrade to THIS project's base UUIDs (not foreign defaults).
|
||||
assert states["to_analyse"] == states["in_progress"] == "ip-u"
|
||||
assert states["analysis"] == "ip-u"
|
||||
assert states["code_review"] == states["review"] == "review-u"
|
||||
assert states["awaiting_deploy"] == states["in_review"] == "inrev-u"
|
||||
assert states["deploying"] == "ip-u"
|
||||
assert states["monitoring"] == states["done"] == "done-u"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-17 (AC-16): Plane API down -> _DEFAULT_STATES; set_issue_* never-raise.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc17_api_down_falls_back_to_defaults():
|
||||
with patch("src.plane_sync.httpx.get", side_effect=Exception("plane down")):
|
||||
states = PS.get_project_states(ENDURO_PROJECT_ID)
|
||||
assert states is PS._DEFAULT_STATES
|
||||
# All new keys exist in the defaults (so callers never KeyError).
|
||||
for k in ("to_analyse", "analysis", "code_review", "awaiting_deploy",
|
||||
"deploying", "monitoring"):
|
||||
assert k in states
|
||||
|
||||
|
||||
def test_tc17_set_issue_helpers_never_raise_when_issue_missing():
|
||||
# find_issue_id returns None (issue not in Plane) -> helpers log + return,
|
||||
# they must NOT raise. Covers every ORCH-066 setter.
|
||||
setters = [
|
||||
PS.set_issue_analysis, PS.set_issue_code_review,
|
||||
PS.set_issue_awaiting_deploy, PS.set_issue_deploying,
|
||||
PS.set_issue_monitoring,
|
||||
]
|
||||
with patch("src.plane_sync._resolve_project_id", return_value="proj-1"), \
|
||||
patch("src.plane_sync.get_project_states", return_value=PS._DEFAULT_STATES), \
|
||||
patch("src.plane_sync.find_issue_id", return_value=None), \
|
||||
patch("src.plane_sync.httpx.patch") as mock_patch:
|
||||
for setter in setters:
|
||||
setter("ET-1") # must not raise
|
||||
# No PATCH issued because the issue could not be resolved.
|
||||
mock_patch.assert_not_called()
|
||||
|
||||
|
||||
def test_tc17_set_issue_helpers_never_raise_when_patch_errors():
|
||||
# The PATCH itself blows up -> _set_issue_state_direct swallows it.
|
||||
with patch("src.plane_sync._resolve_project_id", return_value="proj-1"), \
|
||||
patch("src.plane_sync.get_project_states", return_value=PS._DEFAULT_STATES), \
|
||||
patch("src.plane_sync.find_issue_id", return_value="issue-uuid"), \
|
||||
patch("src.plane_sync.httpx.patch", side_effect=Exception("boom")):
|
||||
PS.set_issue_monitoring("ET-1") # must not raise
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-18 (AC-17): enduro In Progress still starts the pipeline via to_analyse alias.
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_tc18_enduro_in_progress_still_starts_via_alias():
|
||||
from src.webhooks.plane import handle_issue_updated
|
||||
|
||||
with patch("src.plane_sync.httpx.get") as mock_get, \
|
||||
patch("src.webhooks.plane.handle_status_start", new_callable=AsyncMock) as mock_start, \
|
||||
patch("src.webhooks.plane.handle_verdict", new_callable=AsyncMock) as mock_verdict:
|
||||
mock_get.return_value = _fake_resp(_states_response(_ENDURO_BASE))
|
||||
# enduro never created 'To Analyse' -> to_analyse aliases In Progress (ip-u).
|
||||
data = {"id": "et-issue", "state": {"id": "ip-u", "name": "In Progress"}}
|
||||
await handle_issue_updated(data, ENDURO_PROJECT_ID)
|
||||
|
||||
mock_start.assert_called_once()
|
||||
mock_verdict.assert_not_called()
|
||||
151
tests/test_plane_status_model.py
Normal file
151
tests/test_plane_status_model.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""ORCH-066: the meaningful Plane status model (layer B) — unit coverage.
|
||||
|
||||
These tests pin the layer-B behaviour WITHOUT touching layer A (the stage
|
||||
machine). httpx is mocked; no network.
|
||||
|
||||
* TC-03 (AC-3) — the analyst start/resume indicates `Analysis`, not In Progress.
|
||||
* TC-05 (AC-5) — entering the `review` stage indicates `Code-Review`.
|
||||
* TC-14 (AC-14) — set_issue_needs_input is unchanged (still PATCHes Needs Input).
|
||||
* TC-22 (AC-21) — STAGE_TRANSITIONS (layer A) is byte-identical (explicit pin).
|
||||
* TC-23 (AC-22) — QG_CHECKS registry + check_deploy_status contract unchanged.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
os.environ.setdefault("ORCH_PLANE_API_TOKEN", "test-token")
|
||||
os.environ.setdefault("ORCH_GITEA_TOKEN", "test-token")
|
||||
|
||||
from unittest.mock import patch, MagicMock # noqa: E402
|
||||
|
||||
from src import plane_sync as PS # noqa: E402
|
||||
|
||||
|
||||
# A per-project state map that DEFINES the new ORCH-066 statuses with distinct
|
||||
# UUIDs, so we can prove the dedicated status (not the base alias) is used.
|
||||
_STATES_WITH_NEW = {
|
||||
"in_progress": "ip-uuid",
|
||||
"review": "review-uuid",
|
||||
"in_review": "inrev-uuid",
|
||||
"needs_input": "ni-uuid",
|
||||
"done": "done-uuid",
|
||||
"analysis": "analysis-uuid",
|
||||
"code_review": "codereview-uuid",
|
||||
"awaiting_deploy": "awaiting-uuid",
|
||||
"deploying": "deploying-uuid",
|
||||
"monitoring": "monitoring-uuid",
|
||||
}
|
||||
|
||||
|
||||
def _patch_resolve(states):
|
||||
"""Patch find_issue_id + _resolve_project_id + get_project_states so a
|
||||
set_issue_* helper reaches the PATCH with a known per-project state map."""
|
||||
return (
|
||||
patch("src.plane_sync.httpx.patch"),
|
||||
patch("src.plane_sync.find_issue_id", return_value="issue-uuid"),
|
||||
patch("src.plane_sync._resolve_project_id", return_value="proj-1"),
|
||||
patch("src.plane_sync.get_project_states", return_value=states),
|
||||
)
|
||||
|
||||
|
||||
def _run_setter(setter, states):
|
||||
p_patch, p_find, p_res, p_states = _patch_resolve(states)
|
||||
with p_patch as mock_patch, p_find, p_res, p_states:
|
||||
resp = MagicMock()
|
||||
resp.raise_for_status.return_value = None
|
||||
mock_patch.return_value = resp
|
||||
setter("ET-1")
|
||||
return mock_patch
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-03 (AC-3): analyst start/resume indicates Analysis.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc03_set_issue_analysis_patches_analysis_uuid():
|
||||
mock_patch = _run_setter(PS.set_issue_analysis, _STATES_WITH_NEW)
|
||||
# The dedicated Analysis UUID is used (NOT the in_progress base alias).
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == "analysis-uuid"
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] != _STATES_WITH_NEW["in_progress"]
|
||||
|
||||
|
||||
def test_tc03_analysis_aliases_in_progress_when_absent():
|
||||
# A project without the Analysis status -> get_project_states already aliased
|
||||
# 'analysis' onto its in_progress UUID, so the PATCH degrades gracefully.
|
||||
aliased = dict(_STATES_WITH_NEW)
|
||||
aliased["analysis"] = aliased["in_progress"]
|
||||
mock_patch = _run_setter(PS.set_issue_analysis, aliased)
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == aliased["in_progress"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-05 (AC-5): the review stage indicates Code-Review.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc05_review_stage_maps_to_code_review():
|
||||
# Both the stage->state-key map and the stage-visibility map point review at
|
||||
# the new code_review logical key (layer B only).
|
||||
assert PS._STAGE_TO_STATE_KEY["review"] == "code_review"
|
||||
assert PS.STAGE_VISIBILITY_STATE["review"] == "code_review"
|
||||
|
||||
|
||||
def test_tc05_set_issue_stage_state_review_patches_code_review_uuid():
|
||||
p_patch, p_find, p_res, p_states = _patch_resolve(_STATES_WITH_NEW)
|
||||
with p_patch as mock_patch, p_find, p_res, p_states:
|
||||
resp = MagicMock()
|
||||
resp.raise_for_status.return_value = None
|
||||
mock_patch.return_value = resp
|
||||
PS.set_issue_stage_state("ET-1", "review")
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == "codereview-uuid"
|
||||
|
||||
|
||||
def test_tc05_set_issue_code_review_helper_patches_code_review_uuid():
|
||||
mock_patch = _run_setter(PS.set_issue_code_review, _STATES_WITH_NEW)
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == "codereview-uuid"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-14 (AC-14): Needs Input behaviour unchanged.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc14_needs_input_unchanged():
|
||||
mock_patch = _run_setter(PS.set_issue_needs_input, _STATES_WITH_NEW)
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == "ni-uuid"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-22 (AC-21): STAGE_TRANSITIONS (layer A) is byte-identical. ORCH-066 changes
|
||||
# ONLY layer B — the machine must not move.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc22_stage_transitions_unchanged():
|
||||
from src.stages import STAGE_TRANSITIONS
|
||||
assert STAGE_TRANSITIONS == {
|
||||
"created": {"next": "analysis", "agent": "analyst", "qg": None},
|
||||
"analysis": {"next": "architecture", "agent": "architect", "qg": "check_analysis_approved"},
|
||||
"architecture": {"next": "development", "agent": "developer", "qg": "check_architecture_done"},
|
||||
"development": {"next": "review", "agent": "reviewer", "qg": "check_ci_green"},
|
||||
"review": {"next": "testing", "agent": "tester", "qg": "check_reviewer_verdict"},
|
||||
"testing": {"next": "deploy-staging", "agent": "deployer", "qg": "check_tests_passed"},
|
||||
"deploy-staging": {"next": "deploy", "agent": "deployer", "qg": "check_staging_status"},
|
||||
"deploy": {"next": "done", "agent": None, "qg": "check_deploy_status"},
|
||||
"done": {"next": None, "agent": None, "qg": None},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-23 (AC-22): QG_CHECKS registry + check_deploy_status contract unchanged.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc23_qg_checks_registry_unchanged():
|
||||
from src.qg.checks import QG_CHECKS
|
||||
assert set(QG_CHECKS.keys()) == {
|
||||
"check_analysis_approved", "check_analysis_complete", "check_architecture_done",
|
||||
"check_ci_green", "check_review_approved", "check_tests_passed",
|
||||
"check_reviewer_verdict", "check_tests_local", "check_deploy_status",
|
||||
"check_staging_status", "check_branch_mergeable", "check_staging_image_fresh",
|
||||
}
|
||||
|
||||
|
||||
def test_tc23_check_deploy_status_signature_unchanged():
|
||||
import inspect
|
||||
from src.qg.checks import check_deploy_status, QG_CHECKS
|
||||
# Registry still points at the same callable.
|
||||
assert QG_CHECKS["check_deploy_status"] is check_deploy_status
|
||||
# (repo, work_item_id, branch=None) -> tuple[bool, str] contract intact.
|
||||
params = list(inspect.signature(check_deploy_status).parameters)
|
||||
assert params == ["repo", "work_item_id", "branch"]
|
||||
114
tests/test_plane_to_analyse_resume.py
Normal file
114
tests/test_plane_to_analyse_resume.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""ORCH-066: To Analyse resume semantics (F-1 status-only model).
|
||||
|
||||
`handle_status_start` forks on (existing task?) + (active job?):
|
||||
|
||||
* TC-02 (AC-2, BR-11) — an EXISTING task with NO active job + To Analyse ->
|
||||
RELAUNCH the current stage's agent (the analyst resumes from Needs Input);
|
||||
NO second task is created; the issue is re-indicated `Analysis`.
|
||||
* TC-04 (AC-4) — an EXISTING task WITH an active job + To Analyse ->
|
||||
busy-guard: NO relaunch (no double launch).
|
||||
|
||||
handle_status_start is exercised directly; enqueue_job + Plane side-effects are
|
||||
mocked. A real isolated sqlite DB backs get_task_by_plane_id / the job guard.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
_test_db = os.path.join(tempfile.gettempdir(), "test_orch066_to_analyse_resume.db")
|
||||
os.environ["ORCH_DB_PATH"] = _test_db
|
||||
os.environ["ORCH_REPOS_DIR"] = tempfile.gettempdir()
|
||||
os.environ.setdefault("ORCH_GITEA_TOKEN", "test-token")
|
||||
os.environ.setdefault("ORCH_PLANE_API_TOKEN", "test-token")
|
||||
|
||||
from unittest.mock import patch, AsyncMock, MagicMock # noqa: E402
|
||||
|
||||
import src.db as _db # noqa: E402
|
||||
from src.db import init_db, get_db # noqa: E402
|
||||
from src.webhooks.plane import handle_status_start # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_db(monkeypatch):
|
||||
monkeypatch.setattr(_db.settings, "db_path", _test_db)
|
||||
if os.path.exists(_test_db):
|
||||
os.unlink(_test_db)
|
||||
init_db()
|
||||
yield
|
||||
if os.path.exists(_test_db):
|
||||
os.unlink(_test_db)
|
||||
|
||||
|
||||
def _make_task(plane_id="resume-1", stage="analysis", repo="enduro-trails",
|
||||
branch="feature/ET-001-x", wi="ET-001"):
|
||||
conn = get_db()
|
||||
cur = conn.execute(
|
||||
"INSERT INTO tasks (plane_id, work_item_id, repo, branch, stage) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
(plane_id, wi, repo, branch, stage),
|
||||
)
|
||||
tid = cur.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return tid
|
||||
|
||||
|
||||
def _count(plane_id):
|
||||
conn = get_db()
|
||||
n = conn.execute("SELECT COUNT(*) FROM tasks WHERE plane_id=?", (plane_id,)).fetchone()[0]
|
||||
conn.close()
|
||||
return n
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-02 (AC-2 / BR-11): existing task, no active job -> RELAUNCH (resume), no dup.
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_tc02_to_analyse_resume_relaunches_analyst_no_duplicate():
|
||||
_make_task("resume-1", stage="analysis")
|
||||
data = {"id": "resume-1", "state": {"id": "ip-uuid", "name": "To Analyse"}}
|
||||
|
||||
with patch("src.webhooks.plane.enqueue_job", return_value=7) as mock_enqueue, \
|
||||
patch("src.webhooks.plane.start_pipeline", new_callable=AsyncMock) as mock_start, \
|
||||
patch("src.plane_sync.add_comment", MagicMock()), \
|
||||
patch("src.plane_sync.set_issue_analysis") as mock_analysis:
|
||||
await handle_status_start(data, "proj-1")
|
||||
|
||||
# No new pipeline start (it is a resume, not a fresh task).
|
||||
mock_start.assert_not_called()
|
||||
assert _count("resume-1") == 1 # NO duplicate task
|
||||
# The current stage's agent (analyst) was relaunched exactly once.
|
||||
assert mock_enqueue.call_count == 1
|
||||
assert mock_enqueue.call_args.args[0] == "analyst"
|
||||
# AC-3: the resumed analysis stage is re-indicated as Analysis.
|
||||
mock_analysis.assert_called_once_with("ET-001")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-04 (AC-4): existing task WITH active job -> busy-guard, NO relaunch.
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_tc04_to_analyse_with_active_job_does_not_relaunch():
|
||||
tid = _make_task("resume-2", stage="analysis")
|
||||
# Seed an active (queued) job so has_active_job_for_task reports busy.
|
||||
conn = get_db()
|
||||
conn.execute(
|
||||
"INSERT INTO jobs (agent, repo, task_id, status) VALUES (?, ?, ?, 'queued')",
|
||||
("analyst", "enduro-trails", tid),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
data = {"id": "resume-2", "state": {"id": "ip-uuid", "name": "To Analyse"}}
|
||||
with patch("src.webhooks.plane.enqueue_job", return_value=9) as mock_enqueue, \
|
||||
patch("src.webhooks.plane.start_pipeline", new_callable=AsyncMock) as mock_start, \
|
||||
patch("src.plane_sync.add_comment", MagicMock()), \
|
||||
patch("src.plane_sync.set_issue_analysis") as mock_analysis:
|
||||
await handle_status_start(data, "proj-1")
|
||||
|
||||
mock_start.assert_not_called()
|
||||
mock_enqueue.assert_not_called() # busy-guard held: NO double launch
|
||||
mock_analysis.assert_not_called()
|
||||
assert _count("resume-2") == 1
|
||||
@@ -47,13 +47,18 @@ UNKNOWN_PLANE_ID = "deadbeef-0000-0000-0000-000000000000"
|
||||
_PROJECT_STATES = {
|
||||
ENDURO_PLANE_ID: {
|
||||
"in_progress": "b873d9eb-993c-48cd-97ac-99a9b1623967",
|
||||
# ORCH-066: To Analyse is the start trigger; absent -> aliases in_progress.
|
||||
"to_analyse": "b873d9eb-993c-48cd-97ac-99a9b1623967",
|
||||
"approved": "a519a341-dada-4a91-8910-7604f82b79c5",
|
||||
"rejected": "ba958f3c-5db5-461d-8f82-89425e413b97",
|
||||
"cancelled": "b1cae7f9-961d-4889-a179-f3acea697d17",
|
||||
},
|
||||
ORCH_PLANE_ID: {
|
||||
"in_progress": "e331bfb3-e17e-4699-ba48-4abb89c21b7b",
|
||||
"to_analyse": "e331bfb3-e17e-4699-ba48-4abb89c21b7b",
|
||||
"approved": "63f2c8fe-dcda-4ace-952f-dd88bd0118ff",
|
||||
"rejected": "4c769e90-bf80-4a52-b97a-e1c84904bfc3",
|
||||
"cancelled": "59d1d210-8e3a-4a83-930a-cbc5dbf6ad85",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -219,3 +224,38 @@ def test_prefixes_independent_per_project(mock_branch, mock_docs, mock_launcher)
|
||||
assert rows["o1"] == "ORCH-001"
|
||||
assert rows["o2"] == "ORCH-002"
|
||||
assert rows["e1"] == "ET-001"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-15 (AC-15): Cancelled is a valid human exit — the orchestrator
|
||||
# performs NO advance/rollback (indication, not control).
|
||||
# ---------------------------------------------------------------------------
|
||||
@patch("src.webhooks.plane.handle_verdict", new_callable=AsyncMock)
|
||||
@patch("src.webhooks.plane.handle_status_start", new_callable=AsyncMock)
|
||||
@patch("src.webhooks.plane.launcher")
|
||||
def test_cancelled_state_does_no_pipeline_action(mock_launcher, mock_start, mock_verdict):
|
||||
cancelled = _PROJECT_STATES[ORCH_PLANE_ID]["cancelled"]
|
||||
resp = client.post(
|
||||
"/webhook/plane",
|
||||
json={
|
||||
"event": "issue",
|
||||
"action": "updated",
|
||||
"data": {
|
||||
"id": "cancel-1",
|
||||
"name": "A cancelled work item",
|
||||
"description_stripped": "This is a sufficiently long description.",
|
||||
"project": ORCH_PLANE_ID,
|
||||
"state": {"id": cancelled, "name": "Cancelled", "group": "cancelled"},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
# Neither the start nor the verdict (advance/rollback) handler ran.
|
||||
mock_start.assert_not_called()
|
||||
mock_verdict.assert_not_called()
|
||||
mock_launcher.launch.assert_not_called()
|
||||
# No task created off a Cancelled transition.
|
||||
conn = get_db()
|
||||
task = conn.execute("SELECT * FROM tasks WHERE plane_id='cancel-1'").fetchone()
|
||||
conn.close()
|
||||
assert task is None
|
||||
|
||||
@@ -47,6 +47,9 @@ def silence_side_effects(monkeypatch):
|
||||
"send_telegram", "plane_notify_stage", "plane_notify_qg", "plane_add_comment",
|
||||
"set_issue_in_review", "set_issue_needs_input", "set_issue_in_progress",
|
||||
"set_issue_blocked", "set_issue_done",
|
||||
# ORCH-066 status setters.
|
||||
"set_issue_analysis", "set_issue_awaiting_deploy", "set_issue_deploying",
|
||||
"set_issue_monitoring",
|
||||
):
|
||||
monkeypatch.setattr(stage_engine, name, MagicMock())
|
||||
|
||||
@@ -242,6 +245,81 @@ def test_finished_window_tick_is_noop(monkeypatch):
|
||||
probe.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-10 (AC-10): HEALTHY + window exhausted -> Plane state Done.
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_orch066_tc10_clean_window_close_sets_done(monkeypatch):
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_monitor_enabled", True)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_window_s", 30)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_interval_s", 30) # budget=1
|
||||
monkeypatch.setattr(
|
||||
post_deploy, "probe_signals",
|
||||
lambda url: post_deploy.ProbeResult(True, 2, 0, "ok"),
|
||||
)
|
||||
task_id = _make_task("done")
|
||||
post_deploy.write_marker("orchestrator", "ORCH-021", post_deploy.ARMED, "armed")
|
||||
stage_engine.run_post_deploy_monitor(
|
||||
{"task_id": task_id, "repo": "orchestrator", "id": 1, "agent": "post-deploy-monitor"}
|
||||
)
|
||||
# Clean window close -> terminal Done indicated on Plane; window marked done.
|
||||
stage_engine.set_issue_done.assert_called_once_with("ORCH-021")
|
||||
stage_engine.set_issue_blocked.assert_not_called()
|
||||
assert post_deploy.has_marker("orchestrator", "ORCH-021", post_deploy.DONE)
|
||||
# No follow-up tick once the window closed.
|
||||
assert _jobs("post-deploy-monitor") == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-11 (AC-11): DEGRADED -> Plane state Blocked (self-hosting alert).
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_orch066_tc11_degraded_sets_blocked(monkeypatch):
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_monitor_enabled", True)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_fail_threshold", 1)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_window_s", 30)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_interval_s", 30)
|
||||
monkeypatch.setattr(
|
||||
post_deploy, "probe_signals",
|
||||
lambda url: post_deploy.ProbeResult(False, 2, 2, "down"),
|
||||
)
|
||||
monkeypatch.setattr(stage_engine, "_notify_post_deploy", MagicMock())
|
||||
task_id = _make_task("done")
|
||||
post_deploy.write_marker("orchestrator", "ORCH-021", post_deploy.ARMED, "armed")
|
||||
stage_engine.run_post_deploy_monitor(
|
||||
{"task_id": task_id, "repo": "orchestrator", "id": 1, "agent": "post-deploy-monitor"}
|
||||
)
|
||||
# DEGRADED -> Blocked indication (NOT Done); window finalised.
|
||||
stage_engine.set_issue_blocked.assert_called_once_with("ORCH-021")
|
||||
stage_engine.set_issue_done.assert_not_called()
|
||||
assert post_deploy.has_marker("orchestrator", "ORCH-021", post_deploy.DONE)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-12 (AC-12): a self-hosting tick NEVER restarts/rolls back prod —
|
||||
# the Blocked indication is the ONLY mutation (ORCH-021 BR-5 preserved).
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_orch066_tc12_self_tick_never_restarts_prod(monkeypatch):
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_monitor_enabled", True)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_auto_rollback", True)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_fail_threshold", 1)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_window_s", 30)
|
||||
monkeypatch.setattr(post_deploy.settings, "post_deploy_interval_s", 30)
|
||||
monkeypatch.setattr(
|
||||
post_deploy, "probe_signals",
|
||||
lambda url: post_deploy.ProbeResult(False, 2, 2, "down"),
|
||||
)
|
||||
monkeypatch.setattr(stage_engine, "_notify_post_deploy", MagicMock())
|
||||
# The rollback hook (the only restart-capable path) MUST stay untouched for self.
|
||||
rollback = MagicMock(return_value=(0, "ok"))
|
||||
monkeypatch.setattr(post_deploy, "run_rollback", rollback)
|
||||
task_id = _make_task("done")
|
||||
post_deploy.write_marker("orchestrator", "ORCH-021", post_deploy.ARMED, "armed")
|
||||
stage_engine.run_post_deploy_monitor(
|
||||
{"task_id": task_id, "repo": "orchestrator", "id": 1, "agent": "post-deploy-monitor"}
|
||||
)
|
||||
rollback.assert_not_called() # never restarts/rolls back the prod self-container
|
||||
stage_engine.set_issue_blocked.assert_called_once_with("ORCH-021") # indication only
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-20 — /queue observability block
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -302,3 +302,58 @@ class TestWorkerConcurrency:
|
||||
assert count_running_jobs() == 0
|
||||
counts = job_status_counts()
|
||||
assert counts["failed"] == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-065: job-reaper unblocks the shared queue (TC-09) + /queue block (TC-18)
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestReaperUnblocksQueue:
|
||||
def test_tc09_reap_unblocks_claim_at_concurrency_1(self, monkeypatch):
|
||||
"""A zombie 'running' row at max_concurrency=1 blocks every claim; once the
|
||||
reaper reaps it the next queued job can be claimed (AC-2)."""
|
||||
import src.merge_gate as mg
|
||||
from src.job_reaper import JobReaper
|
||||
|
||||
monkeypatch.setattr(db.settings, "reaper_dead_ticks", 1)
|
||||
monkeypatch.setattr(mg, "pid_alive", lambda pid: False) # zombie pid dead
|
||||
|
||||
# A zombie row stuck 'running' with a dead pid.
|
||||
conn = db.get_db()
|
||||
cur = conn.execute(
|
||||
"INSERT INTO jobs (agent, repo, status, attempts, max_attempts, pid, "
|
||||
"started_at) VALUES ('developer','r','running',2,2,999999,datetime('now'))"
|
||||
)
|
||||
zombie = cur.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# A second job waits in the queue behind it.
|
||||
nxt = enqueue_job("analyst", "r")
|
||||
|
||||
# At concurrency 1 the slot is fully occupied -> nothing else can run.
|
||||
assert count_running_jobs() == 1
|
||||
|
||||
monkeypatch.setattr("src.notifications.send_telegram", lambda *a, **k: None)
|
||||
JobReaper().reap_once() # dead pid, attempts>=max -> failed
|
||||
|
||||
assert get_job(zombie)["status"] == "failed"
|
||||
assert count_running_jobs() == 0
|
||||
# Queue is unblocked: the next job claims successfully.
|
||||
claimed = claim_next_job()
|
||||
assert claimed is not None and claimed["id"] == nxt
|
||||
|
||||
def test_tc18_queue_endpoint_has_reaper_block(self):
|
||||
"""GET /queue exposes the reaper observability block (AC-15).
|
||||
|
||||
Calls the endpoint coroutine directly (no lifespan / no background
|
||||
threads / no network) so the test stays hermetic.
|
||||
"""
|
||||
import asyncio
|
||||
import src.main as main
|
||||
|
||||
body = asyncio.run(main.queue())
|
||||
assert "reaper" in body
|
||||
reaper = body["reaper"]
|
||||
for key in ("enabled", "interval", "last_run_ts", "reaped_total",
|
||||
"last_reaped", "lease_reclaimed_total"):
|
||||
assert key in reaper
|
||||
|
||||
@@ -572,7 +572,7 @@ def test_tc060_08_no_gate_call_on_escalated(monkeypatch):
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc060_09_f2_does_not_replay_blocked(monkeypatch):
|
||||
states = {
|
||||
"in_progress": "IP", "approved": "AP", "rejected": "RJ",
|
||||
"in_progress": "IP", "to_analyse": "IP", "approved": "AP", "rejected": "RJ",
|
||||
"blocked": "BL", "needs_input": "NI",
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
@@ -680,3 +680,67 @@ def test_tc060_subflag_disables_only_guard2(monkeypatch):
|
||||
|
||||
assert _stage_of(blocked) == "review" # Guard 2 muted
|
||||
assert _stage_of(escalated) == "development" # Guard 1 still skips
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-21 (AC-20 / BR-13): Guard 2 skips the active orchestrator waits
|
||||
# (Awaiting Deploy / Deploying / Monitoring after Deploy) ONLY when they are
|
||||
# DISTINCT statuses — an aliased (enduro) project must NOT widen the skip-set.
|
||||
# ---------------------------------------------------------------------------
|
||||
def _guard2(monkeypatch, states, cur_state):
|
||||
"""Drive _is_blocked_or_needs_input with a chosen project state map + the
|
||||
issue's current Plane state uuid."""
|
||||
monkeypatch.setattr(reconciler_mod, "get_project_states",
|
||||
MagicMock(return_value=states))
|
||||
monkeypatch.setattr(reconciler_mod, "fetch_issue_state",
|
||||
MagicMock(return_value=cur_state))
|
||||
monkeypatch.setattr(
|
||||
reconciler_mod.projects, "get_project_by_repo",
|
||||
MagicMock(return_value=MagicMock(plane_project_id="proj-test")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
reconciler_mod.settings, "reconcile_skip_blocked_enabled", True
|
||||
)
|
||||
task = {"id": 1, "repo": "orchestrator", "plane_id": "iss-1"}
|
||||
return Reconciler()._is_blocked_or_needs_input(task)
|
||||
|
||||
|
||||
# orchestrator has the three new statuses as DISTINCT UUIDs.
|
||||
_DISTINCT_STATES = {
|
||||
"backlog": "bl-u", "todo": "td-u", "in_progress": "ip-u", "in_review": "inrev-u",
|
||||
"review": "rev-u", "architecture": "arch-u", "development": "dev-u",
|
||||
"testing": "test-u", "approved": "appr-u", "rejected": "rej-u", "done": "done-u",
|
||||
"blocked": "blocked-u", "needs_input": "ni-u",
|
||||
"awaiting_deploy": "await-u", "deploying": "deploying-u", "monitoring": "monitor-u",
|
||||
}
|
||||
|
||||
|
||||
def test_tc21_guard2_skips_distinct_active_waits(monkeypatch):
|
||||
# Each active-wait status (distinct UUID) -> skipped (not revived).
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "await-u") is True
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "deploying-u") is True
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "monitor-u") is True
|
||||
# Explicit human gates still skip.
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "blocked-u") is True
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "ni-u") is True
|
||||
# A normal working state is NOT skipped (gets reconciled).
|
||||
assert _guard2(monkeypatch, _DISTINCT_STATES, "ip-u") is False
|
||||
|
||||
|
||||
def test_tc21_guard2_aliased_waits_do_not_widen_skipset(monkeypatch):
|
||||
# enduro: the new keys alias onto base working statuses -> they must NOT make
|
||||
# F-1 skip a genuinely In Progress / In Review / Done task (anti-regress).
|
||||
aliased = {
|
||||
"backlog": "bl-u", "todo": "td-u", "in_progress": "ip-u", "in_review": "inrev-u",
|
||||
"review": "rev-u", "architecture": "arch-u", "development": "dev-u",
|
||||
"testing": "test-u", "approved": "appr-u", "rejected": "rej-u", "done": "done-u",
|
||||
"blocked": "blocked-u", "needs_input": "ni-u",
|
||||
# aliased onto base UUIDs (project did not create dedicated statuses).
|
||||
"awaiting_deploy": "inrev-u", "deploying": "ip-u", "monitoring": "done-u",
|
||||
}
|
||||
# In Progress / In Review / Done are base working states -> NOT skipped.
|
||||
assert _guard2(monkeypatch, aliased, "ip-u") is False
|
||||
assert _guard2(monkeypatch, aliased, "inrev-u") is False
|
||||
assert _guard2(monkeypatch, aliased, "done-u") is False
|
||||
# The explicit human gates still skip.
|
||||
assert _guard2(monkeypatch, aliased, "blocked-u") is True
|
||||
|
||||
@@ -59,6 +59,9 @@ def single_project(monkeypatch):
|
||||
reconciler_mod, "get_project_states",
|
||||
lambda pid: {
|
||||
"in_progress": _IN_PROGRESS,
|
||||
# ORCH-066: To Analyse is the F-2 start/resume trigger; absent in this
|
||||
# project -> aliases in_progress (real get_project_states fallback).
|
||||
"to_analyse": _IN_PROGRESS,
|
||||
"approved": _APPROVED,
|
||||
"rejected": _REJECTED,
|
||||
},
|
||||
@@ -114,6 +117,46 @@ def test_tc11_in_progress_without_task_starts_pipeline(monkeypatch, single_proje
|
||||
verdict.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ORCH-066 TC-20 (AC-19): F-2 polls the DISTINCT To Analyse status and routes it
|
||||
# to handle_status_start (a lost start/resume webhook is recovered).
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_tc20_distinct_to_analyse_polled_and_routed(monkeypatch):
|
||||
_TO_ANALYSE = "uuid-to-analyse" # distinct from in_progress
|
||||
monkeypatch.setattr(
|
||||
reconciler_mod, "get_project_states",
|
||||
lambda pid: {
|
||||
"in_progress": _IN_PROGRESS,
|
||||
"to_analyse": _TO_ANALYSE, # dedicated status created
|
||||
"approved": _APPROVED,
|
||||
"rejected": _REJECTED,
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
reconciler_mod.projects, "PROJECTS",
|
||||
[SimpleNamespace(plane_project_id="proj-1", repo="enduro-trails",
|
||||
work_item_prefix="ET")],
|
||||
)
|
||||
start, verdict = _patch_handlers(monkeypatch)
|
||||
|
||||
polled = {}
|
||||
|
||||
def fake_list(pid, states):
|
||||
polled["states"] = list(states)
|
||||
return [{"id": "iss-ta", "state": {"id": _TO_ANALYSE}, "updated_at": _OLD_TS,
|
||||
"name": "Lost start"}]
|
||||
|
||||
monkeypatch.setattr(reconciler_mod, "list_issues_by_state", fake_list)
|
||||
|
||||
Reconciler().reconcile_plane_once()
|
||||
|
||||
# The To Analyse UUID is in the polled set and routed to start (not verdict).
|
||||
assert _TO_ANALYSE in polled["states"]
|
||||
assert start.call_count == 1
|
||||
assert start.call_args.args[0]["id"] == "iss-ta"
|
||||
verdict.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TC-12: Approved with an existing task, no active job -> handle_verdict(True).
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -279,7 +322,10 @@ def test_tc17_polls_all_projects_resolves_states_per_project(monkeypatch):
|
||||
|
||||
def fake_states(pid):
|
||||
states_calls.append(pid)
|
||||
return {"in_progress": _IN_PROGRESS, "approved": _APPROVED, "rejected": _REJECTED}
|
||||
return {
|
||||
"in_progress": _IN_PROGRESS, "to_analyse": _IN_PROGRESS,
|
||||
"approved": _APPROVED, "rejected": _REJECTED,
|
||||
}
|
||||
|
||||
def fake_issues(pid, states):
|
||||
issues_calls.append((pid, tuple(states)))
|
||||
|
||||
@@ -68,10 +68,18 @@ def test_set_issue_stage_state_patches_correct_uuid(mock_proj, mock_find, mock_p
|
||||
@patch("src.plane_sync.httpx.patch")
|
||||
@patch("src.plane_sync.find_issue_id", return_value="issue-uuid")
|
||||
@patch("src.plane_sync._resolve_project_id", return_value="proj-1")
|
||||
def test_set_issue_stage_state_noop_for_analysis(mock_proj, mock_find, mock_patch):
|
||||
# analysis has no dedicated board status -> no PATCH at all.
|
||||
def test_set_issue_stage_state_noop_for_deploy(mock_proj, mock_find, mock_patch):
|
||||
# ORCH-066: analysis now HAS a dedicated status (Analysis) -> it PATCHes.
|
||||
# deploy still has no board status here (driven by Phase A/B/C) -> no-op.
|
||||
resp = MagicMock()
|
||||
resp.raise_for_status.return_value = None
|
||||
mock_patch.return_value = resp
|
||||
|
||||
PS.set_issue_stage_state("ET-1", "analysis")
|
||||
mock_patch.assert_not_called()
|
||||
# analysis aliases in_progress when the Analysis status is absent.
|
||||
assert mock_patch.call_args.kwargs["json"]["state"] == PS.PLANE_STATES["analysis"]
|
||||
|
||||
mock_patch.reset_mock()
|
||||
PS.set_issue_stage_state("ET-1", "deploy")
|
||||
mock_patch.assert_not_called()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user