Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions openhands/automation/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,10 @@ async def _fail(
error,
status_detail=status_detail,
)
# mark_run_terminal updates a re-fetched row; sync this object so
# telemetry reports the persisted status instead of RUNNING.
run.status = AutomationRunStatus.FAILED
run.error_detail = error
automation_disabled = disable
if disable:
automation_disabled = await disable_automation(
Expand Down Expand Up @@ -1787,6 +1791,18 @@ async def _execute_run_safe(
operation="execute_run_task",
),
)
run.status = AutomationRunStatus.FAILED
run.error_detail = "Internal error"
await capture_automation_event(
"automation_run_failed",
automation=run.automation,
run=run,
session_factory=session_factory,
properties={
"trigger_source": "dispatcher",
"failure_kind": "dispatch_error",
},
)


async def dispatcher_loop(
Expand Down
35 changes: 35 additions & 0 deletions openhands/automation/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,40 @@ def _failure_kind_from_error_detail(error_detail: str | None) -> str | None:
return "execution_error"


# Failure events must stay categorizable even when a caller stored no error
# text, so terminal failure captures fall back to these bounded values.
# Stage names reuse the vocabulary record_first_run_outcome already records.
_FAILURE_STAGE_BY_TRIGGER_SOURCE = {
"callback": "execution",
"dispatcher": "dispatch",
"watchdog": "watchdog",
}
_FAILURE_EVENTS = frozenset({"automation_run_failed", "automation_run_dispatch_failed"})


def _ensure_failure_properties(event: str, properties: dict[str, Any]) -> None:
"""Guarantee bounded failure_stage/failure_kind on failure events.

Explicit caller properties always win; raw error text is never copied.
"""
if event not in _FAILURE_EVENTS:
return
stage = properties.get("failure_stage")
if not stage:
trigger_source = properties.get("trigger_source")
stage = (
_FAILURE_STAGE_BY_TRIGGER_SOURCE.get(trigger_source)
if isinstance(trigger_source, str)
else None
)
if stage is not None:
properties["failure_stage"] = stage
if not properties.get("failure_kind"):
properties["failure_kind"] = (
"dispatch_error" if stage == "dispatch" else "execution_error"
)


@lru_cache(maxsize=1)
def _installed_sdk_version() -> str:
# Only successful lookups are cached: lru_cache does not memoize exceptions.
Expand Down Expand Up @@ -506,6 +540,7 @@ async def _capture_automation_event(
)
if properties:
event_properties.update(properties)
_ensure_failure_properties(event, event_properties)

payload = {
"api_key": settings.posthog_api_key,
Expand Down
17 changes: 16 additions & 1 deletion openhands/automation/watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ async def _verify_and_mark_run(
verification = await backend.verify_run(run_id)
except Exception as e:
logger.warning("Failed to verify run: %s", e, extra=extra)
error_detail = f"Timed out: verification failed: {e}"
stmt = (
update(AutomationRun)
.where(
Expand All @@ -257,7 +258,7 @@ async def _verify_and_mark_run(
.values(
status=AutomationRunStatus.FAILED,
completed_at=now,
error_detail=f"Timed out: verification failed: {e}",
error_detail=error_detail,
status_detail=run_status_detail_from_exception(
e,
phase=RunStatusPhase.VERIFICATION,
Expand All @@ -269,6 +270,10 @@ async def _verify_and_mark_run(
)
result: CursorResult = await session.execute(stmt) # type: ignore[assignment]
if result.rowcount > 0:
# The UPDATE above bypasses the ORM object; sync it so telemetry
# derives run_status/failure_kind from the persisted values.
run.status = AutomationRunStatus.FAILED
run.error_detail = error_detail
await capture_automation_event(
"automation_run_failed",
automation=_loaded_automation(run),
Expand All @@ -289,6 +294,7 @@ async def _verify_and_mark_run(
VerificationOutcome.FAILED,
):
exit_code = verification.exit_code
error_detail: str | None = None

# Command completed successfully; the callback was missed.
if verification.outcome == VerificationOutcome.COMPLETED:
Expand Down Expand Up @@ -386,6 +392,13 @@ async def _verify_and_mark_run(

result = await session.execute(stmt) # type: ignore[assignment]
if result.rowcount > 0:
run.status = (
AutomationRunStatus.COMPLETED
if exit_code == 0
else AutomationRunStatus.FAILED
)
if exit_code != 0:
run.error_detail = error_detail
await capture_automation_event(
"automation_run_completed"
if exit_code == 0
Expand Down Expand Up @@ -539,6 +552,8 @@ async def _verify_and_mark_run(
)
result = await session.execute(stmt) # type: ignore[assignment]
if result.rowcount > 0:
run.status = AutomationRunStatus.FAILED
run.error_detail = f"Timed out: {error_msg}"
await capture_automation_event(
"automation_run_failed",
automation=_loaded_automation(run),
Expand Down
92 changes: 92 additions & 0 deletions tests/test_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,98 @@ async def test_execute_run_safe_resumes_triggering_event_trace():
assert mock_span.call_args.kwargs["parent_span_context"] == parent_context


class _FakeTelemetryResponse:
def raise_for_status(self) -> None:
return None


class _FakeTelemetryClient:
"""Stand-in for the external PostHog HTTP transport only."""

def __init__(self) -> None:
self.posts: list[tuple[str, dict]] = []

async def post(self, url: str, json: dict) -> _FakeTelemetryResponse:
self.posts.append((url, json))
return _FakeTelemetryResponse()


@pytest.mark.asyncio
async def test_execute_run_safe_emits_categorized_failure_telemetry(
async_session_factory, mock_settings, mock_client, monkeypatch
):
"""A last-resort dispatcher failure still emits a terminal failed event."""
from openhands.automation import telemetry
from openhands.automation.config import clear_config_cache

monkeypatch.setenv("AUTOMATION_POSTHOG_API_KEY", "ph_test")
monkeypatch.delenv("AUTOMATION_AGENT_SERVER_URL", raising=False)
clear_config_cache()
fake_client = _FakeTelemetryClient()
monkeypatch.setattr(telemetry, "_telemetry_http_client", fake_client)
try:
async with async_session_factory() as session:
automation = Automation(
user_id=TEST_USER_ID,
org_id=TEST_ORG_ID,
name="Dispatcher Telemetry Automation",
trigger={"type": "cron", "schedule": "* * * * *"},
tarball_path="s3://bucket/code.tar.gz",
entrypoint="uv run main.py",
enabled=True,
timeout=60,
)
session.add(automation)
await session.commit()
run = AutomationRun(
automation_id=automation.id,
status=AutomationRunStatus.RUNNING,
started_at=utcnow(),
)
session.add(run)
await session.commit()
run_id = run.id

async with async_session_factory() as session:
run = (
(
await session.execute(
select(AutomationRun)
.options(selectinload(AutomationRun.automation))
.where(AutomationRun.id == run_id)
)
)
.scalars()
.first()
)

with patch(
"openhands.automation.dispatcher._execute_run",
new_callable=AsyncMock,
side_effect=RuntimeError("boom token=sekrit"),
):
await _execute_run_safe(
run, mock_settings, async_session_factory, mock_client
)

async with async_session_factory() as session:
updated = await session.get(AutomationRun, run_id)
assert updated.status == AutomationRunStatus.FAILED

assert len(fake_client.posts) == 1
_, payload = fake_client.posts[0]
assert payload["event"] == "automation_run_failed"
assert payload["distinct_id"] == str(TEST_USER_ID)
properties = payload["properties"]
assert properties["failure_kind"] == "dispatch_error"
assert properties["failure_stage"] == "dispatch"
assert properties["trigger_source"] == "dispatcher"
assert properties["run_status"] == "FAILED"
assert "sekrit" not in str(properties)
finally:
clear_config_cache()


class TestIsHttpUrl:
"""Tests for is_http_url helper function."""

Expand Down
Loading
Loading