diff --git a/promptpilot/db.py b/promptpilot/db.py index f4c79ce..7001244 100644 --- a/promptpilot/db.py +++ b/promptpilot/db.py @@ -2783,7 +2783,7 @@ def repair_active_series_occurrences( ).fetchone() is not None: continue latest = conn.execute( - """SELECT id, status, completed_at FROM tasks WHERE series_id = ? + """SELECT * FROM tasks WHERE series_id = ? ORDER BY id DESC LIMIT 1""", (series_id,), ).fetchone() @@ -2804,6 +2804,11 @@ def repair_active_series_occurrences( recurrence = _effective_series_recurrence(dict(series), anchor) scheduled_at = (datetime.now(timezone.utc) if has_wake else parse_recurrence(recurrence, now=anchor)) + if scheduled_at and not has_wake and latest["verdict"] == "ПУСТО": + from .merge_ci_wait import defer_time + hint = defer_time(_row_to_task(latest), conn=conn) + if hint is not None: + scheduled_at = min(scheduled_at, hint) if (scheduled_at is not None and _recreate_series_occurrence( conn, series_id, series, scheduled_at)): # The immediate repaired occurrence itself satisfies a wake @@ -4272,7 +4277,7 @@ def _pipeline_source_refresh_state(conn, scope, task_id, profile_id, queue_id, r if (started.tzinfo is None or started.timestamp() > now or timeout and now >= started.timestamp() + timeout): raise ValueError("source refresh attempt lifetime is invalid") - if bounded_route not in (None, "merge_confirmation", "merge_full_confirmation", "merge_receipt"): + if bounded_route not in (None, "merge_confirmation", "merge_full_confirmation", "merge_receipt", "merge_ci_poll"): raise ValueError("unsupported Native-only continuation route") routes = (bounded_route,) if bounded_route else ("skill", "fallback_targeted") costs = {route: _pipeline_budget_vector(route_costs[route], f"continuation {route} cost") @@ -4326,7 +4331,7 @@ def _pipeline_source_refresh_guard_matches(conn, guard): try: observed = _pipeline_source_refresh_state(conn, guard["scope"], guard["task_id"], guard["profile_id"], guard["queue_id"], guard["route_costs"], - bounded_route=(guard["route"] if guard["route"] in ("merge_confirmation", "merge_full_confirmation", "merge_receipt") else None)) + bounded_route=(guard["route"] if guard["route"] in ("merge_confirmation", "merge_full_confirmation", "merge_receipt", "merge_ci_poll") else None)) return observed["guard"] == guard except (KeyError, TypeError, ValueError, OverflowError): return False diff --git a/promptpilot/merge_ci_dispatch.py b/promptpilot/merge_ci_dispatch.py new file mode 100644 index 0000000..4fc3d91 --- /dev/null +++ b/promptpilot/merge_ci_dispatch.py @@ -0,0 +1,166 @@ +"""Resume an ordinary MERGE's external Actions wait without starting a provider.""" + +import json +import sqlite3 +import time +from pathlib import Path + +from . import db, merge_ci_wait as ci, pipeline_insights as pi, project_pipeline as pp +from .task_identity import task_execution_fingerprint + + +POLL_COST = {"core": 2, "search": 0, "graphql": 0} + + +def enabled(queue, profile): + execution = queue.get("execution") or {} + return (isinstance(execution, dict) and queue.get("id") == "merge" and queue.get("item_blockers") is True + and str(execution.get("stage") or "merge").lower() == "merge" + and str(execution.get("mode", "auto")).lower() == "auto" + and execution.get("merge_confirmation") == "bounded-v1" + and profile.get("github_budget", {}).get("source_cost_protocol") == "source-graphql-cost-v1") + + +def source_wait(task, profile, data): + """A fresh executable queue may save the election only for a passive poll.""" + items = (data.get("diagnostics") or {}).get("merge_executable") or [] + if (not items or not isinstance(items[0], dict) + or pi._required_snapshot_state(data, profile, "merge") is not None + or data.get("repository") != profile["repository"] or items[0].get("stage") not in ci.ORDINARY_STAGES): + return None + record = ci.series_wait(task.series_id, profile["repository"]) + if (record and record["state"] in ci.WAITING + and all(items[0].get(k) == record[k] for k in ("number", "head"))): + return record + return None + + +def elected_wait(task, repo, preflight, lease): + action = preflight["action"] + if action == "fallback" and lease and lease["target"]["stage"] in ci.ORDINARY_STAGES: + return ci.active_wait(repo, lease["target"]) + target = preflight.get("target") or {} + if action == "merge" and target.get("number") and target.get("head"): + return ci.active_wait(repo, target) + if action == "wait" and preflight.get("reason") == "required CI checks are still running": + record = ci.series_wait(task.series_id, repo) + if record and preflight.get("number") == record["number"]: + return record + return None + + +def diagnose(task, profile_id, profile, queue, admission, execution, command, working_dir, record, exclusions): + """Buy a second project preflight only when an elected route contradicts the recorded run.""" + config_path = ci.adapter_config_path(command) + native = pi._expanded_command(["{python}", "-m", "promptpilot.project_pipeline"], "merge") + argv = [*native, "--config", config_path, "merge-ci-diagnose", "--number", str(record["number"]), + "--head", record["head"]] + decision = pi._reserve_execution_admission(task, profile_id, profile, queue, admission, + "tool_preflight", retain_budget=True) + if not decision.get("allowed"): + return None, pi._budget_defer_route(decision, profile_id, profile, queue, mode="tool") + try: + response = pi._tool_preflight(execution, argv, working_dir, + env_extra={"PP_PIPELINE_EXCLUDED_NUMBERS": json.dumps(exclusions), + "PP_DATA_DIR": str(Path(db.DB_PATH).resolve().parent)}) + if response.get("action") == "fallback": + lease = pi._validate_targeted_handoff(response, "merge") + if (lease["repository"] == record["repository"] and lease["config_sha256"] == record["config_sha256"] + and lease.get("target_reservation") is None and lease["target"].get("stage") in ci.ORDINARY_STAGES + and all(lease["target"].get(k) == record[k] for k in ("number", "head"))): + return response, None + if response.get("action") == "wait" and response.get("state") in {"success", "superseded"}: + return None, {"action": "defer", "mode": "tool", "defer_until": + pi._defer_at(time.time() + 5), + "reason": f"MERGE CI {response['state']}; re-elect for fresh checks"} + reason = response.get("reason") or response.get("error") or "conflicting diagnostic target" + except (RuntimeError, KeyError, TypeError, ValueError, OSError) as exc: + reason = str(exc) + finally: + pi.release_execution_admission() + admission["_budget_reservation_revision"] = db.pipeline_github_budget_reservations( + pi._GITHUB_SCAN_LEASE_SCOPE)["revision"] + return None, {"action": "defer", "mode": "tool", "defer_for": "2m", "reason": + f"MERGE CI diagnosis for #{record['number']}: {pi._bounded_defer_text(reason)}"} + + +def poll(task, profile_id, profile, queue, admission, record, preflight=None): + admission = pi._reserve_execution_admission( + task, profile_id, profile, queue, admission, "merge_ci_poll", retain_budget=True) + if not admission.get("allowed"): + return pi._budget_defer_route(admission, profile_id, profile, queue, mode="tool", + preflight=preflight) + account = admission["_lease"] + reservation = pi._execution_budget_context.reservation + identity = task_execution_fingerprint(task) + + def fence(): + account.ensure_owned() + with db._connect() as conn: + conn.execute("BEGIN") + observed = db._pipeline_source_refresh_state( + conn, pi._GITHUB_SCAN_LEASE_SCOPE, task.id, profile_id, "merge", + {"merge_ci_poll": POLL_COST}, bounded_route="merge_ci_poll")["guard"] + if (observed["token"] != reservation.token or observed["execution_sha256"] != identity + or observed["started_at"] != task.started_at.isoformat() + or not db._pipeline_scan_lease_guard_matches(conn, account.guard)): + raise pp.PipelineError("MERGE CI readback lost its task or account reservation") + + route = {"action": "defer", "mode": "tool", "profile_id": profile_id, "queue_id": queue["id"]} + label = f"PR #{record['number']} Actions run {record['run_id']} attempt {record['attempt']}" + try: + fence() + try: + observation = ci.observe_run(pp.GitHub(timeout_seconds=15), record) + except (RuntimeError, OSError, ValueError, KeyError, TypeError): + if time.time() < record["deadline"]: + raise + # This is a local deadline, not a failed CI conclusion. A fresh + # signed diagnosis must still obtain the real run before any write. + observation = {"state": "timeout", "run_id": record["run_id"], "attempt": record["attempt"], + "deadline": record["deadline"]} + fence() + if not ci.save_observation(record, observation): + return dict(route, defer_until=pi._defer_at(time.time() + 5), reason=f"{label}: CI journal changed, re-elect") + except (RuntimeError, OSError, ValueError, KeyError, TypeError, sqlite3.Error) as exc: + return dict(route, defer_for="2m", defer_policy="hard_not_before", + reason=f"{label}: CI readback unavailable: {pi._bounded_defer_text(exc)}") + state = observation["state"] + if state in ci.WAITING: + until = min(time.time() + ci.POLL_SECONDS, observation["deadline"]) + return dict(route, reason=f"{label}: {state}", defer_policy="hard_not_before", + defer_until=pi._defer_at(until)) + if state == record["state"]: + return dict(route, defer_for="2m", defer_policy="hard_not_before", + reason=f"{label}: {state}, awaiting a compatible fresh election") + return dict(route, defer_until=pi._defer_at(time.time() + 5), reason=f"{label}: {state}, re-elect for fresh checks") + + +def add_command(envelope, native, profile_id, lease, gate_file, record): + target = lease["target"] + envelope["ci_wait_command"] = [*native, "merge-ci-wait", "", "--profile", profile_id, + "--number", str(target["number"]), "--head", target["head"], + "--run-id", "", "--attempt", "", "--lease-file", gate_file] + if record: + envelope["ci_wait_record"] = {key: record[key] for key in + ("run_id", "attempt", "state", "deadline", "claimed_at")} + readback = lease.get("ci_attempt_readback") + if (readback and record and record["state"] == "attempt_changed" + and readback["run_id"] == record["run_id"] and readback["previous_attempt"] == record["attempt"]): + envelope["ci_current_attempt"] = readback["attempt"] + return ( + "Для §4 канонического MERGE действует управляемое ожидание CI. Выбери точный CI run и attempt. " + "При наличии ci_wait_record продолжай с его run_id и attempt. При выполняющемся CI вызови " + "ci_wait_command с observe. При waiting или unknown заверши ИТОГ: ПУСТО и освободи воркер. " + "Не запускай watch, sleep или повторный сбор истории. Для единственного разрешённого повтора " + "подтверди временный сбой обязательного задания по логам и все штатные Source, HEAD, ship и " + "gate-проверки. Вызови ci_wait_command с claim для первой упавшей попытки. Только свежий " + "state=claimed с send_allowed=true допускает одну отправку gh run rerun --failed " + "в проверенном репозитории. При любом результате отправки выполни observe для возвращённой " + "попытки. При неясном ответе, отказе или ранее занятом claim повторная отправка запрещена. " + "Готовый CI требует всех штатных восьми проверок и новой проверки актуальности перед записью. " + "При failed или timeout пройди штатную диагностику именно этой попытки. При смене HEAD, " + "попытки, потере ship или отказе команды остановись для новой сверки. Если новое подписанное " + "назначение содержит ci_current_attempt, выполни только observe с этим номером попытки для того же " + "run_id. Срок ожидания сохраняется. Даже при success закончи ИТОГ: ПУСТО для нового выбора цели.\n\n" + ) diff --git a/promptpilot/merge_ci_wait.py b/promptpilot/merge_ci_wait.py new file mode 100644 index 0000000..f9849db --- /dev/null +++ b/promptpilot/merge_ci_wait.py @@ -0,0 +1,431 @@ +"""Hand an ordinary MERGE's external Actions wait back to the scheduler. + +This module reads GitHub. The canonical MERGE procedure owns the diagnosis, +its scheduling and product gates, and the single authorized rerun request. +""" + +import json +import math +import os +import re +import sqlite3 +import time +from contextlib import nullcontext +from datetime import datetime, timezone +from pathlib import Path + +from . import fallback_handoff, merge_checkpoint, project_pipeline as pp + + +POLL_SECONDS = 120 +WAIT_SECONDS = 35 * 60 +WAITING = {"waiting", "unknown"} +TERMINAL = {"success", "failed", "timeout", "superseded", "attempt_changed"} +PENDING = {"queued", "in_progress", "waiting", "pending", "requested"} +FAILURES = {"failure", "timed_out", "cancelled"} +WORKFLOW = ".github/workflows/ci.yml" +ORDINARY_STAGES = {"merge", "integration-merge-ready", "legacy-integration-merge-ready"} +UNRESOLVED = {"failed", "timeout", "attempt_changed"} + + +def _require(condition, reason): + if not condition: + raise pp.PipelineError(reason) + + +def _id(value): + return type(value) is int and 0 < value < 2**63 + + +def _key(repository, number, head): + # Independent of the config, workflow, and task. A fresh election cannot + # issue a second rerun for another run on the same unchanged PR. + return "pipeline_merge_ci_wait:v1:" + pp.digest([repository, number, head]) + + +def _receipt_key(series_id): + return f"pipeline_merge_ci_wait:task:v1:{series_id}" + + +def _get(conn, key): + row = conn.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone() + return json.loads(row[0]) if row is not None else None + + +def _put(conn, key, record): + conn.execute("INSERT OR REPLACE INTO settings(key,value) VALUES(?,?)", + (key, json.dumps(record, sort_keys=True))) + + +def _load(conn, repository, target): + number, head = target["number"], target["head"] + record = _get(conn, _key(repository, number, head)) + if record is not None: + _require(isinstance(record, dict) and record["version"] == 1 + and (record["repository"], record["number"], record["head"]) == (repository, number, head) + and _id(record["run_id"]) and _id(record["attempt"]) and _id(record["workflow_id"]) + and re.fullmatch(r"[0-9a-f]{64}", record["config_sha256"]) + and isinstance(record["base_branch"], str) and record["base_branch"] + and record["state"] in WAITING | TERMINAL and math.isfinite(record["deadline"]) + and (record["claimed_at"] is None or math.isfinite(record["claimed_at"])), + "corrupt external CI journal") + return record + + +def active_wait(repository, target): + from . import db + + if not target: + return None + with db._connect() as conn: + record = _load(conn, repository, target) + # An exact-head election can return after an operator restores ship or a + # previously closed PR is reopened. Reobserve its run before trusting it. + return record if record and record["state"] != "success" else None + + +def series_wait(series_id, repository): + """An unsigned 'wait' election can reference this journal only for a fresh PR readback.""" + from . import db + + with db._connect() as conn: + conn.execute("BEGIN") + hint = _get(conn, f"pipeline_merge_ci_wait:series:v1:{series_id}") + if not hint or hint["repository"] != repository: + return None + record = _load(conn, repository, hint) + return record if record and record["state"] not in {"success", "superseded"} else None + + +def _status(gh, record): + repo, number, head = (record[k] for k in ("repository", "number", "head")) + prefix = "repos/" + repo + pr = gh.json("api", f"{prefix}/pulls/{number}") + base = record["base_branch"] + _require(pr["number"] == number and pr["base"]["repo"]["full_name"] == repo, + "Actions observation returned another pull request") + labels = {item["name"] for item in pr["labels"]} + if (pr["state"] != "open" or pr["draft"] is not False or pr["merged"] is not False or pr["head"]["sha"] != head + or pr["base"]["ref"] != base or "ship" not in labels + or labels & {"hold", "needs-decision", "manual", "changes-requested"}): + return None + run = gh.json("api", f"{prefix}/actions/runs/{record['run_id']}") + head_ref, head_repo = pr["head"]["ref"], pr["head"]["repo"] + _require(run["id"] == record["run_id"] and _id(run["workflow_id"]) and _id(run["run_attempt"]) + and run["repository"]["full_name"] == repo and run["path"] == WORKFLOW + and run["event"] in {"pull_request", "workflow_dispatch", "push"} + and run["head_sha"] == head and run["head_branch"] == head_ref + and run["head_repository"]["full_name"] == head_repo["full_name"] + and (not record.get("workflow_id") or record["workflow_id"] == run["workflow_id"]), + "Actions run does not match this CI workflow, repository and PR head") + # workflow_dispatch can have a PR association too (#2731). Do not accept + # an arbitrary workflow which happens to mention the same commit. + matches = [p for p in run["pull_requests"] if p["number"] == number] + _require(len(matches) == 1 and matches[0]["head"]["sha"] == head + and matches[0]["head"]["ref"] == head_ref and matches[0]["base"]["ref"] == base + and matches[0]["head"]["repo"]["id"] == head_repo["id"] + and matches[0]["base"]["repo"]["id"] == pr["base"]["repo"]["id"], + "Actions run lacks the elected PR association") + _require((run["status"] in PENDING and run["conclusion"] is None) + or (run["status"] == "completed" and isinstance(run["conclusion"], str) and run["conclusion"]), + "Actions run has incomplete status") + return run + + +def _started(run): + stamp = datetime.fromisoformat(run["run_started_at"].replace("Z", "+00:00")) + _require(stamp.tzinfo is not None, "Actions run start time needs a timezone") + return stamp.timestamp() + + +def _observation(record, run, now): + result = dict(run_id=record["run_id"], attempt=record["attempt"], deadline=record["deadline"]) + if run is None: + return dict(result, state="superseded") + if run["run_attempt"] > record["attempt"]: + return dict(result, state="attempt_changed", current_attempt=run["run_attempt"]) + if run["run_attempt"] < record["attempt"]: + _require(record["claimed_at"] is not None and run["run_attempt"] == record["attempt"] - 1, + "unexpected earlier Actions attempt") + state = "unknown" + elif run["status"] == "completed": + # A terminal fact already on GitHub wins over a late local poll. + return dict(result, state="success" if run["conclusion"] == "success" else "failed") + else: + state = "waiting" + result["deadline"] = min(result["deadline"], _started(run) + WAIT_SECONDS) + return dict(result, state="timeout" if now >= result["deadline"] else state) + + +def observe_run(gh, record, *, now=None): + """Bounded readback for a scheduler-admitted poll. No task or GitHub writes.""" + run = _status(gh, record) + return _observation(record, run, time.time() if now is None else now) + + +def _observed(record, observation): + _require(observation["state"] in WAITING | TERMINAL + and observation["run_id"] == record["run_id"] and observation["attempt"] == record["attempt"] + and math.isfinite(observation["deadline"]) and observation["deadline"] <= record["deadline"], + "CI readback differs from the saved wait") + updated = dict(record, state=observation["state"], deadline=observation["deadline"]) + if observation["state"] == "attempt_changed" and record["claimed_at"] is None: + # An external rerun also consumes the per-HEAD allowance. + updated["claimed_at"] = time.time() + return updated + + +def save_observation(record, observation): + """Publish only a readback for the record seen before network I/O.""" + from . import db + + updated = _observed(record, observation) + with db._connect(immediate=True) as conn: + if _load(conn, record["repository"], record) != record: + return False + _put(conn, _key(record["repository"], record["number"], record["head"]), updated) + return True + + +def defer_time(task, *, conn=None): + """Schedule a completed empty turn's next poll while preserving its report and usage.""" + from . import db + + if not getattr(task, "series_id", None) or not getattr(task, "started_at", None): + return None + with (nullcontext(conn) if conn is not None else db._connect()) as reader: + if conn is None: + reader.execute("BEGIN") + try: + notice = _get(reader, _receipt_key(task.series_id)) + if not notice or (notice["task_id"], notice["started_at"]) != (task.id, task.started_at.isoformat()): + return None + row = reader.execute("SELECT merge_checkpoint_gate FROM tasks WHERE id=? AND series_id=? " + "AND started_at=? AND status='completed' AND verdict='ПУСТО'", + (task.id, task.series_id, notice["started_at"])).fetchone() + if not row or row[0] != notice["gate"]: + return None + record = _load(reader, notice["repository"], notice) + if not record or (record["run_id"], record["attempt"]) != (notice["run_id"], notice["attempt"]): + return None + if record["state"] == "success" and record.get("adoption_gate") == notice["gate"]: + return datetime.fromtimestamp(min(time.time(), notice["observed_at"]) + 5, timezone.utc) + if record["state"] not in WAITING: + return None + when = min(time.time() + POLL_SECONDS, notice["observed_at"] + POLL_SECONDS, record["deadline"]) + return datetime.fromtimestamp(when, timezone.utc) + except (pp.PipelineError, ValueError, TypeError, KeyError, OverflowError): + # A damaged optional wake receipt must not disable ordinary recurrence. + return None + + +def _check_failure(gh, record, config): + path = f"repos/{record['repository']}/actions/runs/{record['run_id']}/attempts/1/jobs?per_page=100" + answer = gh.json("api", path) + jobs = answer["jobs"] + _require(isinstance(jobs, list) and len(jobs) == answer["total_count"] <= 100 + and any(j["name"] in config["required_checks"] and j["status"] == "completed" + and j["conclusion"] in FAILURES and j["head_sha"] == record["head"] + and j["run_id"] == record["run_id"] and j["run_attempt"] == 1 for j in jobs), + "no failed required check in the exact original attempt") + + +def adapter_config_path(command): + _require(command and command[-2:] == ["next", "merge"], "expected the configured MERGE adapter") + options = command[:-2] + flags = [index for index, arg in enumerate(options) if arg == "--config" or arg.startswith("--config=")] + _require(len(flags) <= 1, "ambiguous MERGE adapter config") + if not flags: + return "pipelinectl.json" + index = flags[0] + if options[index] == "--config": + _require(index + 1 < len(options), "MERGE adapter config path is missing") + path = options[index + 1] + else: + path = options[index].partition("=")[2] + _require(path and not path.startswith("-"), "invalid MERGE adapter config path") + return path + + +def diagnose(gh, config, config_path, number, head): + """Elect a signed ordinary fallback after an exact CI run needs investigation.""" + from .review_routing_policy import require_legacy + + def wait(reason, state="unavailable"): + return {"action": "wait", "number": number, "state": state, "reason": reason} + + try: + _require(_id(number) and merge_checkpoint.SHA.fullmatch(head), "invalid CI target") + _require(number not in pp.admission_exclusions() and pp._configured_replica_count() == 1, + "CI diagnosis requires an available ordinary MERGE target") + repo = config["repository"] + record = active_wait(repo, {"number": number, "head": head}) + _require(record and record["state"] in UNRESOLVED, "no unresolved exact Actions attempt") + _require(config.get("fallback_handoff") == "target-v1" + and record["config_sha256"] == fallback_handoff.config_digest(config), + "CI diagnosis config no longer matches its exact Actions journal") + pp.ensure_identity(gh, config) + _require(not pp.pending_merge_intents(gh, config), "pending merge cleanup takes precedence") + health = pp.run_health(config, config_path=config_path) + _require(fallback_handoff.config_digest(config) == record["config_sha256"], + "MERGE configuration changed during diagnosis") + fallback_handoff.validate_health(health) + queue = health["merge_executable"] + _require(queue and queue[0]["number"] == number and queue[0]["head"] == head + and queue[0]["stage"] in ORDINARY_STAGES, + "the first executable MERGE target changed") + observed = observe_run(gh, record) + if observed["state"] != record["state"]: + _require(save_observation(record, observed), "CI journal changed during diagnosis") + return wait("Actions readback changed, re-elect before diagnosis", observed["state"]) + require_legacy(gh, config, number) + _require(active_wait(repo, record) == record + and fallback_handoff.config_digest(pp.load_config(config_path)) == record["config_sha256"], + "CI journal or configuration changed before the handoff") + offer = fallback_handoff.create(config, health, "merge", queue[0], + f"Actions run {record['run_id']} attempt {record['attempt']} requires diagnosis") + if observed["state"] == "attempt_changed": + current = observed["current_attempt"] + lease = fallback_handoff.validate(offer, "merge") + lease["ci_attempt_readback"] = {"run_id": record["run_id"], "previous_attempt": record["attempt"], + "attempt": current} + offer["handoff"]["lease"] = pp.encode_signed_lease(lease) + offer["ci_current_attempt"] = current + return offer + except (RuntimeError, OSError, KeyError, ValueError, TypeError, sqlite3.Error) as exc: + return wait(str(exc)) + + +def _apply(args, env): + from . import db, pipeline_insights as pi + + raw = env.get("PP_TASK_ID", "") + marker = env.get("PP_TASK_STARTED_AT") + _require(re.fullmatch(r"[1-9][0-9]{0,18}", raw) and _id(int(raw)) and marker + and _id(args.number) and _id(args.run_id) and _id(args.attempt) + and merge_checkpoint.SHA.fullmatch(args.head), "invalid CI task or target identity") + task_id = int(raw) + task = db.get_task(task_id) + binding = pi._matching_queue(task) if task else None + _require(binding and binding[0] == args.profile and binding[2]["id"] == "merge" + and binding[2].get("item_blockers") is True, "CI wait needs an ordinary managed MERGE") + profile, queue = binding[1:] + policy = pi._github_budget_policy(profile) + execution = queue["execution"] + _require(policy and policy.get("costs") and str(execution.get("mode", "auto")).lower() == "auto" + and str(execution.get("stage") or queue["id"]).lower() == "merge" + and execution.get("merge_confirmation") == "bounded-v1" + and profile["github_budget"].get("source_cost_protocol") == "source-graphql-cost-v1", + "CI wait needs costed managed MERGE admission") + lease, token = merge_checkpoint._gate_file(task_id, args.lease_file) + repo, target = lease["repository"], lease["target"] + _require(not lease.get("target_reservation") and repo == profile["repository"] + and target["stage"] in ORDINARY_STAGES + and (args.number, args.head) == (target["number"], target["head"]), + "CI wait target differs from the signed ordinary election") + command = pi._tool_command(queue["execution"], "merge") + path = Path(adapter_config_path(command)) + if not path.is_absolute(): + path = Path(task.working_dir or ".").resolve() / path + config = pp.load_config(str(path)) + gate = pp.digest([marker, token]) + + def guard(conn): + fallback_handoff.validate_lease(lease, "merge") + _require(pi._matching_queue(task) == binding + and fallback_handoff.config_digest(config) == lease["config_sha256"] + and fallback_handoff.config_digest(pp.load_config(str(path))) == lease["config_sha256"], + "MERGE configuration changed") + state = db._pipeline_source_refresh_state(conn, policy["lease_scope"], task_id, args.profile, "merge", + policy["costs"])["guard"] + row = conn.execute("SELECT merge_checkpoint_gate FROM tasks WHERE id=?", (task_id,)).fetchone() + _require(state["route"] == "fallback_targeted" and state["started_at"] == marker and row[0] == gate, + "CI wait lost its admitted election") + return state + + with db._connect() as conn: + conn.execute("BEGIN") + admitted = guard(conn) + previous = _load(conn, repo, target) + claiming = args.operation == "claim" + if previous: + _require(lease["config_sha256"] == previous["config_sha256"], "previous CI journal has another config") + if claiming and previous["claimed_at"] is not None: + return dict(state="already_claimed", run_id=previous["run_id"], attempt=previous["attempt"]) + if previous["run_id"] != args.run_id: + _require(previous["state"] in TERMINAL and previous["claimed_at"] is None, + "another CI run owns the waiting record") + same = previous if previous and previous["run_id"] == args.run_id else None + record = same or dict(version=1, repository=repo, number=args.number, head=args.head, run_id=args.run_id, + attempt=args.attempt, config_sha256=lease["config_sha256"], base_branch=config["base_branch"], + claimed_at=None, deadline=time.time() + WAIT_SECONDS) + adopting = bool(same and not claiming and args.attempt != same["attempt"]) + if adopting: + expected = {"run_id": args.run_id, "previous_attempt": same["attempt"], "attempt": args.attempt} + _require(same["state"] == "attempt_changed" and args.attempt > same["attempt"] + and lease.get("ci_attempt_readback") == expected, + "observing a new Actions attempt requires its fresh signed diagnosis") + gh = pp.GitHub(timeout_seconds=config["github_timeout_seconds"]) + run = _status(gh, record) + now = time.time() + if not run: + if not same: + return {"state": "superseded"} + updated = dict(record, state="superseded") + elif claiming: + _require(args.attempt == run["run_attempt"] == 1 and run["status"] == "completed" + and run["conclusion"] in FAILURES, "claim requires the failed original attempt") + _check_failure(gh, record, config) + now = time.time() + updated = dict(record, state="unknown", attempt=2, workflow_id=run["workflow_id"], + claimed_at=now, deadline=now + WAIT_SECONDS) + else: + if adopting: + _require(run["run_attempt"] == args.attempt, "diagnosed Actions attempt changed again") + record = dict(record, attempt=args.attempt, claimed_at=(record["claimed_at"] or now), adoption_gate=gate) + if not same: + _require(run["run_attempt"] == args.attempt, "Actions attempt differs from observation") + record["workflow_id"] = run["workflow_id"] + record["deadline"] = min(now, _started(run)) + WAIT_SECONDS + # An existing external attempt > 1 already consumed the allowed rerun. + if args.attempt > 1: + record["claimed_at"] = min(now, _started(run)) + updated = _observed(record, _observation(record, run, now)) + + reelect = updated["state"] == "success" and updated.get("adoption_gate") == gate + with db._connect(immediate=True) as conn: + _require(guard(conn) == admitted and _load(conn, repo, target) == previous, + "MERGE CI record or admission changed concurrently; reread before continuing") + _put(conn, _key(repo, args.number, args.head), updated) + _put(conn, f"pipeline_merge_ci_wait:series:v1:{task.series_id}", + dict(repository=repo, number=args.number, head=args.head)) + if updated["state"] in WAITING or reelect: + _put(conn, _receipt_key(task.series_id), + dict(repository=repo, number=args.number, head=args.head, run_id=updated["run_id"], + attempt=updated["attempt"], task_id=task_id, started_at=marker, gate=gate, observed_at=now)) + else: + conn.execute("DELETE FROM settings WHERE key=?", (_receipt_key(task.series_id),)) + granted = claiming and updated["state"] == "unknown" + return dict(state="claimed" if granted else updated["state"], run_id=updated["run_id"], + attempt=updated["attempt"], deadline=updated["deadline"], send_allowed=granted, reelect=reelect) + + +def add_arguments(parser): + parser.add_argument("operation", choices=("claim", "observe")) + parser.add_argument("--profile", required=True) + parser.add_argument("--number", type=int, required=True) + parser.add_argument("--head", required=True) + parser.add_argument("--run-id", type=int, required=True) + parser.add_argument("--attempt", type=int, required=True) + parser.add_argument("--lease-file", required=True) + + +def execute(args): + try: + result = _apply(args, os.environ) + except (RuntimeError, ValueError, KeyError, IndexError, TypeError, AttributeError, OSError, sqlite3.Error) as exc: + result = {"state": "refused", "reason": str(exc)} + result.setdefault("send_allowed", False) + result["product_mutation_authorized"] = False + print(json.dumps(result, ensure_ascii=False)) + return int(result["state"] == "refused") diff --git a/promptpilot/pipeline_insights.py b/promptpilot/pipeline_insights.py index b395b2d..73be371 100644 --- a/promptpilot/pipeline_insights.py +++ b/promptpilot/pipeline_insights.py @@ -819,6 +819,9 @@ def _budget_policy_for_route(policy: dict, route: str | None) -> dict: if route == "merge_receipt": from .merge_finish_transport import RECEIPT_COST return dict(policy, budget_route=route, requested_cost=dict(RECEIPT_COST), cost_accounting=True) + if route == "merge_ci_poll": + from .merge_ci_dispatch import POLL_COST + return dict(policy, budget_route=route, requested_cost=dict(POLL_COST), cost_accounting=True) if route == "merge_confirmation": from .merge_finish_transport import reservation_cost return dict(policy, budget_route=route, requested_cost=reservation_cost(policy), @@ -1550,6 +1553,11 @@ def _reserve_execution_admission( from .merge_checkpoint import blocks_fallback if blocks_fallback(profile.get("repository"), fallback_target): raise ValueError("prior MERGE confirmation send needs exact readback before general fallback") + if budget_route == "skill": + from . import merge_ci_dispatch, merge_ci_wait + if (merge_ci_dispatch.enabled(queue, profile) + and merge_ci_wait.series_wait(task.series_id, profile["repository"])): + raise ValueError("saved MERGE CI wait needs a targeted election before general fallback") policy = _github_budget_policy(profile) if policy is None: _clear_budget_waiter_after_admission(task) @@ -3646,6 +3654,7 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, from .pipeline_item_holds import (prepare, claim_progress_attempt, released_progress, progress_attempt_blocked, unproved_progress_hold) from .merge_progress_probe import measurements + from . import merge_ci_dispatch progress_scope = (queue.get("item_blockers") is True and str((queue.get("execution") or {}).get("stage") or queue.get("id") or "").lower() == "merge") progress_data = read_cached(profile_id, db.list_series()) if queue.get("item_blockers") is True else {} @@ -3653,8 +3662,11 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, return {"action": "defer", "mode": "tool", "defer_for": "30m", "reason": "canonical recovery progress was consumed by another occurrence", "profile_id": profile_id, "queue_id": queue.get("id")} + ci_configured = merge_ci_dispatch.enabled(queue, profile) + pending_ci = (merge_ci_dispatch.source_wait(task, profile, progress_data) + if ci_configured and retain_budget else None) progress = measurements(sys.modules[__name__], task, profile_id, profile, queue, progress_data, - working_dir) if progress_scope else {} + working_dir) if progress_scope and not pending_ci else {} if progress_scope and unproved_progress_hold(task, progress_data, progress): return {"action": "defer", "mode": "tool", "defer_for": "30m", "reason": "held canonical recovery has no verified unused progress", @@ -3793,6 +3805,9 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, 'PP_TASK_ID':str(task.id),'PP_TASK_STARTED_AT':started.astimezone(timezone.utc).isoformat(), 'PP_PROVIDER_OWNERSHIP_KIND':'headless','PP_DATA_DIR':str(Path(db.DB_PATH).resolve().parent)}) command = _tool_command(execution, stage) + managed_confirmation = (stage == "merge" and mode == "auto" and queue.get("item_blockers") is True + and execution.get("merge_confirmation") == "bounded-v1" + and profile.get("github_budget", {}).get("source_cost_protocol") == "source-graphql-cost-v1") if typed_queue and (stage not in {"review", "fix"} or not command or command[-2:] != ["next", stage]): return {"action": "block", "mode": "tool", "reason": "typed routing requires its exact next stage command"} if (stage == "merge" and queue.get("id") == "merge" and mode == "auto" @@ -3803,6 +3818,15 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, waiting = merge_checkpoint.prepare_source(task, profile_id, profile) if waiting is not None: return waiting + ci_wait_enabled = (ci_configured and not owned_preflight and not progress_releases + and command and command[-2:] == ["next", "merge"]) + ci_record = None + if ci_wait_enabled and pending_ci and pending_ci["number"] not in exclusions: + with _github_scan_admission(profile, f"MERGE CI readback {profile_id}", profile_id=profile_id, + budget_route="merge_ci_poll", task=task) as admission: + if not admission.get("allowed"): + return _budget_defer_route(admission, profile_id, profile, queue) + return merge_ci_dispatch.poll(task, profile_id, profile, queue, admission, pending_ci) with _github_scan_admission( profile, f"pipeline preflight {profile_id}/{stage}", profile_id=profile_id, budget_route="tool_preflight", @@ -4095,9 +4119,6 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, validated_target_stage = None fallback_lease = None merge_checkpoint_hint = None - managed_confirmation = (stage == "merge" and mode == "auto" and queue.get("item_blockers") is True - and execution.get("merge_confirmation") == "bounded-v1" - and profile.get("github_budget", {}).get("source_cost_protocol") == "source-graphql-cost-v1") if owned_preflight and preflight_action in {"audit", "fallback", "recover"}: try: from . import project_pipeline @@ -4212,6 +4233,26 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, return {"action": "defer", "mode": "tool", "defer_for": "2m", "reason": "saved MERGE checkpoint awaits matching fresh Source"} merge_checkpoint_hint = None + if ci_wait_enabled and target_reservation is None and merge_checkpoint_hint is None: + from . import merge_ci_wait + ci_record = merge_ci_dispatch.elected_wait(task, profile["repository"], preflight, fallback_lease) + if ci_record and (ci_record["state"] in merge_ci_wait.WAITING + or ci_record["state"] == "attempt_changed" or fallback_lease is None): + if not retain_budget: + return {"action": "defer", "mode": "tool", "defer_for": "2m", + "reason": "MERGE CI readback requires retained Native admission"} + if ci_record["state"] in merge_ci_wait.UNRESOLVED and not positive_claim: + diagnostic, deferred = merge_ci_dispatch.diagnose( + task, profile_id, profile, queue, admission, execution, command, + working_dir, ci_record, exclusions) + if deferred: + return deferred + preflight = diagnostic + fallback_lease = _validate_targeted_handoff(preflight, stage) + preflight_action = "fallback" + validated_target_stage = fallback_lease["target"]["stage"] + else: + return merge_ci_dispatch.poll(task, profile_id, profile, queue, admission, ci_record, preflight) provider_route = None if preflight_action == "fallback" and mode == "auto": provider_route = ("fallback_targeted" if "handoff" in preflight @@ -4454,6 +4495,10 @@ def execution_route(task, fallback_prompt: str, working_dir: str | None = None, ) if managed_confirmation and target_reservation is None: native = _expanded_command(["{python}", "-m", "promptpilot.project_pipeline"], stage) + if (ci_wait_enabled and target["stage"] in merge_ci_wait.ORDINARY_STAGES + and gate_command[-2] == "--lease-file"): + pre_review_guard += merge_ci_dispatch.add_command( + envelope, native, profile_id, fallback_lease, gate_command[-1], ci_record) envelope["checkpoint_record_command"] = [*native, "merge-checkpoint", "record", "--profile", profile_id, "--number", str(target["number"]), "--from", "", "--base", "", "--to", "", "--tree", "", @@ -5396,7 +5441,7 @@ def _with_persisted_refresh_status(result: dict, profile_id: str, # rows without changing the real cache stale/epoch/profile/lease guards. # Unknown legacy routes remain conservative. route = (status.get("github_budget") or {}).get("budget_route") - if route in {"skill", "tool_preflight", "tool", "fallback_targeted", "merge_confirmation", "merge_full_confirmation", "merge_receipt"}: + if route in {"skill", "tool_preflight", "tool", "fallback_targeted", "merge_confirmation", "merge_full_confirmation", "merge_receipt", "merge_ci_poll"}: return result raw_defer_until = status.get("refresh_deferred_until") defer_until = _parse_time(raw_defer_until) diff --git a/promptpilot/project_pipeline.py b/promptpilot/project_pipeline.py index 2ed0e28..fc2681b 100644 --- a/promptpilot/project_pipeline.py +++ b/promptpilot/project_pipeline.py @@ -2908,8 +2908,12 @@ def run(argv=None) -> int: if name == "tail-create": target.add_argument("--item", type=int, required=True, help="verified issue item selected by the TAIL worker") target.add_argument("--context-file", type=Path, help="UTF-8 explanation from checking the current base branch") - from . import merge_checkpoint + from . import merge_checkpoint, merge_ci_wait merge_checkpoint.add_arguments(sub.add_parser("merge-checkpoint")) + merge_ci_wait.add_arguments(sub.add_parser("merge-ci-wait")) + diagnose_parser = sub.add_parser("merge-ci-diagnose") + diagnose_parser.add_argument("--number", type=int, required=True) + diagnose_parser.add_argument("--head", required=True) source_refresh_parser = sub.add_parser("source-refresh") source_refresh_parser.add_argument("--profile", required=True) source_refresh_parser.add_argument("--final", action="store_true") @@ -2953,6 +2957,8 @@ def run(argv=None) -> int: args = parser.parse_args(argv) if args.command == "merge-checkpoint": return merge_checkpoint.execute(args) + if args.command == "merge-ci-wait": + return merge_ci_wait.execute(args) if args.command in ("source-refresh", "budget-refresh"): from .pipeline_source_refresh import run as source_refresh_run @@ -2998,6 +3004,8 @@ def run(argv=None) -> int: elif args.command == "inspect-merge-progress": from .merge_admission_progress import observe value = observe(gh, config, args.config, args.number, args.head) + elif args.command == "merge-ci-diagnose": + value = merge_ci_wait.diagnose(gh, config, args.config, args.number, args.head) elif args.command == "next": if args.stage == "review": value = next_review(gh, config, config_path=args.config) diff --git a/promptpilot/worker.py b/promptpilot/worker.py index 03b20cd..8e52cdb 100644 --- a/promptpilot/worker.py +++ b/promptpilot/worker.py @@ -1179,6 +1179,9 @@ def _maybe_recur(task, failed: bool = False): else db.parse_recurrence(recurrence)) if not next_dt: return + if series and task.verdict == "ПУСТО": + from .merge_ci_wait import defer_time + next_dt = min(next_dt, defer_time(task) or next_dt) from .models import TaskCreate # The current series template owns future instructions. A running # occurrence keeps its original prompt for audit, while later occurrences diff --git a/tests/test_merge_ci_dispatch.py b/tests/test_merge_ci_dispatch.py new file mode 100644 index 0000000..d851d36 --- /dev/null +++ b/tests/test_merge_ci_dispatch.py @@ -0,0 +1,136 @@ +"""Exercise the worker's ordinary handoff, recurrence and read-only Actions poll.""" + +from datetime import datetime, timedelta, timezone + +import pytest + +from promptpilot import fallback_handoff, merge_ci_wait, pipeline_insights as pi, project_pipeline as pp, worker +from promptpilot.models import TaskCreate +from tests.test_fallback_handoff import health +from tests.test_merge_checkpoint import dispatch +from tests.test_merge_ci_wait import elected as elected +from tests.test_merge_final_source import merge_dispatch as merge_dispatch +from tests.test_pipeline_source_refresh import continuation as continuation, targeted_merge as targeted_merge + + +def finish(e, *, repair=False): + f = e.f + assert e.call("claim")["send_allowed"] is True + pi.release_execution_admission() + result = "Recorded the external Actions attempt.\nИТОГ: ПУСТО" + assert f.db.mark_completed(f.task.id, result, verdict="ПУСТО", usage={"input_tokens": 231, "output_tokens": 51}) + if repair: + assert f.db.repair_active_series_occurrences() == [f.task.series_id] + else: + worker._recur_after_run(f.task) + with f.db._connect() as conn: + row = conn.execute("SELECT id,scheduled_at FROM tasks WHERE series_id=? AND status='pending'", + (f.task.series_id,)).fetchone() + assert datetime.now(timezone.utc) < datetime.fromisoformat(row["scheduled_at"]) <= ( + datetime.now(timezone.utc) + timedelta(seconds=merge_ci_wait.POLL_SECONDS)) + usage = conn.execute("SELECT input_tokens,output_tokens FROM task_token_usage WHERE task_id=?", + (f.task.id,)).fetchone() + assert tuple(usage) == (231, 51) and f.db.get_task(f.task.id).result == result + other = f.db.create_task(TaskCreate(prompt="another runnable queue")) + assert f.db.get_next_runnable().id == other.id + with f.db._connect() as conn: + conn.execute("UPDATE tasks SET scheduled_at=? WHERE id=?", (datetime.now(timezone.utc).isoformat(), row["id"])) + f.task = f.db.get_next_runnable() + assert f.task.id == row["id"] + + +def cached(f): + return {"repository": f.profile["repository"], "diagnostics": health("merge"), + "cache": {"profile_hash": pi._profile_fingerprint(f.profile), "complete": True, + "available": True, "stale": False}, + "queues": [{"id": "merge", "membership_complete": True, "items": []}]} + + +@pytest.mark.parametrize("repair", [True, False]) +def test_poll_releases_worker_and_reserves_two_reads_without_replaying_election(elected, monkeypatch, repair): + e = elected + finish(e, repair=repair) + monkeypatch.setattr(pi, "read_cached", lambda *_: cached(e.f)) + monkeypatch.setattr(pi, "_tool_preflight", lambda *_: pytest.fail("polled the entire queue")) + from promptpilot import merge_progress_probe + monkeypatch.setattr(merge_progress_probe, "measurements", lambda *_: pytest.fail("polled the full PR history")) + e.gh.run.update(run_attempt=2, status="in_progress", conclusion=None) + e.gh.requests.clear() + waiting = dispatch(e.f) + assert waiting["action"] == "defer" and waiting["defer_policy"] == "hard_not_before", waiting + assert len(e.gh.requests) == 2 + ledger = e.f.db.pipeline_github_budget_reservations("github-default") + assert ledger["count"] == 1 and ledger["totals"] == {"core": 2, "graphql": 0, "search": 0} + pi.release_execution_admission() + assert e.f.db.pipeline_github_budget_reservations("github-default")["count"] == 0 + e.gh.run.update(status="completed", conclusion="success") + terminal = dispatch(e.f) + assert terminal["action"] == "defer" and "success" in terminal["reason"] + assert worker._pipeline_defer_time(terminal) is not None + assert merge_ci_wait.active_wait(e.repo, e.target) is None + + +def test_green_election_for_another_run_cannot_finish_the_saved_attempt(elected, monkeypatch): + e = elected + finish(e) + monkeypatch.setattr(pi, "_tool_preflight", lambda *_: {"action": "merge", "target": e.target, "lease": "other"}) + e.gh.run.update(run_attempt=2, status="in_progress", conclusion=None) + result = dispatch(e.f) + assert result["action"] == "defer" and "attempt 2" in result["reason"], result + pi.release_execution_admission() + e.gh.pr["head"]["sha"] = "f" * 40 + result = dispatch(e.f) + assert result["action"] == "defer" and "superseded" in result["reason"] + assert merge_ci_wait.active_wait(e.repo, {"number": 42, "head": "f" * 40}) is None + + +def test_unsigned_skill_cannot_reissue_an_ambiguous_send(elected, monkeypatch): + e = elected + finish(e) + monkeypatch.setattr(pi, "_tool_preflight", lambda *_: {"action": "fallback", "reason": "unavailable"}) + result = dispatch(e.f) + assert result["action"] == "defer" and "targeted election" in result["reason"], result + + +def test_unavailable_readback_at_deadline_preserves_the_claim_for_diagnosis(elected, monkeypatch): + e = elected + finish(e) + record = merge_ci_wait.active_wait(e.repo, e.target) + assert merge_ci_wait.save_observation(record, {"state": "unknown", "run_id": record["run_id"], + "attempt": record["attempt"], "deadline": 1}) + monkeypatch.setattr(pi, "read_cached", lambda *_: cached(e.f)) + def offline(*args): + raise pp.PipelineError("readback unavailable") + monkeypatch.setattr(e.gh, "json", offline) + result = dispatch(e.f) + assert result["action"] == "defer" and "timeout" in result["reason"], result + saved = merge_ci_wait.active_wait(e.repo, e.target) + assert saved["state"] == "timeout" and saved["claimed_at"] == record["claimed_at"] + + +def test_failed_saved_attempt_enters_signed_diagnosis_when_another_run_is_green(elected, monkeypatch): + e = elected + finish(e) + e.gh.run.update(run_attempt=2, status="completed", conclusion="failure") + config_path = e.f.profile["queues"][0]["execution"]["command"][2] + live = health("merge") + handoff = fallback_handoff.create(pp.load_config(config_path), live, "merge", live["merge_executable"][0], + "inspect the saved CI failure") + calls = [] + + def preflight(execution, argv, directory, **kwargs): + calls.append(argv) + if "merge-ci-diagnose" in argv: + assert e.f.db.pipeline_github_budget_reservations("github-default")["items"][0]["route"] == "tool_preflight" + return handoff + return {"action": "merge", "target": e.target, "lease": "another-green-run"} + + monkeypatch.setattr(pi, "_tool_preflight", preflight) + first = dispatch(e.f) + assert first["action"] == "defer" and "failed" in first["reason"] + pi.release_execution_admission() + route = dispatch(e.f) + assert route["action"] == "prompt" and route["target"]["number"] == 42, route + assert '"ci_wait_record"' in route["prompt"] and '"ci_wait_command"' in route["prompt"] + assert route["preflight"] == handoff and route["gate_command"][-2] == "--lease-file" + assert len(calls) == 3 diff --git a/tests/test_merge_ci_wait.py b/tests/test_merge_ci_wait.py new file mode 100644 index 0000000..a3a90a8 --- /dev/null +++ b/tests/test_merge_ci_wait.py @@ -0,0 +1,307 @@ +"""Exercise CI waiting from the ordinary signed fallback through the public CLI.""" +import argparse +import json +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from pathlib import Path +from threading import Barrier +from types import SimpleNamespace + +import pytest + +from promptpilot import entrypoint, fallback_handoff, merge_ci_wait as ci +from promptpilot import pipeline_insights as pi, project_pipeline as pp +from tests.test_fallback_handoff import HEAD, health +from tests.test_merge_checkpoint import dispatch +from tests.test_merge_final_source import merge_dispatch as merge_dispatch +from tests.test_pipeline_source_refresh import continuation as continuation, targeted_merge as targeted_merge + + +class Actions: + def __init__(self, repo): + repository = {"full_name": repo, "id": 101} + self.pr = {"state": "open", "draft": False, "merged": False, "number": 42, + "head": {"ref": "my-branch", "sha": HEAD, "repo": repository}, + "base": {"ref": "main", "repo": repository}, "labels": [{"name": "ship"}]} + self.run = {"id": 444, "workflow_id": 99, "run_attempt": 1, "repository": repository, + "path": ".github/workflows/ci.yml", "event": "workflow_dispatch", + "head_sha": HEAD, "head_branch": "my-branch", "head_repository": repository, + "pull_requests": [{"number": 42, "head": dict(self.pr["head"]), "base": dict(self.pr["base"])}], + "run_started_at": datetime.now(timezone.utc).isoformat(), + "status": "completed", "conclusion": "failure"} + self.jobs = [{"name": "e2e", "status": "completed", "conclusion": "failure", + "head_sha": HEAD, "run_id": 444, "run_attempt": 1}] + self.prefix = "repos/" + repo + self.requests = [] + self.on_jobs = lambda: None + + def json(self, method, path): + assert method == "api" + self.requests.append(path) + if path == "user": + return {"login": "owner"} + if path == self.prefix + "/pulls/42": + return self.pr + if path == f"{self.prefix}/actions/runs/{self.run['id']}": + return self.run + if path == f"{self.prefix}/actions/runs/{self.run['id']}/attempts/1/jobs?per_page=100": + self.on_jobs() + return {"total_count": len(self.jobs), "jobs": self.jobs} + raise AssertionError(path) + + +@pytest.fixture +def elected(merge_dispatch, monkeypatch, tmp_path, capsys): + f = merge_dispatch + queue = f.profile["queues"][0] + queue["item_blockers"] = True + path = tmp_path / "pipelinectl.json" + repo = f.profile["repository"] + path.write_text(json.dumps({"repository": repo, "trusted_account": "owner", + "health_command": ["health"], "required_checks": ["e2e"], + "fallback_handoff": "target-v1"}), encoding="utf-8") + queue["execution"].update(merge_confirmation="bounded-v1", command=["pipeline", "--config", str(path), "next", "merge"]) + live = health("merge") + handoff = fallback_handoff.create(pp.load_config(str(path)), live, "merge", live["merge_executable"][0], "audit") + monkeypatch.setattr(pi, "_tool_preflight", lambda *_: handoff) + route = dispatch(f) + assert route["action"] == "prompt", route + gate = route["gate_command"][-1] + monkeypatch.setenv("PP_TASK_ID", str(f.task.id)) + monkeypatch.setenv("PP_TASK_STARTED_AT", f.task.started_at.isoformat()) + gh = Actions(repo) + monkeypatch.setattr(pp, "GitHub", lambda **_: gh) + + def call(verb, attempt=1, rid=444, *, lease_file=gate): + argv = ["pp", "pipelinectl", "merge-ci-wait", verb, "--profile", "example", "--number", "42", + "--head", HEAD, "--run-id", str(rid), "--attempt", str(attempt), "--lease-file", lease_file] + monkeypatch.setattr(sys, "argv", argv) + with pytest.raises(SystemExit) as done: + entrypoint.main() + result = json.loads(capsys.readouterr().out) + assert done.value.code == int(result["state"] == "refused") + assert result["product_mutation_authorized"] is False + return result + + return SimpleNamespace(f=f, gh=gh, repo=repo, target={"number": 42, "head": HEAD}, call=call, gate=gate, + config_path=path) + + +def test_one_shot_survives_unknown_send_and_late_terminal_readback(elected): + e = elected + first = e.call("claim") + assert first["state"] == "claimed" and first["send_allowed"] is True and first["attempt"] == 2 + assert ci.active_wait(e.repo, e.target) == ci.series_wait(e.f.task.series_id, e.repo) + assert ci.defer_time(e.f.task) is None + + assert e.call("observe", 2)["state"] == "unknown" # process died on either side of send + second = e.call("claim", rid=999) + assert (second["state"], second["send_allowed"], second["run_id"]) == ("already_claimed", False, 444) + assert e.call("observe", 2, rid=999)["state"] == "refused" + e.gh.run.update(run_attempt=2, status="in_progress", conclusion=None) + result = e.call("observe", 2) + assert result["state"] == "waiting" + e.f.db.mark_completed(e.f.task.id, "ИТОГ: ПУСТО", verdict="ПУСТО") + due = ci.defer_time(e.f.task) + assert due and time.time() < due.timestamp() <= time.time() + ci.POLL_SECONDS + record = ci.series_wait(e.f.task.series_id, e.repo) + assert ci.observe_run(e.gh, record, now=first["deadline"] + 1)["state"] == "timeout" + e.gh.run.update(status="completed", conclusion="success") + outcome = ci.observe_run(e.gh, record, now=first["deadline"] + 1) + assert outcome["state"] == "success" and ci.save_observation(record, outcome) + assert not ci.save_observation(record, outcome) # stale continuation + assert ci.defer_time(e.f.task) is None and ci.series_wait(e.f.task.series_id, e.repo) is None + assert ci.active_wait(e.repo, e.target) is None + assert e.call("claim")["state"] == "refused" # old task no longer running + + +def test_claim_arms_wake_even_when_github_did_not_acknowledge(elected): + e = elected + assert e.call("claim")["send_allowed"] + e.f.db.mark_completed(e.f.task.id, "ИТОГ: ПУСТО", verdict="ПУСТО") + due = ci.defer_time(e.f.task) + assert due and time.time() < due.timestamp() <= time.time() + ci.POLL_SECONDS + e.f.db.set_setting(ci._receipt_key(e.f.task.series_id), "{") + assert ci.defer_time(e.f.task) is None + + +@pytest.mark.parametrize("fault", ["run-sha", "workflow", "branch", "association", "repo", "test", "late", "pause", + "config", "incarnation", "lease"]) +def test_wrong_identity_or_lost_admission_is_never_claimed(elected, fault, monkeypatch): + e = elected + if fault == "run-sha": + e.gh.run["head_sha"] = "f" * 40 + elif fault == "workflow": + e.gh.run["path"] = ".github/workflows/release.yml" + elif fault == "branch": + e.gh.run["head_branch"] = "other" + elif fault == "association": + e.gh.run["pull_requests"] = [] + elif fault == "repo": + e.gh.run["head_repository"] = {"full_name": "other/project"} + elif fault == "test": + e.gh.jobs[0]["name"] = "bench" + elif fault == "late": + e.gh.run["run_attempt"] = 2 + elif fault == "pause": + e.gh.on_jobs = lambda: e.f.db.set_setting("worker_paused", "1") + elif fault == "config": + path = Path(e.f.profile["queues"][0]["execution"]["command"][2]) + data = json.loads(path.read_text(encoding="utf-8")) + data["required_checks"] = ["other-check"] + e.gh.on_jobs = lambda: path.write_text(json.dumps(data), encoding="utf-8") + elif fault == "incarnation": + monkeypatch.setenv("PP_TASK_STARTED_AT", "2000-01-01T00:00:00+00:00") + elif fault == "lease": + token_file = Path(e.gate) + token_file.write_text(token_file.read_text(encoding="ascii") + "x", encoding="ascii") + result = e.call("claim") + assert result["state"] == "refused" and not result["send_allowed"] + assert ci.active_wait(e.repo, e.target) is None + + +def test_concurrent_claims_return_one_send_permission(elected): + e = elected + e.gh.on_jobs = Barrier(2).wait + args = argparse.Namespace(profile="example", operation="claim", number=42, head=HEAD, + run_id=444, attempt=1, lease_file=e.gate) + env = {"PP_TASK_ID": str(e.f.task.id), "PP_TASK_STARTED_AT": e.f.task.started_at.isoformat()} + + def claim(): + try: + return ci._apply(args, env)["state"] + except pp.PipelineError as exc: + assert "concurrently" in str(exc) + return "refused" + + with ThreadPoolExecutor(2) as pool: + results = list(pool.map(lambda _: claim(), [0, 1])) + assert sorted(results) == ["claimed", "refused"] + + +@pytest.mark.parametrize("change", ["closed", "head", "hold", "new-attempt", "failure"]) +def test_restart_of_external_attempt_does_not_resend_or_merge_another_head(elected, change): + e = elected + e.gh.run.update(run_attempt=2, status="in_progress", conclusion=None) + assert e.call("observe", 2)["state"] == "waiting" + assert e.call("claim")["state"] == "already_claimed" + record = ci.active_wait(e.repo, e.target) + if change == "closed": + e.gh.pr["state"] = "closed" + elif change == "head": + e.gh.pr["head"]["sha"] = "f" * 40 + elif change == "hold": + e.gh.pr["labels"].append({"name": "hold"}) + elif change == "new-attempt": + e.gh.run.update(run_attempt=3, status="completed", conclusion="success") + else: + e.gh.run.update(status="completed", conclusion="failure") + expected = {"new-attempt": "attempt_changed", "failure": "failed"}.get(change, "superseded") + e.gh.requests.clear() + outcome = ci.observe_run(e.gh, record) + assert len(e.gh.requests) == (1 if expected == "superseded" else 2) + assert outcome["state"] == expected and ci.save_observation(record, outcome) + assert ci.active_wait(e.repo, dict(e.target, head="f" * 40)) is None + assert ci.defer_time(e.f.task) is None + +@pytest.mark.parametrize(("options", "expected"), [ + ([], "pipelinectl.json"), (["--config", "custom.json"], "custom.json"), (["--config=project"], "project"), + (["--config", "a", "--config=b"], None), (["--config"], None), (["--config="], None), +]) +def test_adapter_configuration_matches_the_project_cli(options, expected): + cmd = ["pipelinectl", *options, "next", "merge"] + if expected is None: + with pytest.raises(pp.PipelineError): + ci.adapter_config_path(cmd) + else: + assert ci.adapter_config_path(cmd) == expected + + +@pytest.mark.parametrize("after_election", ["success", "in_progress", "another_attempt"]) +def test_external_attempt_needs_a_fresh_signed_readback_and_keeps_its_deadline(elected, monkeypatch, after_election): + from promptpilot import merge_checkpoint + + e = elected + e.gh.run.update(status="in_progress", conclusion=None) + first = e.call("observe") + e.gh.run.update(run_attempt=2) + assert e.call("observe")["state"] == "attempt_changed" + assert e.call("observe", 2)["state"] == "refused" + assert e.call("claim", rid=999)["state"] == "already_claimed" + monkeypatch.setattr(pp, "run_health", lambda *_, **__: health("merge")) + monkeypatch.setattr(pp, "pending_merge_intents", lambda *_: []) + monkeypatch.setattr(pp, "stable_timeline", lambda *_: {"edges": []}) + handoff = ci.diagnose(e.gh, pp.load_config(str(e.config_path)), str(e.config_path), 42, HEAD) + assert handoff["ci_current_attempt"] == 2 + lease = fallback_handoff.validate(handoff, "merge") + assert lease["ci_attempt_readback"] == {"run_id": 444, "previous_attempt": 1, "attempt": 2} + token = handoff["handoff"]["lease"] + gate_file = pi._lease_argument(e.f.task, token, "gate")[-1] + merge_checkpoint.bind_election(e.f.task, token) + if after_election == "another_attempt": + e.gh.run.update(run_attempt=3) + assert e.call("observe", 3, lease_file=gate_file)["state"] == "refused" + assert e.call("observe", 2, lease_file=gate_file)["state"] == "refused" + return + if after_election == "success": + e.gh.run.update(status="completed", conclusion="success") + result = e.call("observe", 2, lease_file=gate_file) + assert not result["send_allowed"] and result["deadline"] == first["deadline"] + assert e.call("claim", rid=999, lease_file=gate_file)["state"] == "already_claimed" + e.f.db.mark_completed(e.f.task.id, "ИТОГ: ПУСТО", verdict="ПУСТО") + when = ci.defer_time(e.f.task).timestamp() + if after_election == "success": + assert result["state"] == "success" and result["reelect"] is True + assert time.time() < when <= time.time() + 5 + else: + assert result["state"] == "waiting" and result["reelect"] is False + assert time.time() + 5 < when <= time.time() + ci.POLL_SECONDS + + +@pytest.mark.parametrize("scenario", ["legacy", "ready-owner", "cleanup", "first-changed", "hold", "typed", + "config", "green", "excluded", "pending"]) +def test_elects_exact_ci_diagnosis_with_the_normal_signed_gate_only(elected, monkeypatch, capsys, scenario): + from promptpilot import review_routing_adapter + + e = elected + if scenario == "pending": + e.gh.run.update(status="in_progress", conclusion=None) + state = e.call("observe")["state"] + assert state == ("waiting" if scenario == "pending" else "failed") + source = health("integration-merge-ready" if scenario == "ready-owner" else "merge") + if scenario == "first-changed": + source["merge_executable"].insert(0, dict(source["merge_executable"][0], number=100)) + if scenario == "hold": + e.gh.pr["labels"].append({"name": "manual"}) + if scenario == "green": + e.gh.run.update(conclusion="success") + if scenario == "excluded": + monkeypatch.setenv("PP_PIPELINE_EXCLUDED_NUMBERS", "[42]") + + def run_health(config, *, config_path): + assert config_path == str(e.config_path) + if scenario == "config": + config["base_branch"] = "other" + return source + + monkeypatch.setattr(pp, "pending_merge_intents", lambda *_: [{"number": 9}] if scenario == "cleanup" else []) + monkeypatch.setattr(pp, "run_health", run_health) + monkeypatch.setattr(review_routing_adapter, "journal_directory", lambda *_: e.config_path.parent / "routing") + marker = {"node": {"__typename": "IssueComment", "author": {"login": "owner"}, + "body": ""}} + monkeypatch.setattr(pp, "stable_timeline", lambda *_: {"edges": [marker] if scenario == "typed" else []}) + argv = ["pp", "pipelinectl", "--config", str(e.config_path), "merge-ci-diagnose", "--number", "42", "--head", HEAD] + monkeypatch.setattr(sys, "argv", argv) + with pytest.raises(SystemExit) as done: + entrypoint.main() + assert done.value.code == 0 + result = json.loads(capsys.readouterr().out) + if scenario in {"legacy", "ready-owner"}: + lease = fallback_handoff.validate(result, "merge") + assert lease["repository"] == e.repo and lease["target"] == fallback_handoff.identity(source["merge_executable"][0]) + assert not lease.get("target_reservation") + else: + expected = {"hold": "superseded", "green": "success"}.get(scenario, "unavailable") + assert result["action"] == "wait" and result["state"] == expected and "handoff" not in result