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: add configurable worker healthcheck modes and default to startup-only checks

leixiao29765df88baa
diff --git a/cairn/src/cairn/dispatcher/config.py b/cairn/src/cairn/dispatcher/config.py
index 2add9d2..7dc2540 100644
--- a/cairn/src/cairn/dispatcher/config.py
+++ b/cairn/src/cairn/dispatcher/config.py
@@ -13,6 +13,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
TaskType = Literal["reason", "explore", "bootstrap"]
WorkerType = Literal["claudecode", "codex", "pi", "mock"]
CompletedAction = Literal["remove", "stop"]
+WorkerHealthcheckMode = Literal["startup_and_task", "startup_only", "disabled"]
WORKER_ENV_KEYS: dict[WorkerType, tuple[str, ...]] = {
"claudecode": (
@@ -160,6 +161,7 @@ class RuntimeConfig(BaseModel):
max_project_workers: int = Field(gt=0)
interval: int = Field(gt=0)
healthcheck_timeout: int = Field(gt=0)
+ worker_healthcheck: WorkerHealthcheckMode = "startup_only"
prompt_group: str = Field(min_length=1)
diff --git a/cairn/src/cairn/dispatcher/scheduler/loop.py b/cairn/src/cairn/dispatcher/scheduler/loop.py
index c879570..89ea6aa 100644
--- a/cairn/src/cairn/dispatcher/scheduler/loop.py
+++ b/cairn/src/cairn/dispatcher/scheduler/loop.py
@@ -103,13 +103,17 @@ class DispatcherLoop:
def run_startup_healthchecks_only(self) -> None:
try:
- self.run_startup_healthchecks(show_commands=True)
+ self.run_startup_healthchecks(show_commands=True, force=True)
finally:
self.close()
- def run_startup_healthchecks(self, *, show_commands: bool = False) -> None:
+ def run_startup_healthchecks(self, *, show_commands: bool = False, force: bool = False) -> None:
if self._startup_healthchecks_checked:
return
+ if not force and self.config.runtime.worker_healthcheck == "disabled":
+ LOG.info("skip startup worker healthchecks because runtime.worker_healthcheck=disabled")
+ self._startup_healthchecks_checked = True
+ return
self._run_startup_healthchecks(show_commands=show_commands)
self._startup_healthchecks_checked = True
diff --git a/cairn/src/cairn/dispatcher/tasks/bootstrap.py b/cairn/src/cairn/dispatcher/tasks/bootstrap.py
index 2d5019a..568da24 100644
--- a/cairn/src/cairn/dispatcher/tasks/bootstrap.py
+++ b/cairn/src/cairn/dispatcher/tasks/bootstrap.py
@@ -22,6 +22,7 @@ from cairn.dispatcher.tasks.common import (
preview,
run_healthcheck,
run_worker_process,
+ task_healthcheck_enabled,
write_conclude_result,
write_conclude_result_with_fact_id,
)
@@ -48,54 +49,55 @@ def run_bootstrap_task(
try:
container_name = container_manager.ensure_running(project.project.id)
- LOG.info(
- "starting container exec project=%s intent=%s worker=%s phase=bootstrap_healthcheck 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:
+ if task_healthcheck_enabled(config):
LOG.info(
- "bootstrap cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
+ "starting container exec project=%s intent=%s worker=%s phase=bootstrap_healthcheck timeout=%ss",
project.project.id,
intent.id,
worker.name,
- cancelled,
+ healthcheck_timeout,
)
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "cancelled"
- if lease.failure is not None:
- LOG.warning(
- "heartbeat lost during bootstrap healthcheck project=%s intent=%s worker=%s status=%s",
- project.project.id,
- intent.id,
- worker.name,
- lease.failure.status_code,
- )
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "failed"
- if healthcheck.result.returncode != 0:
- LOG.warning(
- "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
- project.project.id,
- intent.id,
- worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ healthcheck = run_healthcheck(
+ container_manager,
+ container_name,
+ worker,
+ driver.build_healthcheck(worker),
+ timeout_seconds=healthcheck_timeout,
+ lease=lease,
+ cancellation=cancellation,
)
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "unhealthy"
+ cancelled = cancel_reason(healthcheck.result, cancellation)
+ if cancelled is not None:
+ LOG.info(
+ "bootstrap cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ cancelled,
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "cancelled"
+ if lease.failure is not None:
+ LOG.warning(
+ "heartbeat lost during bootstrap healthcheck project=%s intent=%s worker=%s status=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ lease.failure.status_code,
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "failed"
+ if healthcheck.result.returncode != 0:
+ LOG.warning(
+ "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ healthcheck.duration_ms,
+ preview(healthcheck.result.stderr),
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "unhealthy"
prompt = render_prompt(
load_prompt(config.runtime.prompt_group, "bootstrap.md"),
diff --git a/cairn/src/cairn/dispatcher/tasks/common.py b/cairn/src/cairn/dispatcher/tasks/common.py
index dabf39b..c6d1126 100644
--- a/cairn/src/cairn/dispatcher/tasks/common.py
+++ b/cairn/src/cairn/dispatcher/tasks/common.py
@@ -5,7 +5,7 @@ import time
import uuid
from dataclasses import dataclass
-from cairn.dispatcher.config import WorkerConfig
+from cairn.dispatcher.config import DispatchConfig, WorkerConfig
from cairn.dispatcher.protocol.client import CairnClient
from cairn.dispatcher.runtime.cancellation import TaskCancellation
from cairn.dispatcher.runtime.containers import ContainerManager
@@ -54,6 +54,10 @@ def communicate_timeout(timeout_seconds: int, grace_seconds: int = PROCESS_COMMU
return timeout_seconds + grace_seconds
+def task_healthcheck_enabled(config: DispatchConfig) -> bool:
+ return config.runtime.worker_healthcheck == "startup_and_task"
+
+
def write_graph_snapshot_reference(
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 db81d2b..fef8b8f 100644
--- a/cairn/src/cairn/dispatcher/tasks/explore.py
+++ b/cairn/src/cairn/dispatcher/tasks/explore.py
@@ -18,6 +18,7 @@ from cairn.dispatcher.tasks.common import (
preview,
run_healthcheck,
run_worker_process,
+ task_healthcheck_enabled,
write_conclude_result,
write_graph_snapshot_reference,
)
@@ -45,54 +46,55 @@ def run_explore_task(
try:
container_name = container_manager.ensure_running(project.project.id)
- LOG.info(
- "starting container exec project=%s intent=%s worker=%s phase=explore_healthcheck 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:
+ if task_healthcheck_enabled(config):
LOG.info(
- "explore cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
+ "starting container exec project=%s intent=%s worker=%s phase=explore_healthcheck timeout=%ss",
project.project.id,
intent.id,
worker.name,
- cancelled,
+ healthcheck_timeout,
)
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "cancelled"
- if lease.failure is not None:
- LOG.warning(
- "heartbeat lost during explore healthcheck project=%s intent=%s worker=%s status=%s",
- project.project.id,
- intent.id,
- worker.name,
- lease.failure.status_code,
- )
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "failed"
- if healthcheck.result.returncode != 0:
- LOG.warning(
- "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
- project.project.id,
- intent.id,
- worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ healthcheck = run_healthcheck(
+ container_manager,
+ container_name,
+ worker,
+ driver.build_healthcheck(worker),
+ timeout_seconds=healthcheck_timeout,
+ lease=lease,
+ cancellation=cancellation,
)
- best_effort_release(client, project.project.id, intent.id, worker.name)
- return "unhealthy"
+ cancelled = cancel_reason(healthcheck.result, cancellation)
+ if cancelled is not None:
+ LOG.info(
+ "explore cancelled during healthcheck project=%s intent=%s worker=%s reason=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ cancelled,
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "cancelled"
+ if lease.failure is not None:
+ LOG.warning(
+ "heartbeat lost during explore healthcheck project=%s intent=%s worker=%s status=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ lease.failure.status_code,
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "failed"
+ if healthcheck.result.returncode != 0:
+ LOG.warning(
+ "worker unhealthy project=%s intent=%s worker=%s healthcheck_ms=%s stderr=%s",
+ project.project.id,
+ intent.id,
+ worker.name,
+ healthcheck.duration_ms,
+ preview(healthcheck.result.stderr),
+ )
+ best_effort_release(client, project.project.id, intent.id, worker.name)
+ return "unhealthy"
prompt = render_prompt(
load_prompt(config.runtime.prompt_group, "explore.md"),
diff --git a/cairn/src/cairn/dispatcher/tasks/reason.py b/cairn/src/cairn/dispatcher/tasks/reason.py
index 3897d0e..b67f0e9 100644
--- a/cairn/src/cairn/dispatcher/tasks/reason.py
+++ b/cairn/src/cairn/dispatcher/tasks/reason.py
@@ -22,6 +22,7 @@ from cairn.dispatcher.tasks.common import (
preview,
run_healthcheck,
run_worker_process,
+ task_healthcheck_enabled,
write_graph_snapshot_reference,
)
from cairn.dispatcher.workers.registry import get_driver
@@ -47,47 +48,48 @@ def run_reason_task(
try:
container_name = container_manager.ensure_running(project.project.id)
- LOG.info(
- "starting container exec project=%s worker=%s phase=reason_healthcheck 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:
+ if task_healthcheck_enabled(config):
LOG.info(
- "reason cancelled during healthcheck project=%s worker=%s reason=%s",
- project.project.id,
- worker.name,
- cancelled,
- )
- return "cancelled"
- if lease.failure is not None:
- LOG.warning(
- "heartbeat lost during reason healthcheck project=%s worker=%s status=%s",
+ "starting container exec project=%s worker=%s phase=reason_healthcheck timeout=%ss",
project.project.id,
worker.name,
- lease.failure.status_code,
+ healthcheck_timeout,
)
- return "failed"
- if healthcheck.result.returncode != 0:
- LOG.warning(
- "worker unhealthy project=%s worker=%s healthcheck_ms=%s stderr=%s",
- project.project.id,
- worker.name,
- healthcheck.duration_ms,
- preview(healthcheck.result.stderr),
+ healthcheck = run_healthcheck(
+ container_manager,
+ container_name,
+ worker,
+ driver.build_healthcheck(worker),
+ timeout_seconds=healthcheck_timeout,
+ lease=lease,
+ cancellation=cancellation,
)
- return "unhealthy"
+ cancelled = cancel_reason(healthcheck.result, cancellation)
+ if cancelled is not None:
+ LOG.info(
+ "reason cancelled during healthcheck project=%s worker=%s reason=%s",
+ project.project.id,
+ worker.name,
+ cancelled,
+ )
+ return "cancelled"
+ if lease.failure is not None:
+ LOG.warning(
+ "heartbeat lost during reason healthcheck project=%s worker=%s status=%s",
+ project.project.id,
+ worker.name,
+ lease.failure.status_code,
+ )
+ return "failed"
+ if healthcheck.result.returncode != 0:
+ LOG.warning(
+ "worker unhealthy project=%s worker=%s healthcheck_ms=%s stderr=%s",
+ project.project.id,
+ worker.name,
+ healthcheck.duration_ms,
+ preview(healthcheck.result.stderr),
+ )
+ return "unhealthy"
open_intents = [
{
"id": intent.id,
diff --git a/cairn/tests/test_config_and_adapters.py b/cairn/tests/test_config_and_adapters.py
index 02f7f1c..0c6083a 100644
--- a/cairn/tests/test_config_and_adapters.py
+++ b/cairn/tests/test_config_and_adapters.py
@@ -23,6 +23,17 @@ def test_dispatch_config_merges_common_env_with_worker_override() -> None:
assert config.workers[0].env["OVERRIDE"] == "worker"
+def test_dispatch_config_defaults_worker_healthcheck_and_rejects_unknown_mode() -> None:
+ payload = make_config().model_dump()
+ payload["runtime"].pop("worker_healthcheck")
+
+ assert DispatchConfig.model_validate(payload).runtime.worker_healthcheck == "startup_only"
+
+ payload["runtime"]["worker_healthcheck"] = "sometimes"
+ with pytest.raises(ValidationError):
+ DispatchConfig.model_validate(payload)
+
+
def test_dispatch_config_rejects_duplicate_workers_and_excess_project_parallelism() -> None:
payload = make_config().model_dump()
payload["workers"].append(dict(payload["workers"][0]))
diff --git a/cairn/tests/test_scheduler_logic.py b/cairn/tests/test_scheduler_logic.py
index f2b51c4..eabd95b 100644
--- a/cairn/tests/test_scheduler_logic.py
+++ b/cairn/tests/test_scheduler_logic.py
@@ -203,3 +203,39 @@ def test_select_worker_reports_busy_unhealthy_rejected_and_unsupported_workers(m
assert selection.blocked_unhealthy == ["unhealthy(10.0s)"]
assert selection.blocked_rejected == ["rejected(20.0s)"]
assert selection.blocked_task_type == ["unsupported"]
+
+
+def test_disabled_worker_healthcheck_skips_automatic_startup_but_force_runs_diagnostic() -> None:
+ loop = _loop()
+ config = make_config()
+ loop.config = config.model_copy(
+ update={"runtime": config.runtime.model_copy(update={"worker_healthcheck": "disabled"})}
+ )
+ calls: list[bool] = []
+ loop._run_startup_healthchecks = lambda *, show_commands: calls.append(show_commands)
+ loop._startup_healthchecks_checked = False
+
+ loop.run_startup_healthchecks()
+
+ assert calls == []
+ assert loop._startup_healthchecks_checked
+
+ loop._startup_healthchecks_checked = False
+ loop.run_startup_healthchecks(show_commands=True, force=True)
+
+ assert calls == [True]
+
+
+def test_startup_only_worker_healthcheck_runs_automatic_startup_check() -> None:
+ loop = _loop()
+ config = make_config()
+ loop.config = config.model_copy(
+ update={"runtime": config.runtime.model_copy(update={"worker_healthcheck": "startup_only"})}
+ )
+ calls: list[bool] = []
+ loop._run_startup_healthchecks = lambda *, show_commands: calls.append(show_commands)
+ loop._startup_healthchecks_checked = False
+
+ loop.run_startup_healthchecks()
+
+ assert calls == [False]
diff --git a/cairn/tests/test_worker_tasks.py b/cairn/tests/test_worker_tasks.py
index 9111e8b..4077664 100644
--- a/cairn/tests/test_worker_tasks.py
+++ b/cairn/tests/test_worker_tasks.py
@@ -116,6 +116,7 @@ def test_explore_early_plain_text_exit_uses_conclude_fallback(monkeypatch) -> No
def test_explore_healthcheck_failure_releases_claim(monkeypatch) -> None:
config = make_config()
+ config.runtime.worker_healthcheck = "startup_and_task"
intent = make_intent()
project = make_project(intents=[intent])
client = FakeClient(project)
@@ -222,3 +223,41 @@ def test_reason_complete_treats_inactive_project_as_success(monkeypatch) -> None
assert outcome == "success"
assert client.released_reasons == [("proj_001", "test-worker")]
+
+def test_reason_startup_only_mode_skips_task_healthcheck(monkeypatch) -> None:
+ config = make_config()
+ config.runtime.worker_healthcheck = "startup_only"
+ project = make_project()
+ client = FakeClient(project)
+ containers = FakeContainerManager()
+ lease = FakeLease()
+
+ monkeypatch.setattr(reason, "get_driver", lambda _name: FakeDriver())
+ 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",
+ lambda *_args, **_kwargs: ProcessResult(
+ 0,
+ '{"accepted":true,"data":{"intents":[{"from":["f001"],"description":"next"}]}}',
+ "",
+ ),
+ )
+
+ outcome = reason.run_reason_task(
+ config,
+ client,
+ containers,
+ project,
+ "graph",
+ config.workers[0],
+ TaskCancellation(),
+ )
+
+ assert outcome == "success"
+ assert client.created_intents == [("proj_001", ["f001"], "next", "test-worker")]
diff --git a/dispatch.yaml b/dispatch.yaml
index aa5113f..ce5e46f 100644
--- a/dispatch.yaml
+++ b/dispatch.yaml
@@ -15,8 +15,11 @@ runtime:
max_running_projects: 3
# Per-project worker cap. Prevents one project from monopolizing the whole dispatcher.
max_project_workers: 4
- # Healthcheck timeout for each worker process before a task is assigned.
+ # Timeout for each enabled worker healthcheck.
healthcheck_timeout: 20
+ # "startup_and_task" checks at dispatcher startup and before every task.
+ # "startup_only" checks only at startup. "disabled" skips automatic worker checks.
+ worker_healthcheck: "startup_only"
# Prompt set loaded from cairn/src/cairn/dispatcher/prompts/.
prompt_group: "default"
diff --git a/dispatch_mock.yaml b/dispatch_mock.yaml
index c685e97..49f0262 100644
--- a/dispatch_mock.yaml
+++ b/dispatch_mock.yaml
@@ -6,6 +6,7 @@ runtime:
max_running_projects: 2
max_project_workers: 4
healthcheck_timeout: 2
+ worker_healthcheck: "startup_only"
prompt_group: "mock"
tasks: