Skip to content

armgit / Cairn

Public Imported from GitHub
0

Cairn is a general-purpose AI state-space search engine, validated first on autonomous penetration testing. Sometimes misspelled as Carin.

feat: run worker health checks in code instead of in-container curl

leixiao668d339d91ec
diff --git a/cairn/src/cairn/dispatcher/runtime/backend.py b/cairn/src/cairn/dispatcher/runtime/backend.py
index d889984..832bbc7 100644
--- a/cairn/src/cairn/dispatcher/runtime/backend.py
+++ b/cairn/src/cairn/dispatcher/runtime/backend.py
@@ -30,10 +30,6 @@ class ExecutionBackend(Protocol):
def write_text_file(self, container_name: str, path: str, content: str) -> None: ...
- def create_startup_container(self) -> str: ...
-
- def remove_container(self, name: str, *, force: bool = True) -> None: ...
-
def needs_completed_cleanup(self, project_id: str) -> bool: ...
def needs_stopped_cleanup(self, project_id: str) -> bool: ...
diff --git a/cairn/src/cairn/dispatcher/runtime/containers.py b/cairn/src/cairn/dispatcher/runtime/containers.py
index f96ca5e..d6bda8a 100644
--- a/cairn/src/cairn/dispatcher/runtime/containers.py
+++ b/cairn/src/cairn/dispatcher/runtime/containers.py
@@ -5,7 +5,6 @@ import logging
from pathlib import PurePosixPath
import tarfile
import threading
-import uuid
import docker
from docker.errors import APIError, DockerException, NotFound
@@ -19,7 +18,6 @@ LOG = logging.getLogger(__name__)
class ContainerManager:
_PREFIX = "cairn-dispatch-"
- _STARTUP_PREFIX = "cairn-startup-healthcheck-"
def __init__(self, config: ContainerConfig):
self._config = config
@@ -81,22 +79,6 @@ class ContainerManager:
self._ensure_running_locks[name] = lock
return lock
- def create_startup_container(self) -> str:
- name = f"{self._STARTUP_PREFIX}{uuid.uuid4().hex[:12]}"
- LOG.debug("creating startup healthcheck container container=%s image=%s", name, self._config.image)
- try:
- self._client.containers.run(
- self._config.image,
- ["sleep", "infinity"],
- detach=True,
- name=name,
- network_mode=self._config.network_mode,
- cap_add=self._config.cap_add or None,
- )
- except DockerException as exc:
- raise RuntimeError(f"failed to create startup container {name}: {exc}") from exc
- return name
-
def inspect_state(self, name: str) -> str | None:
container = self._get_container(name)
if container is None:
@@ -222,17 +204,6 @@ class ContainerManager:
if not ok:
raise RuntimeError(f"failed to write container file {path}")
- def remove_container(self, name: str, *, force: bool = True) -> None:
- container = self._get_container(name)
- if container is None:
- return
- try:
- container.remove(force=force)
- except NotFound:
- return
- except DockerException as exc:
- LOG.warning("failed to remove container=%s error=%s", name, exc)
-
def _start_existing(self, name: str) -> None:
LOG.debug("starting container=%s", name)
container = self._require_container(name)
diff --git a/cairn/src/cairn/dispatcher/runtime/local_backend.py b/cairn/src/cairn/dispatcher/runtime/local_backend.py
index a25f9af..ba4eb08 100644
--- a/cairn/src/cairn/dispatcher/runtime/local_backend.py
+++ b/cairn/src/cairn/dispatcher/runtime/local_backend.py
@@ -62,12 +62,6 @@ class LocalBackend:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
- def create_startup_container(self) -> str:
- raise RuntimeError("startup healthcheck container is not used in local execution mode")
-
- def remove_container(self, name: str, *, force: bool = True) -> None:
- return None
-
def needs_completed_cleanup(self, project_id: str) -> bool:
return self._config.completed_action == "remove" and self._project_dir(project_id).exists()
diff --git a/cairn/src/cairn/dispatcher/runtime/startup_healthcheck.py b/cairn/src/cairn/dispatcher/runtime/startup_healthcheck.py
index 633e5e0..da709bc 100644
--- a/cairn/src/cairn/dispatcher/runtime/startup_healthcheck.py
+++ b/cairn/src/cairn/dispatcher/runtime/startup_healthcheck.py
@@ -1,77 +1,47 @@
from __future__ import annotations
import logging
+import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from cairn.dispatcher.config import DispatchConfig, WorkerConfig
-from cairn.dispatcher.runtime.containers import ContainerManager
-from cairn.dispatcher.tasks.common import run_healthcheck
from cairn.dispatcher.workers.registry import get_driver
LOG = logging.getLogger("runtime.startup")
-STARTUP_HEALTHCHECK_PREVIEW_LIMIT = 50
+DETAIL_PREVIEW_LIMIT = 60
@dataclass(slots=True)
class StartupHealthcheckResult:
worker_name: str
ok: bool
- returncode: int
+ status: int | None
duration_ms: int
- http_status: str | None
- response_preview: str
- stderr_preview: str
- command: str
+ detail: str
+ endpoint: str
def run_startup_healthchecks(
config: DispatchConfig,
- container_manager: ContainerManager,
*,
show_commands: bool = False,
) -> list[StartupHealthcheckResult]:
- container_name = container_manager.create_startup_container()
workers = list(config.workers)
parallelism = max(1, min(len(workers), config.runtime.max_workers, 8))
- LOG.info(
- "[*] Startup healthcheck: workers=%s parallelism=%s",
- len(workers),
- parallelism,
- )
- try:
- with ThreadPoolExecutor(max_workers=parallelism) as executor:
- future_map = {
- executor.submit(
- _run_worker_healthcheck,
- container_manager,
- container_name,
- worker,
- config.runtime.healthcheck_timeout,
- ): worker.name
- for worker in workers
- }
- results: list[StartupHealthcheckResult] = []
- for future in as_completed(future_map):
- worker_name = future_map[future]
- try:
- result = future.result()
- except Exception:
- LOG.exception("startup healthcheck crashed worker=%s", worker_name)
- result = StartupHealthcheckResult(
- worker_name=worker_name,
- ok=False,
- returncode=1,
- duration_ms=0,
- http_status=None,
- response_preview="",
- stderr_preview="startup healthcheck crashed",
- command="-",
- )
- results.append(result)
- finally:
- LOG.debug("removing startup healthcheck container container=%s", container_name)
- container_manager.remove_container(container_name, force=True)
+ LOG.info("[*] Startup healthcheck: workers=%s parallelism=%s", len(workers), parallelism)
+ with ThreadPoolExecutor(max_workers=parallelism) as executor:
+ future_map = {executor.submit(_check_worker, config, worker): worker.name for worker in workers}
+ results: list[StartupHealthcheckResult] = []
+ for future in as_completed(future_map):
+ worker_name = future_map[future]
+ try:
+ results.append(future.result())
+ except Exception:
+ LOG.exception("startup healthcheck crashed worker=%s", worker_name)
+ results.append(
+ StartupHealthcheckResult(worker_name, False, None, 0, "startup healthcheck crashed", "-")
+ )
results.sort(key=lambda result: result.worker_name)
_log_report(results, show_commands=show_commands)
@@ -82,40 +52,22 @@ def format_failure_summary(results: list[StartupHealthcheckResult]) -> str:
failed = [result for result in results if not result.ok]
if not failed:
return "startup healthchecks failed for all workers"
- details = []
- for result in failed:
- preview = result.response_preview or result.stderr_preview or "-"
- details.append(
- f"{result.worker_name}(http={result.http_status or '-'}, code={result.returncode}, preview={preview})"
- )
+ details = [f"{result.worker_name}(http={result.status or '-'}, detail={result.detail or '-'})" for result in failed]
return f"startup healthchecks failed for all workers: {', '.join(details)}"
-def _run_worker_healthcheck(
- container_manager: ContainerManager,
- container_name: str,
- worker: WorkerConfig,
- timeout_seconds: int,
-) -> StartupHealthcheckResult:
- driver = get_driver(worker.type)
- healthcheck = run_healthcheck(
- container_manager,
- container_name,
- worker,
- driver.build_startup_healthcheck(worker),
- timeout_seconds=timeout_seconds,
- )
- result = healthcheck.result
- http_status, response_preview = _parse_stdout(result.stdout)
+def _check_worker(config: DispatchConfig, worker: WorkerConfig) -> StartupHealthcheckResult:
+ driver = get_driver(worker.type, config.runtime.execution)
+ started = time.perf_counter()
+ result = driver.check_health(worker, timeout=config.runtime.healthcheck_timeout)
+ duration_ms = int((time.perf_counter() - started) * 1000)
return StartupHealthcheckResult(
worker_name=worker.name,
- ok=result.returncode == 0,
- returncode=result.returncode,
- duration_ms=healthcheck.duration_ms,
- http_status=http_status,
- response_preview=response_preview,
- stderr_preview=_preview(result.stderr),
- command=driver.describe_startup_healthcheck(worker),
+ ok=result.ok,
+ status=result.status,
+ duration_ms=duration_ms,
+ detail=_preview(result.detail),
+ endpoint=driver.describe_health(worker),
)
@@ -125,52 +77,35 @@ def _log_report(results: list[StartupHealthcheckResult], *, show_commands: bool)
return
worker_width = max(len("WORKER"), *(len(result.worker_name) for result in results))
lines = ["[=] Startup healthcheck results"]
- header = f"{'CHK':<5} {'WORKER':<{worker_width}} {'HTTP':<6} {'CODE':<6} {'TIME_S':>8} PREVIEW"
- lines.append(header)
- lines.append(f"{'-' * 5} {'-' * worker_width} {'-' * 6} {'-' * 6} {'-' * 8} {'-' * 50}")
+ lines.append(f"{'CHK':<5} {'WORKER':<{worker_width}} {'HTTP':<6} {'TIME_S':>8} DETAIL")
+ lines.append(f"{'-' * 5} {'-' * worker_width} {'-' * 6} {'-' * 8} {'-' * 60}")
healthy_count = 0
for result in results:
if result.ok:
healthy_count += 1
marker = "[+]" if result.ok else "[-]"
- preview = result.response_preview or result.stderr_preview or "-"
duration_seconds = f"{result.duration_ms / 1000:.2f}"
lines.append(
f"{marker:<5} "
f"{result.worker_name:<{worker_width}} "
- f"{(result.http_status or '-'): <6} "
- f"{result.returncode:<6} "
+ f"{(str(result.status) if result.status is not None else '-'):<6} "
f"{duration_seconds:>8} "
- f"{preview}"
+ f"{result.detail or '-'}"
)
lines.append(
f"[=] Summary: total={len(results)} healthy={healthy_count} unhealthy={len(results) - healthy_count}"
)
if show_commands:
lines.append("")
- lines.append("[=] Startup healthcheck commands")
+ lines.append("[=] Startup healthcheck endpoints")
for result in results:
- lines.append(f"- {result.worker_name}")
- lines.append(f" {result.command}")
+ lines.append(f"- {result.worker_name}: {result.endpoint}")
lines.append("")
LOG.info("\n%s\n", "\n".join(lines))
-def _parse_stdout(stdout: str) -> tuple[str | None, str]:
- lines = stdout.splitlines()
- http_status: str | None = None
- body_lines: list[str] = []
- for line in lines:
- stripped = line.strip()
- if http_status is None and stripped.startswith("http_status="):
- http_status = stripped.partition("=")[2] or None
- continue
- body_lines.append(line)
- return http_status, _preview("\n".join(body_lines))
-
-
def _preview(text: str) -> str:
compact = " ".join(text.split())
- if len(compact) <= STARTUP_HEALTHCHECK_PREVIEW_LIMIT:
+ if len(compact) <= DETAIL_PREVIEW_LIMIT:
return compact
- return compact[:STARTUP_HEALTHCHECK_PREVIEW_LIMIT] + "..."
+ return compact[:DETAIL_PREVIEW_LIMIT] + "..."
diff --git a/cairn/src/cairn/dispatcher/scheduler/loop.py b/cairn/src/cairn/dispatcher/scheduler/loop.py
index 3d33066..41d207d 100644
--- a/cairn/src/cairn/dispatcher/scheduler/loop.py
+++ b/cairn/src/cairn/dispatcher/scheduler/loop.py
@@ -929,7 +929,7 @@ class DispatcherLoop:
)
def _run_startup_healthchecks(self, *, show_commands: bool) -> None:
- results = run_startup_healthchecks(self.config, self.container_manager, show_commands=show_commands)
+ results = run_startup_healthchecks(self.config, show_commands=show_commands)
if any(result.ok for result in results):
return
raise RuntimeError(format_failure_summary(results))
diff --git a/cairn/src/cairn/dispatcher/tasks/bootstrap.py b/cairn/src/cairn/dispatcher/tasks/bootstrap.py
index cc6b060..eef1d7a 100644
--- a/cairn/src/cairn/dispatcher/tasks/bootstrap.py
+++ b/cairn/src/cairn/dispatcher/tasks/bootstrap.py
@@ -20,7 +20,6 @@ from cairn.dispatcher.tasks.common import (
did_timeout,
project_allows_conclude_fallback,
preview,
- run_healthcheck,
run_worker_process,
task_healthcheck_enabled,
write_conclude_result,
@@ -51,29 +50,20 @@ def run_bootstrap_task(
if task_healthcheck_enabled(config):
LOG.info(
- "starting container exec project=%s intent=%s worker=%s phase=bootstrap_healthcheck timeout=%ss",
+ "checking worker health project=%s intent=%s worker=%s timeout=%ss",
project.project.id,
intent.id,
worker.name,
healthcheck_timeout,
)
- healthcheck = run_healthcheck(
- container_manager,
- container_name,
- worker,
- driver.build_healthcheck(worker),
- timeout_seconds=healthcheck_timeout,
- lease=lease,
- cancellation=cancellation,
- )
- cancelled = cancel_reason(healthcheck.result, cancellation)
- if cancelled is not None:
+ health = driver.check_health(worker, timeout=healthcheck_timeout)
+ if cancellation.is_cancelled:
LOG.info(
"bootstrap cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
project.project.id,
intent.id,
worker.name,
- cancelled,
+ cancellation.reason,
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "cancelled"
@@ -87,14 +77,14 @@ def run_bootstrap_task(
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "failed"
- if healthcheck.result.returncode != 0:
+ if not health.ok:
LOG.warning(
- "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
+ "worker unhealthy project=%s intent=%s worker=%s status=%s detail=%s",
project.project.id,
intent.id,
worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ health.status,
+ health.detail,
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "unhealthy"
diff --git a/cairn/src/cairn/dispatcher/tasks/common.py b/cairn/src/cairn/dispatcher/tasks/common.py
index c8f4571..d2c8ed2 100644
--- a/cairn/src/cairn/dispatcher/tasks/common.py
+++ b/cairn/src/cairn/dispatcher/tasks/common.py
@@ -12,19 +12,12 @@ from cairn.dispatcher.runtime.containers import ContainerManager
from cairn.dispatcher.runtime.heartbeat import HeartbeatLease
from cairn.dispatcher.runtime.process import ProcessResult
-HEALTHCHECK_COMMUNICATE_GRACE_SECONDS = 10
PROCESS_COMMUNICATE_GRACE_SECONDS = 15
LOG_PREVIEW_LIMIT = 1200
GRAPH_SNAPSHOT_ROOT = "/tmp/cairn-prompts"
LOG = logging.getLogger(__name__)
-@dataclass(slots=True)
-class HealthcheckRun:
- result: ProcessResult
- duration_ms: int
-
-
@dataclass(slots=True)
class ConcludeWriteResult:
status: str
@@ -77,39 +70,6 @@ def write_graph_snapshot_reference(
)
-def run_healthcheck(
- container_manager: ContainerManager,
- container_name: str,
- worker: WorkerConfig,
- command: list[str],
- *,
- timeout_seconds: int,
- lease: HeartbeatLease | None = None,
- cancellation: TaskCancellation | None = None,
-) -> HealthcheckRun:
- process = container_manager.build_exec_process(
- container_name,
- dict(worker.env),
- command,
- timeout_seconds=timeout_seconds,
- )
- process.start()
- if lease is not None:
- lease.attach_process(process)
- if cancellation is not None:
- cancellation.attach_process(process)
- started = time.perf_counter()
- try:
- result = process.communicate(timeout=communicate_timeout(timeout_seconds, HEALTHCHECK_COMMUNICATE_GRACE_SECONDS))
- finally:
- if lease is not None:
- lease.attach_process(None)
- if cancellation is not None:
- cancellation.attach_process(None)
- duration_ms = int((time.perf_counter() - started) * 1000)
- return HealthcheckRun(result=result, duration_ms=duration_ms)
-
-
def run_worker_process(
container_manager: ContainerManager,
container_name: str,
diff --git a/cairn/src/cairn/dispatcher/tasks/explore.py b/cairn/src/cairn/dispatcher/tasks/explore.py
index e065c79..eea5b19 100644
--- a/cairn/src/cairn/dispatcher/tasks/explore.py
+++ b/cairn/src/cairn/dispatcher/tasks/explore.py
@@ -16,7 +16,6 @@ from cairn.dispatcher.tasks.common import (
did_timeout,
project_allows_conclude_fallback,
preview,
- run_healthcheck,
run_worker_process,
task_healthcheck_enabled,
write_conclude_result,
@@ -48,29 +47,20 @@ def run_explore_task(
if task_healthcheck_enabled(config):
LOG.info(
- "starting container exec project=%s intent=%s worker=%s phase=explore_healthcheck timeout=%ss",
+ "checking worker health project=%s intent=%s worker=%s timeout=%ss",
project.project.id,
intent.id,
worker.name,
healthcheck_timeout,
)
- healthcheck = run_healthcheck(
- container_manager,
- container_name,
- worker,
- driver.build_healthcheck(worker),
- timeout_seconds=healthcheck_timeout,
- lease=lease,
- cancellation=cancellation,
- )
- cancelled = cancel_reason(healthcheck.result, cancellation)
- if cancelled is not None:
+ health = driver.check_health(worker, timeout=healthcheck_timeout)
+ if cancellation.is_cancelled:
LOG.info(
"explore cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
project.project.id,
intent.id,
worker.name,
- cancelled,
+ cancellation.reason,
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "cancelled"
@@ -84,14 +74,14 @@ def run_explore_task(
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "failed"
- if healthcheck.result.returncode != 0:
+ if not health.ok:
LOG.warning(
- "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
+ "worker unhealthy project=%s intent=%s worker=%s status=%s detail=%s",
project.project.id,
intent.id,
worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ health.status,
+ health.detail,
)
best_effort_release(client, project.project.id, intent.id, worker.name)
return "unhealthy"
diff --git a/cairn/src/cairn/dispatcher/tasks/reason.py b/cairn/src/cairn/dispatcher/tasks/reason.py
index 2e14442..98d4c39 100644
--- a/cairn/src/cairn/dispatcher/tasks/reason.py
+++ b/cairn/src/cairn/dispatcher/tasks/reason.py
@@ -20,7 +20,6 @@ from cairn.dispatcher.tasks.common import (
cancel_reason,
did_timeout,
preview,
- run_healthcheck,
run_worker_process,
task_healthcheck_enabled,
write_graph_snapshot_reference,
@@ -50,27 +49,18 @@ def run_reason_task(
if task_healthcheck_enabled(config):
LOG.info(
- "starting container exec project=%s worker=%s phase=reason_healthcheck timeout=%ss",
+ "checking worker health project=%s worker=%s timeout=%ss",
project.project.id,
worker.name,
healthcheck_timeout,
)
- healthcheck = run_healthcheck(
- container_manager,
- container_name,
- worker,
- driver.build_healthcheck(worker),
- timeout_seconds=healthcheck_timeout,
- lease=lease,
- cancellation=cancellation,
- )
- cancelled = cancel_reason(healthcheck.result, cancellation)
- if cancelled is not None:
+ health = driver.check_health(worker, timeout=healthcheck_timeout)
+ if cancellation.is_cancelled:
LOG.info(
"reason cancelled during healthcheck project=%s worker=%s reason=%s",
project.project.id,
worker.name,
- cancelled,
+ cancellation.reason,
)
return "cancelled"
if lease.failure is not None:
@@ -81,13 +71,13 @@ def run_reason_task(
lease.failure.status_code,
)
return "failed"
- if healthcheck.result.returncode != 0:
+ if not health.ok:
LOG.warning(
- "worker unhealthy project=%s worker=%s healthcheck_ms=%s stderr=%s",
+ "worker unhealthy project=%s worker=%s status=%s detail=%s",
project.project.id,
worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ health.status,
+ health.detail,
)
return "unhealthy"
open_intents = [
diff --git a/cairn/src/cairn/dispatcher/workers/adapters/_curl.py b/cairn/src/cairn/dispatcher/workers/adapters/_curl.py
deleted file mode 100644
index 8f2933f..0000000
--- a/cairn/src/cairn/dispatcher/workers/adapters/_curl.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from __future__ import annotations
-
-import shlex
-from dataclasses import dataclass
-
-
-_VERBOSE_CURL_SCRIPT = """
-url="$1"
-payload="$2"
-shift 2
-
-body_file="$(mktemp)"
-cleanup() {
- rm -f "$body_file"
-}
-trap cleanup EXIT
-
-curl_rc=0
-http_status="$(
- curl -sS -o "$body_file" -w '%{http_code}' "$url" "$@" -d "$payload"
-)" || curl_rc=$?
-
-printf 'http_status=%s\\n' "$http_status"
-if [ -s "$body_file" ]; then
- cat "$body_file"
-fi
-
-if [ "$curl_rc" -ne 0 ]; then
- exit "$curl_rc"
-fi
-
-case "$http_status" in
- 2??) exit 0 ;;
- *) exit 1 ;;
-esac
-""".strip()
-
-
-def build_verbose_curl_healthcheck(url: str, *, headers: list[str], payload: str) -> list[str]:
- return ["/bin/sh", "-lc", _VERBOSE_CURL_SCRIPT, "--", url, payload, *headers]
-
-
-@dataclass(frozen=True, slots=True)
-class ShellArgument:
- text: str
- expand_env: bool = False
-
-
-def expand_env(text: str) -> ShellArgument:
- return ShellArgument(text=text, expand_env=True)
-
-
-def render_curl_command(url: str, *, headers: list[str | ShellArgument], payload: str) -> str:
- parts = ["curl", "-sS", url, *headers, "-d", payload]
- return " ".join(_render_shell_argument(part) for part in parts)
-
-
-def _render_shell_argument(part: str | ShellArgument) -> str:
- if isinstance(part, ShellArgument):
- if part.expand_env:
- return _double_quote_with_env_expansion(part.text)
- return shlex.quote(part.text)
- return shlex.quote(part)
-
-
-def _double_quote_with_env_expansion(text: str) -> str:
- escaped = text.replace("\\", "\\\\").replace('"', '\\"').replace("`", "\\`")
- return f'"{escaped}"'
diff --git a/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py b/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py
index 13495da..6b84f93 100644
--- a/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py
+++ b/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py
@@ -1,8 +1,8 @@
from __future__ import annotations
from cairn.dispatcher.config import WorkerConfig
-from cairn.dispatcher.workers.adapters._curl import build_verbose_curl_healthcheck, expand_env, render_curl_command
from cairn.dispatcher.workers.base import DriverResult, SeedSessionDriver
+from cairn.dispatcher.workers.health import HealthResult, http_ping, proxies_from_env
ANTHROPIC_VERSION = "2023-06-01"
@@ -14,66 +14,26 @@ class ClaudeCodeDriver(SeedSessionDriver):
def local_binary(self) -> str | None:
return "claude"
- def build_healthcheck(self, worker: WorkerConfig) -> list[str]:
+ def check_health(self, worker: WorkerConfig, *, timeout: float) -> HealthResult:
env = worker.env
- return [
- "curl",
- "-sS",
- "--fail",
- "-o",
- "/dev/null",
- f"{env['ANTHROPIC_BASE_URL']}/v1/messages",
- "-H",
- f"Authorization: Bearer {env['ANTHROPIC_AUTH_TOKEN']}",
- "-H",
- f"anthropic-version: {ANTHROPIC_VERSION}",
- "-H",
- "content-type: application/json",
- "-d",
- (
- '{"model":"'
- + env["ANTHROPIC_MODEL"]
- + '","max_tokens":10,"messages":[{"role":"user","content":"ping"}]}'
- ),
- ]
-
- def build_startup_healthcheck(self, worker: WorkerConfig) -> list[str]:
- env = worker.env
- return build_verbose_curl_healthcheck(
+ return http_ping(
f"{env['ANTHROPIC_BASE_URL']}/v1/messages",
- headers=[
- "-H",
- f"Authorization: Bearer {env['ANTHROPIC_AUTH_TOKEN']}",
- "-H",
- f"anthropic-version: {ANTHROPIC_VERSION}",
- "-H",
- "content-type: application/json",
- ],
- payload=(
- '{"model":"'
- + env["ANTHROPIC_MODEL"]
- + '","max_tokens":10,"messages":[{"role":"user","content":"ping"}]}'
- ),
+ headers={
+ "Authorization": f"Bearer {env['ANTHROPIC_AUTH_TOKEN']}",
+ "anthropic-version": ANTHROPIC_VERSION,
+ "content-type": "application/json",
+ },
+ json_body={
+ "model": env["ANTHROPIC_MODEL"],
+ "max_tokens": 10,
+ "messages": [{"role": "user", "content": "ping"}],
+ },
+ timeout=timeout,
+ proxies=proxies_from_env(env),
)
- def describe_startup_healthcheck(self, worker: WorkerConfig) -> str:
- env = worker.env
- return render_curl_command(
- f"{env['ANTHROPIC_BASE_URL']}/v1/messages",
- headers=[
- "-H",
- expand_env("Authorization: Bearer $ANTHROPIC_AUTH_TOKEN"),
- "-H",
- f"anthropic-version: {ANTHROPIC_VERSION}",
- "-H",
- "content-type: application/json",
- ],
- payload=(
- '{"model":"'
- + env["ANTHROPIC_MODEL"]
- + '","max_tokens":10,"messages":[{"role":"user","content":"ping"}]}'
- ),
- )
+ def describe_health(self, worker: WorkerConfig) -> str:
+ return f"POST {worker.env['ANTHROPIC_BASE_URL']}/v1/messages (model={worker.env['ANTHROPIC_MODEL']})"
def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:
assert session is not None
diff --git a/cairn/src/cairn/dispatcher/workers/adapters/codex.py b/cairn/src/cairn/dispatcher/workers/adapters/codex.py
index a09d5f2..dd4cf4e 100644
--- a/cairn/src/cairn/dispatcher/workers/adapters/codex.py
+++ b/cairn/src/cairn/dispatcher/workers/adapters/codex.py
@@ -1,8 +1,8 @@
from __future__ import annotations
from cairn.dispatcher.config import WorkerConfig
-from cairn.dispatcher.workers.adapters._curl import build_verbose_curl_healthcheck, expand_env, render_curl_command
from cairn.dispatcher.workers.base import DriverResult, RegexSessionDriver
+from cairn.dispatcher.workers.health import HealthResult, http_ping, proxies_from_env
class CodexDriver(RegexSessionDriver):
@@ -14,37 +14,25 @@ class CodexDriver(RegexSessionDriver):
def local_binary(self) -> str | None:
return "codex"
- def build_healthcheck(self, worker: WorkerConfig) -> list[str]:
- return [
- "curl",
- "-sS",
- "--fail",
- "-o",
- "/dev/null",
- self._healthcheck_url(worker),
- *self._healthcheck_headers(worker),
- "-d",
- self._healthcheck_payload(worker),
- ]
-
- def build_startup_healthcheck(self, worker: WorkerConfig) -> list[str]:
- return build_verbose_curl_healthcheck(
- self._healthcheck_url(worker),
- headers=self._healthcheck_headers(worker),
- payload=self._healthcheck_payload(worker),
+ def check_health(self, worker: WorkerConfig, *, timeout: float) -> HealthResult:
+ env = worker.env
+ return http_ping(
+ f"{env['CODEX_BASE_URL']}/responses",
+ headers={
+ "Authorization": f"Bearer {env['OPENAI_API_KEY']}",
+ "content-type": "application/json",
+ },
+ json_body={
+ "model": env["CODEX_MODEL"],
+ "input": [{"role": "user", "content": "ping"}],
+ "stream": False,
+ },
+ timeout=timeout,
+ proxies=proxies_from_env(env),
)
- def describe_startup_healthcheck(self, worker: WorkerConfig) -> str:
- return render_curl_command(
- self._healthcheck_url(worker),
- headers=[
- "-H",
- expand_env("Authorization: Bearer $OPENAI_API_KEY"),
- "-H",
- "content-type: application/json",
- ],
- payload=self._healthcheck_payload(worker),
- )
+ def describe_health(self, worker: WorkerConfig) -> str:
+ return f"POST {worker.env['CODEX_BASE_URL']}/responses (model={worker.env['CODEX_MODEL']})"
def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:
if self.local:
@@ -117,25 +105,3 @@ class CodexDriver(RegexSessionDriver):
"--",
prompt,
]
-
- @staticmethod
- def _healthcheck_url(worker: WorkerConfig) -> str:
- return f"{worker.env['CODEX_BASE_URL']}/responses"
-
- @staticmethod
- def _healthcheck_headers(worker: WorkerConfig) -> list[str]:
- return [
- "-H",
- f"Authorization: Bearer {worker.env['OPENAI_API_KEY']}",
- "-H",
- "content-type: application/json",
- ]
-
- @staticmethod
- def _healthcheck_payload(worker: WorkerConfig) -> str:
- return (
- '{"input":[{"content":"ping","role":"user"}],'
- '"model":"'
- + worker.env["CODEX_MODEL"]
- + '","stream":false}'
- )
diff --git a/cairn/src/cairn/dispatcher/workers/adapters/mock.py b/cairn/src/cairn/dispatcher/workers/adapters/mock.py
index 7ca368d..c47a08b 100644
--- a/cairn/src/cairn/dispatcher/workers/adapters/mock.py
+++ b/cairn/src/cairn/dispatcher/workers/adapters/mock.py
@@ -1,9 +1,11 @@
from __future__ import annotations
import json
+import random
from cairn.dispatcher.config import WorkerConfig, resolve_mock_behavior
from cairn.dispatcher.workers.base import DriverResult, SeedSessionDriver
+from cairn.dispatcher.workers.health import HealthResult
_SCRIPT = """
import json,random,sys,time
@@ -131,8 +133,13 @@ class MockDriver(SeedSessionDriver):
behavior = resolve_mock_behavior(worker.name, worker.env)
return ["python3", "-c", _SCRIPT, json.dumps(behavior, ensure_ascii=False), prompt]
- def build_healthcheck(self, worker: WorkerConfig) -> list[str]:
- return self._argv(worker, '{"phase":"healthcheck"}')
+ def check_health(self, worker: WorkerConfig, *, timeout: float) -> HealthResult:
+ outcomes = resolve_mock_behavior(worker.name, worker.env)["healthcheck"]["outcomes"]
+ ok = random.random() < outcomes.get("ok", 0.0)
+ return HealthResult(ok=ok, status=200 if ok else 503, detail="" if ok else "mock healthcheck fail")
+
+ def describe_health(self, worker: WorkerConfig) -> str:
+ return "mock in-process healthcheck"
def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:
return DriverResult(argv=self._argv(worker, prompt), session=session)
diff --git a/cairn/src/cairn/dispatcher/workers/adapters/pi.py b/cairn/src/cairn/dispatcher/workers/adapters/pi.py
index 49f35f6..4d5b574 100644
--- a/cairn/src/cairn/dispatcher/workers/adapters/pi.py
+++ b/cairn/src/cairn/dispatcher/workers/adapters/pi.py
@@ -6,6 +6,7 @@ from typing import Any
from cairn.dispatcher.config import WorkerConfig
from cairn.dispatcher.workers.base import DriverResult, WorkerDriver
+from cairn.dispatcher.workers.health import HealthResult, http_ping, proxies_from_env
class PiDriver(WorkerDriver):
@@ -17,27 +18,42 @@ class PiDriver(WorkerDriver):
def local_binary(self) -> str | None:
return "pi"
- def build_healthcheck(self, worker: WorkerConfig) -> list[str]:
+ def check_health(self, worker: WorkerConfig, *, timeout: float) -> HealthResult:
env = worker.env
- return self._wrap_with_models(
- worker,
- [
- "--provider",
- "cairn",
- "--model",
- env["PI_MODEL"],
- "--mode",
- "json",
- "--session-dir",
- self._session_dir(worker),
- "--no-session",
- "--no-tools",
- "-p",
- "Reply with exactly pong.",
- ],
- enable_tools=False,
+ base = env["PI_BASE_URL"].rstrip("/")
+ model = env["PI_MODEL"]
+ api = env["PI_PROVIDER_API"]
+ proxies = proxies_from_env(env)
+ headers = {"Authorization": f"Bearer {env['PI_API_KEY']}", "content-type": "application/json"}
+ if "anthropic" in api:
+ return http_ping(
+ f"{base}/v1/messages",
+ headers={**headers, "anthropic-version": "2023-06-01"},
+ json_body={"model": model, "max_tokens": 10, "messages": [{"role": "user", "content": "ping"}]},
+ timeout=timeout,
+ proxies=proxies,
+ )
+ if "responses" in api:
+ return http_ping(
+ f"{base}/responses",
+ headers=headers,
+ json_body={"model": model, "input": [{"role": "user", "content": "ping"}], "stream": False},
+ timeout=timeout,
+ proxies=proxies,
+ )
+ # openai-completions and anything else: OpenAI-compatible chat/completions
+ return http_ping(
+ f"{base}/chat/completions",
+ headers=headers,
+ json_body={"model": model, "max_tokens": 10, "messages": [{"role": "user", "content": "ping"}]},
+ timeout=timeout,
+ proxies=proxies,
)
+ def describe_health(self, worker: WorkerConfig) -> str:
+ env = worker.env
+ return f"POST {env['PI_BASE_URL']} (api={env['PI_PROVIDER_API']}, model={env['PI_MODEL']})"
+
def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:
if self.local:
return DriverResult(argv=self._local_argv(worker, prompt, session), session=session)
diff --git a/cairn/src/cairn/dispatcher/workers/base.py b/cairn/src/cairn/dispatcher/workers/base.py
index b000f0b..89df8d9 100644
--- a/cairn/src/cairn/dispatcher/workers/base.py
+++ b/cairn/src/cairn/dispatcher/workers/base.py
@@ -2,11 +2,11 @@ from __future__ import annotations
import abc
import re
-import shlex
import uuid
from dataclasses import dataclass
from cairn.dispatcher.config import WorkerConfig
+from cairn.dispatcher.workers.health import HealthResult
@dataclass(slots=True)
@@ -31,16 +31,14 @@ class WorkerDriver(abc.ABC):
def prepare_session(self) -> str | None:
return None
- def build_startup_healthcheck(self, worker: WorkerConfig) -> list[str]:
- return self.build_healthcheck(worker)
-
- def describe_startup_healthcheck(self, worker: WorkerConfig) -> str:
- return shlex.join(self.build_startup_healthcheck(worker))
-
@abc.abstractmethod
- def build_healthcheck(self, worker: WorkerConfig) -> list[str]:
+ def check_health(self, worker: WorkerConfig, *, timeout: float) -> HealthResult:
+ """Verify this worker's LLM config is usable, in-process (no container, no curl)."""
raise NotImplementedError
+ def describe_health(self, worker: WorkerConfig) -> str:
+ return "in-process API ping"
+
@abc.abstractmethod
def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:
raise NotImplementedError
diff --git a/cairn/src/cairn/dispatcher/workers/health.py b/cairn/src/cairn/dispatcher/workers/health.py
new file mode 100644
index 0000000..54df6a2
--- /dev/null
+++ b/cairn/src/cairn/dispatcher/workers/health.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import requests
+
+DETAIL_LIMIT = 200
+
+
+@dataclass(slots=True)
+class HealthResult:
+ ok: bool
+ status: int | None
+ detail: str
+
+
+def http_ping(
+ url: str,
+ *,
+ headers: dict[str, str],
+ json_body: dict,
+ timeout: float,
+ proxies: dict[str, str] | None = None,
+) -> HealthResult:
+ """POST a tiny request to an LLM endpoint and judge health by the HTTP status.
+
+ Healthy = a 2xx response (endpoint reachable, key accepted, model callable). Any other
+ status, or a connection/timeout error, is unhealthy. The dispatcher runs this in-process
+ instead of shelling a curl into a container.
+ """
+ try:
+ response = requests.post(url, headers=headers, json=json_body, timeout=timeout, proxies=proxies)
+ except requests.RequestException as exc:
+ return HealthResult(ok=False, status=None, detail=_clip(str(exc)))
+ ok = 200 <= response.status_code < 300
+ return HealthResult(ok=ok, status=response.status_code, detail="" if ok else _clip(response.text))
+
+
+def proxies_from_env(env: dict[str, str]) -> dict[str, str] | None:
+ """Build a requests proxies dict from the worker's env so the health check follows the
+ same outbound proxy the worker would use (e.g. a common_env http(s)_proxy)."""
+ all_proxy = env.get("all_proxy") or env.get("ALL_PROXY")
+ http = env.get("http_proxy") or env.get("HTTP_PROXY") or all_proxy
+ https = env.get("https_proxy") or env.get("HTTPS_PROXY") or all_proxy
+ proxies: dict[str, str] = {}
+ if http:
+ proxies["http"] = http
+ if https:
+ proxies["https"] = https
+ return proxies or None
+
+
+def _clip(text: str) -> str:
+ compact = " ".join(text.split())
+ return compact if len(compact) <= DETAIL_LIMIT else compact[:DETAIL_LIMIT] + "..."
diff --git a/cairn/tests/conftest.py b/cairn/tests/conftest.py
index 8d835e4..f56afb1 100644
--- a/cairn/tests/conftest.py
+++ b/cairn/tests/conftest.py
@@ -5,6 +5,7 @@ from dataclasses import dataclass, field
from cairn.dispatcher.config import DispatchConfig
from cairn.dispatcher.protocol.client import ApiResult
from cairn.dispatcher.workers.base import DriverResult
+from cairn.dispatcher.workers.health import HealthResult
from cairn.server.models import Fact, Hint, Intent, ProjectDetail, ProjectMeta
@@ -150,6 +151,7 @@ class FakeDriver:
def __init__(self) -> None:
self.execute_prompts: list[str] = []
self.conclude_prompts: list[str] = []
+ self.health = HealthResult(ok=True, status=200, detail="")
def supports_conclude(self) -> bool:
return True
@@ -157,8 +159,8 @@ class FakeDriver:
def prepare_session(self) -> str:
return "session-001"
- def build_healthcheck(self, _worker) -> list[str]:
- return ["healthcheck"]
+ def check_health(self, _worker, *, timeout: float) -> HealthResult:
+ return self.health
def build_execute(self, _worker, prompt: str, session: str | None) -> DriverResult:
self.execute_prompts.append(prompt)
diff --git a/cairn/tests/test_healthcheck.py b/cairn/tests/test_healthcheck.py
new file mode 100644
index 0000000..8bfcc3e
--- /dev/null
+++ b/cairn/tests/test_healthcheck.py
@@ -0,0 +1,176 @@
+from __future__ import annotations
+
+import requests
+
+from cairn.dispatcher.config import DispatchConfig, WorkerConfig
+from cairn.dispatcher.runtime.startup_healthcheck import run_startup_healthchecks
+from cairn.dispatcher.workers.adapters.claudecode import ClaudeCodeDriver
+from cairn.dispatcher.workers.adapters.codex import CodexDriver
+from cairn.dispatcher.workers.adapters.mock import MockDriver
+from cairn.dispatcher.workers.adapters.pi import PiDriver
+from cairn.dispatcher.workers.health import http_ping, proxies_from_env
+
+
+class _Resp:
+ def __init__(self, status_code: int, text: str = "") -> None:
+ self.status_code = status_code
+ self.text = text
+
+
+def _capture_post(monkeypatch, response: _Resp) -> dict:
+ captured: dict = {}
+
+ def fake_post(url, headers=None, json=None, timeout=None, proxies=None):
+ captured.update(url=url, headers=headers, json=json, timeout=timeout, proxies=proxies)
+ return response
+
+ monkeypatch.setattr(requests, "post", fake_post)
+ return captured
+
+
+# --------------------------------------------------------------------------- http_ping
+
+
+def test_http_ping_healthy_on_2xx(monkeypatch) -> None:
+ _capture_post(monkeypatch, _Resp(200, "ok"))
+ result = http_ping("http://api/v1/messages", headers={}, json_body={}, timeout=5)
+ assert result.ok
+ assert result.status == 200
+
+
+def test_http_ping_unhealthy_on_4xx(monkeypatch) -> None:
+ _capture_post(monkeypatch, _Resp(401, "unauthorized token"))
+ result = http_ping("http://api/v1/messages", headers={}, json_body={}, timeout=5)
+ assert not result.ok
+ assert result.status == 401
+ assert "unauthorized" in result.detail
+
+
+def test_http_ping_unhealthy_on_connection_error(monkeypatch) -> None:
+ def boom(*_a, **_k):
+ raise requests.ConnectionError("no route")
+
+ monkeypatch.setattr(requests, "post", boom)
+ result = http_ping("http://api/v1/messages", headers={}, json_body={}, timeout=5)
+ assert not result.ok
+ assert result.status is None
+ assert "no route" in result.detail
+
+
+def test_proxies_from_env() -> None:
+ assert proxies_from_env({"https_proxy": "http://p:7897"}) == {"https": "http://p:7897"}
+ assert proxies_from_env({"all_proxy": "http://p:1"}) == {"http": "http://p:1", "https": "http://p:1"}
+ assert proxies_from_env({}) is None
+
+
+# --------------------------------------------------------------------------- driver requests
+
+
+def _worker(worker_type: str, env: dict[str, str]) -> WorkerConfig:
+ return WorkerConfig.model_validate(
+ {"name": worker_type, "type": worker_type, "task_types": ["reason"], "max_running": 1, "priority": 0, "env": env}
+ )
+
+
+def test_claudecode_check_health_hits_messages_with_bearer(monkeypatch) -> None:
+ captured = _capture_post(monkeypatch, _Resp(200))
+ worker = _worker("claudecode", {"ANTHROPIC_BASE_URL": "http://api", "ANTHROPIC_AUTH_TOKEN": "tok", "ANTHROPIC_MODEL": "m"})
+
+ result = ClaudeCodeDriver().check_health(worker, timeout=7)
+
+ assert result.ok
+ assert captured["url"] == "http://api/v1/messages"
+ assert captured["headers"]["Authorization"] == "Bearer tok"
+ assert captured["json"]["model"] == "m"
+ assert captured["timeout"] == 7
+
+
+def test_codex_check_health_hits_responses(monkeypatch) -> None:
+ captured = _capture_post(monkeypatch, _Resp(200))
+ worker = _worker("codex", {"CODEX_BASE_URL": "http://api/v1", "OPENAI_API_KEY": "k", "CODEX_MODEL": "m"})
+
+ CodexDriver().check_health(worker, timeout=5)
+
+ assert captured["url"] == "http://api/v1/responses"
+ assert captured["headers"]["Authorization"] == "Bearer k"
+
+
+def test_pi_check_health_openai_completions_uses_chat_completions(monkeypatch) -> None:
+ captured = _capture_post(monkeypatch, _Resp(200))
+ worker = _worker(
+ "pi",
+ {"PI_BASE_URL": "http://api/v1", "PI_API_KEY": "k", "PI_MODEL": "m", "PI_PROVIDER_API": "openai-completions"},
+ )
+
+ PiDriver().check_health(worker, timeout=5)
+
+ assert captured["url"] == "http://api/v1/chat/completions"
+
+
+def test_pi_check_health_anthropic_uses_messages(monkeypatch) -> None:
+ captured = _capture_post(monkeypatch, _Resp(200))
+ worker = _worker(
+ "pi",
+ {"PI_BASE_URL": "http://api", "PI_API_KEY": "k", "PI_MODEL": "m", "PI_PROVIDER_API": "anthropic-messages"},
+ )
+
+ PiDriver().check_health(worker, timeout=5)
+
+ assert captured["url"] == "http://api/v1/messages"
+ assert captured["headers"]["anthropic-version"]
+
+
+def test_check_health_uses_worker_proxy(monkeypatch) -> None:
+ captured = _capture_post(monkeypatch, _Resp(200))
+ worker = _worker(
+ "claudecode",
+ {"ANTHROPIC_BASE_URL": "http://api", "ANTHROPIC_AUTH_TOKEN": "t", "ANTHROPIC_MODEL": "m", "https_proxy": "http://127.0.0.1:7897"},
+ )
+
+ ClaudeCodeDriver().check_health(worker, timeout=5)
+
+ assert captured["proxies"] == {"https": "http://127.0.0.1:7897"}
+
+
+def test_mock_check_health_reflects_configured_outcome() -> None:
+ ok = _worker("mock", {"MOCK_HEALTHCHECK": '{"delay":[0,0],"outcomes":{"ok":1.0,"fail":0.0}}'})
+ fail = _worker("mock", {"MOCK_HEALTHCHECK": '{"delay":[0,0],"outcomes":{"ok":0.0,"fail":1.0}}'})
+
+ assert MockDriver().check_health(ok, timeout=1).ok
+ assert not MockDriver().check_health(fail, timeout=1).ok
+
+
+# --------------------------------------------------------------------------- startup aggregation
+
+
+def test_run_startup_healthchecks_reports_each_worker() -> None:
+ config = DispatchConfig.model_validate(
+ {
+ "server": "http://127.0.0.1:8000",
+ "runtime": {
+ "interval": 3,
+ "max_workers": 2,
+ "max_running_projects": 1,
+ "max_project_workers": 2,
+ "healthcheck_timeout": 5,
+ "prompt_group": "default",
+ },
+ "tasks": {
+ "bootstrap": {"timeout": 10, "conclude_timeout": 5},
+ "reason": {"timeout": 10, "max_intents": 3},
+ "explore": {"timeout": 10, "conclude_timeout": 5},
+ },
+ "container": {"image": "img", "network_mode": "host", "completed_action": "stop"},
+ "workers": [
+ {"name": "ok-worker", "type": "mock", "task_types": ["reason"], "max_running": 1, "priority": 0,
+ "env": {"MOCK_HEALTHCHECK": '{"delay":[0,0],"outcomes":{"ok":1.0,"fail":0.0}}'}},
+ {"name": "fail-worker", "type": "mock", "task_types": ["reason"], "max_running": 1, "priority": 0,
+ "env": {"MOCK_HEALTHCHECK": '{"delay":[0,0],"outcomes":{"ok":0.0,"fail":1.0}}'}},
+ ],
+ }
+ )
+
+ results = {r.worker_name: r for r in run_startup_healthchecks(config)}
+
+ assert results["ok-worker"].ok
+ assert not results["fail-worker"].ok
\ No newline at end of file
diff --git a/cairn/tests/test_mock_end_to_end.py b/cairn/tests/test_mock_end_to_end.py
index 7b5b904..25ea2d4 100644
--- a/cairn/tests/test_mock_end_to_end.py
+++ b/cairn/tests/test_mock_end_to_end.py
@@ -202,6 +202,8 @@ def _config(
reason: str,
explore: str,
task_types: list[str] | None = None,
+ worker_healthcheck: str = "startup_only",
+ healthcheck: str | None = None,
) -> DispatchConfig:
return DispatchConfig.model_validate(
{
@@ -212,6 +214,7 @@ def _config(
"max_running_projects": 1,
"max_project_workers": 1,
"healthcheck_timeout": 2,
+ "worker_healthcheck": worker_healthcheck,
"prompt_group": "mock",
},
"tasks": {
@@ -232,7 +235,7 @@ def _config(
"max_running": 1,
"priority": 0,
"env": {
- "MOCK_HEALTHCHECK": _phase("ok"),
+ "MOCK_HEALTHCHECK": healthcheck or _phase("ok"),
"MOCK_BOOTSTRAP": bootstrap,
"MOCK_REASON": reason,
"MOCK_EXPLORE_EXECUTE": explore,
@@ -376,3 +379,120 @@ def test_mock_scheduler_enabled_project_skips_bootstrap_when_worker_does_not_sup
assert [(intent.description, intent.to) for intent in project.intents] == [
("mock complete from origin", "goal")
]
+
+
+def test_task_healthcheck_healthy_worker_completes_end_to_end(http_client: TestClient) -> None:
+ client = InProcessClient(http_client)
+ containers = LocalContainerManager()
+ loop = _loop(
+ _config(
+ bootstrap=_phase("complete"),
+ reason=_phase("complete", zero_outcomes=["intent"]),
+ explore=_phase("fact"),
+ worker_healthcheck="startup_and_task",
+ ),
+ client,
+ containers,
+ )
+ project_id = _create_project(http_client)
+
+ try:
+ _dispatch_and_wait(loop)
+ project = client.get_project(project_id)
+ finally:
+ loop.close()
+
+ # code-based check_health runs before the task, passes, and the bootstrap completes
+ assert project.project.status == "completed"
+
+
+def test_task_healthcheck_failure_aborts_task_and_cools_down_worker(http_client: TestClient) -> None:
+ client = InProcessClient(http_client)
+ containers = LocalContainerManager()
+ loop = _loop(
+ _config(
+ bootstrap=_phase("complete"),
+ reason=_phase("complete", zero_outcomes=["intent"]),
+ explore=_phase("fact"),
+ worker_healthcheck="startup_and_task",
+ healthcheck=_phase("fail", zero_outcomes=["ok"]),
+ ),
+ client,
+ containers,
+ )
+ project_id = _create_project(http_client)
+
+ try:
+ _dispatch_and_wait(loop)
+ project = client.get_project(project_id)
+ finally:
+ loop.close()
+
+ # unhealthy worker -> task aborted before execution, no facts written, worker put on cooldown
+ assert project.project.status == "active"
+ assert [fact.id for fact in project.facts] == ["origin", "goal"]
+ assert "mock-worker" in loop.worker_unhealthy_until
+
+
+def _failover_config() -> DispatchConfig:
+ def worker(name: str, priority: int, healthcheck: str) -> dict:
+ return {
+ "name": name,
+ "type": "mock",
+ "task_types": ["bootstrap", "reason", "explore"],
+ "max_running": 1,
+ "priority": priority,
+ "env": {
+ "MOCK_HEALTHCHECK": healthcheck,
+ "MOCK_BOOTSTRAP": _phase("complete"),
+ "MOCK_REASON": _phase("complete", zero_outcomes=["intent"]),
+ "MOCK_EXPLORE_EXECUTE": _phase("fact"),
+ },
+ }
+
+ return DispatchConfig.model_validate(
+ {
+ "server": "in-process",
+ "runtime": {
+ "interval": 1,
+ "max_workers": 1,
+ "max_running_projects": 1,
+ "max_project_workers": 1,
+ "healthcheck_timeout": 2,
+ "worker_healthcheck": "startup_and_task",
+ "prompt_group": "mock",
+ },
+ "tasks": {
+ "bootstrap": {"timeout": 2, "conclude_timeout": 2},
+ "reason": {"timeout": 2, "max_intents": 1},
+ "explore": {"timeout": 2, "conclude_timeout": 2},
+ },
+ "container": {"image": "unused", "network_mode": "host", "completed_action": "stop"},
+ "workers": [
+ worker("bad", 0, _phase("fail", zero_outcomes=["ok"])),
+ worker("good", 1, _phase("ok")),
+ ],
+ }
+ )
+
+
+def test_unhealthy_worker_fails_over_to_healthy_worker(http_client: TestClient) -> None:
+ client = InProcessClient(http_client)
+ containers = LocalContainerManager()
+ loop = _loop(_failover_config(), client, containers)
+ project_id = _create_project(http_client)
+
+ try:
+ # round 1: 'bad' (priority 0) is chosen first, its health check fails -> cooldown
+ _dispatch_and_wait(loop)
+ assert "bad" in loop.worker_unhealthy_until
+ assert client.get_project(project_id).project.status == "active"
+
+ # round 2: 'bad' still cooling down -> 'good' takes over and completes the project
+ _dispatch_and_wait(loop)
+ project = client.get_project(project_id)
+ finally:
+ loop.close()
+
+ assert project.project.status == "completed"
+ assert any(intent.worker == "good" for intent in project.intents)
diff --git a/cairn/tests/test_protocol_and_startup.py b/cairn/tests/test_protocol_and_startup.py
index abf1917..59bae79 100644
--- a/cairn/tests/test_protocol_and_startup.py
+++ b/cairn/tests/test_protocol_and_startup.py
@@ -5,7 +5,6 @@ import requests
from cairn.dispatcher.protocol.client import CairnClient
from cairn.dispatcher.runtime.startup_healthcheck import (
StartupHealthcheckResult,
- _parse_stdout,
format_failure_summary,
)
@@ -24,28 +23,28 @@ def test_client_request_failure_returns_status_zero() -> None:
assert result.text == "offline"
-def test_startup_healthcheck_stdout_parser_extracts_status_and_compacts_preview() -> None:
- status, preview = _parse_stdout("http_status=200\n hello\n world ")
-
- assert status == "200"
- assert preview == "hello world"
-
-
def test_startup_healthcheck_failure_summary_includes_worker_details() -> None:
results = [
StartupHealthcheckResult(
worker_name="worker-a",
ok=False,
- returncode=1,
+ status=401,
duration_ms=12,
- http_status="401",
- response_preview="unauthorized",
- stderr_preview="",
- command="curl",
- )
+ detail="unauthorized",
+ endpoint="POST http://api/v1/messages",
+ ),
+ StartupHealthcheckResult(
+ worker_name="worker-b",
+ ok=True,
+ status=200,
+ duration_ms=8,
+ detail="",
+ endpoint="POST http://api/v1/messages",
+ ),
]
- assert format_failure_summary(results) == (
- "startup healthchecks failed for all workers: "
- "worker-a(http=401, code=1, preview=unauthorized)"
+ summary = format_failure_summary(results)
+
+ assert summary == (
+ "startup healthchecks failed for all workers: worker-a(http=401, detail=unauthorized)"
)
diff --git a/cairn/tests/test_worker_tasks.py b/cairn/tests/test_worker_tasks.py
index 4f2b127..bec97df 100644
--- a/cairn/tests/test_worker_tasks.py
+++ b/cairn/tests/test_worker_tasks.py
@@ -5,7 +5,7 @@ from collections.abc import Iterator
from cairn.dispatcher.protocol.client import ApiResult
from cairn.dispatcher.runtime.cancellation import TaskCancellation
from cairn.dispatcher.runtime.process import ProcessResult
-from cairn.dispatcher.tasks.common import HealthcheckRun
+from cairn.dispatcher.workers.health import HealthResult
from cairn.dispatcher.tasks import bootstrap, explore, reason
from conftest import (
@@ -19,10 +19,6 @@ from conftest import (
)
-def _healthy(*_args, **_kwargs) -> HealthcheckRun:
- return HealthcheckRun(ProcessResult(0, "", ""), duration_ms=1)
-
-
def _lease_factory(lease: FakeLease):
return lambda *_args, **_kwargs: lease
@@ -38,7 +34,6 @@ def test_reason_writes_graph_snapshot_and_creates_intent(monkeypatch) -> None:
monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: driver)
monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))
- monkeypatch.setattr(reason, "run_healthcheck", _healthy)
monkeypatch.setattr(
reason,
"run_worker_process",
@@ -90,7 +85,6 @@ def test_explore_early_plain_text_exit_uses_conclude_fallback(monkeypatch) -> No
monkeypatch.setattr(explore, "get_driver", lambda *_a, **_k: driver)
monkeypatch.setattr(explore.HeartbeatLease, "for_intent", _lease_factory(lease))
- monkeypatch.setattr(explore, "run_healthcheck", _healthy)
monkeypatch.setattr(explore, "_run_process", lambda *_args, **_kwargs: next(results))
outcome = explore.run_explore_task(
@@ -123,13 +117,10 @@ def test_explore_healthcheck_failure_releases_claim(monkeypatch) -> None:
containers = FakeContainerManager()
lease = FakeLease()
- monkeypatch.setattr(explore, "get_driver", lambda *_a, **_k: FakeDriver())
+ driver = FakeDriver()
+ driver.health = HealthResult(ok=False, status=401, detail="unauthorized")
+ monkeypatch.setattr(explore, "get_driver", lambda *_a, **_k: driver)
monkeypatch.setattr(explore.HeartbeatLease, "for_intent", _lease_factory(lease))
- monkeypatch.setattr(
- explore,
- "run_healthcheck",
- lambda *_args, **_kwargs: HealthcheckRun(ProcessResult(1, "", "unhealthy"), duration_ms=1),
- )
outcome = explore.run_explore_task(
config,
@@ -158,7 +149,6 @@ def test_bootstrap_success_concludes_fact_then_completes_project(monkeypatch) ->
monkeypatch.setattr(bootstrap, "get_driver", lambda *_a, **_k: driver)
monkeypatch.setattr(bootstrap.HeartbeatLease, "for_intent", _lease_factory(lease))
- monkeypatch.setattr(bootstrap, "run_healthcheck", _healthy)
monkeypatch.setattr(
bootstrap,
"run_worker_process",
@@ -199,7 +189,6 @@ def test_reason_complete_treats_inactive_project_as_success(monkeypatch) -> None
client.complete = complete # type: ignore[method-assign]
monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: FakeDriver())
monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))
- monkeypatch.setattr(reason, "run_healthcheck", _healthy)
monkeypatch.setattr(
reason,
"run_worker_process",
@@ -232,13 +221,14 @@ def test_reason_startup_only_mode_skips_task_healthcheck(monkeypatch) -> None:
containers = FakeContainerManager()
lease = FakeLease()
- monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: FakeDriver())
+ driver = FakeDriver()
+
+ def _boom(*_a, **_k):
+ raise AssertionError("task healthcheck should be skipped")
+
+ driver.check_health = _boom # type: ignore[method-assign]
+ monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: driver)
monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))
- monkeypatch.setattr(
- reason,
- "run_healthcheck",
- lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("task healthcheck should be skipped")),
- )
monkeypatch.setattr(
reason,
"run_worker_process",
diff --git a/docs/specs/dispatcher-design.md b/docs/specs/dispatcher-design.md
index 7863aa3..5d85b50 100644
--- a/docs/specs/dispatcher-design.md
+++ b/docs/specs/dispatcher-design.md
@@ -633,7 +633,7 @@ Dispatcher 固定从 `stdout` 取全文作为模型正文输出。
统一接口至少应覆盖这些能力:
-- `build_healthcheck(worker)`:构造健康检查命令
+- `check_health(worker, *, timeout)`:进程内发起一次 HTTP 探活,返回 `HealthResult`
- `prepare_session()`:需要时预先生成 session id
- `build_execute(worker, prompt, session)`:构造第一阶段执行命令
- `extract_session(session, stderr)`:需要时从 `stderr` 提取 session id,或继续使用预生成 session
@@ -654,7 +654,7 @@ Dispatcher 固定从 `stdout` 取全文作为模型正文输出。
### 健康检查
-健康检查由 driver 实现。
+健康检查由 driver 的 `check_health` 实现,Dispatcher 在自己进程内直接发起(用 `requests`),而不是在容器里执行 curl。
目标不是验证“容器活着”,而是验证某个具体 Worker 的 LLM 配置真的可用:
@@ -662,18 +662,19 @@ Dispatcher 固定从 `stdout` 取全文作为模型正文输出。
- API key 有效
- model 可调用
+driver 按各自 provider 的协议构造请求:`claudecode` 打 `{base}/v1/messages`,`codex` 打 `{base}/responses`,`pi` 按 `PI_PROVIDER_API` 选择 `/chat/completions`、`/responses` 或 `/v1/messages`。请求会带上 worker 环境里的 `http(s)_proxy`,从而与 worker 实际出网路径一致。
+
执行规则:
- 每次准备启动某个 Worker 进程前,都先执行一次健康检查
- `explore` 进入 timeout / parse-fail 后的 `explore_conclude` fallback 不再重复执行健康检查,而是直接尝试 conclude,并继续依赖 JSON / schema 校验决定是否写回
-- 退出码 `0` 视为健康
-- 非 `0` / 超时(Dispatcher 外层 watchdog 由 `runtime.healthcheck_timeout` 控制)/ 命令起不来,视为不健康
-- driver 内部的 HTTP 探活不再自行设置超时,统一由 Dispatcher 外层 watchdog 限制
+- HTTP 2xx 视为健康
+- 非 2xx / 连接失败 / 超时(`requests` 超时由 `runtime.healthcheck_timeout` 控制)视为不健康
- 如果这次失败,本次任务直接作废,并将这个 Worker 放入一个短暂不可选窗口
- 窗口结束后,后续轮次再次选择到这个 Worker 时重新检查
- Dispatcher 内部会为最近失败的 Worker 记录一个本地 `retry_after`,在这之前不再派发给它
-Dispatcher 只需要看退出码,不需要理解响应体。
+Dispatcher 只看 HTTP 状态码,不解析响应体。`local` 模式下不打 API(本机 CLI 自带鉴权),改为启动时对各 CLI 执行 `--help` 探测。
### CLI 接入约定
@@ -685,7 +686,7 @@ Dispatcher 只需要看退出码,不需要理解响应体。
- `ANTHROPIC_BASE_URL`
- `ANTHROPIC_AUTH_TOKEN`
-健康检查可在 driver 内部按等价方式实现:
+健康检查等价于下面这条请求(实现为 Dispatcher 进程内的 HTTP 调用,不再在容器里执行 curl):
```bash
curl -sS --fail -o /dev/null \
@@ -722,7 +723,7 @@ claude -r "{session}" --dangerously-skip-permissions -p -- "{prompt}"
- `CODEX_BASE_URL`
- `OPENAI_API_KEY`
-健康检查可在 driver 内部按等价方式实现:
+健康检查等价于下面这条请求(实现为 Dispatcher 进程内的 HTTP 调用,不再在容器里执行 curl):
```bash
curl -sS --fail -o /dev/null \