From a857c60bda934917c869ccd7cbb6e494d3e05070 Mon Sep 17 00:00:00 2001 From: hieptl Date: Mon, 10 Aug 2026 12:04:42 +0700 Subject: [PATCH] feat: add template provenance, idempotent enablement, and first-run outcome to presets --- openhands/automation/preset_router.py | 180 ++++++++++++++++++++++++-- openhands/automation/router.py | 3 +- openhands/automation/utils/run.py | 111 ++++++++++++++++ openhands/automation/watchdog.py | 15 +++ tests/test_dispatcher.py | 63 ++++++++- tests/test_preset_router.py | 158 ++++++++++++++++++++++ tests/test_router.py | 142 ++++++++++++++++++++ tests/test_watchdog.py | 65 ++++++++++ 8 files changed, 725 insertions(+), 12 deletions(-) diff --git a/openhands/automation/preset_router.py b/openhands/automation/preset_router.py index 220bada9..d94c5a51 100644 --- a/openhands/automation/preset_router.py +++ b/openhands/automation/preset_router.py @@ -19,14 +19,14 @@ from pathlib import Path from typing import Any -from fastapi import APIRouter, Depends, HTTPException, Request, status +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator -from sqlalchemy import select +from sqlalchemy import func, literal, select from sqlalchemy.ext.asyncio import AsyncSession from openhands.automation.auth import AuthenticatedUser, authenticate_request from openhands.automation.constants import MODEL_PROFILE_PATTERN -from openhands.automation.db import get_session +from openhands.automation.db import get_session, using_sqlite from openhands.automation.models import Automation, TarballUpload, UploadStatus from openhands.automation.schemas import AutomationResponse, Trigger from openhands.automation.storage import FileStore, get_file_store @@ -114,6 +114,51 @@ async def _bytes_to_async_iter(data: bytes) -> AsyncIterator[bytes]: yield data +# Cap on the serialized size of template provenance config, so an opaque +# payload cannot bloat the preset_metadata JSON column. +MAX_TEMPLATE_CONFIG_BYTES = 16_384 + + +class TemplateProvenance(BaseModel): + """Opaque provenance of the extension-owned template an automation came from. + + The service stores this verbatim under ``preset_metadata["template"]`` and + never validates it against any catalog — template definitions are owned by + OpenHands/extensions. Must not contain secrets. + """ + + model_config = ConfigDict(extra="forbid") + + id: str = Field( + ..., + min_length=1, + max_length=100, + description="Identifier of the extension template (catalog entry id).", + ) + version: str = Field( + ..., + min_length=1, + max_length=50, + description="Version of the template at creation time.", + ) + config: dict[str, Any] | None = Field( + default=None, + description=( + "Non-secret configuration the user submitted when enabling the " + "template (e.g. setup form values)." + ), + ) + + @field_validator("config") + @classmethod + def validate_config_size(cls, v: dict[str, Any] | None) -> dict[str, Any] | None: + if v is not None and len(json.dumps(v)) > MAX_TEMPLATE_CONFIG_BYTES: + raise ValueError( + f"config must serialize to at most {MAX_TEMPLATE_CONFIG_BYTES} bytes" + ) + return v + + class CreatePromptAutomationRequest(BaseModel): """Request to create an automation from a prompt.""" @@ -163,6 +208,19 @@ class CreatePromptAutomationRequest(BaseModel): "Can be a single repo or a list of repos." ), ) + template: TemplateProvenance | None = Field( + default=None, + description=( + "Opaque provenance of the extension template this automation is " + "created from. Enables idempotent creation: when a live automation " + "for the same user and template id already exists, it is returned " + "unchanged with HTTP 200 instead of creating a duplicate." + ), + ) + enabled: bool = Field( + default=True, + description="Whether the automation starts enabled.", + ) @field_validator("timeout") @classmethod @@ -385,10 +443,62 @@ async def regenerate_preset_prompt_tarball( return build_internal_url(new_upload_id) -@router.post("/prompt", status_code=status.HTTP_201_CREATED) +async def _find_existing_template_automation( + session: AsyncSession, + user: AuthenticatedUser, + template_id: str, +) -> Automation | None: + """Find the caller's live automation created from the given template. + + Cross-database JSON extraction mirrors ``get_event_automations``: SQLite + uses ``json_extract``, PostgreSQL uses the ``->`` / ``->>`` operators. Rows + without template provenance yield NULL and are excluded on both databases. + + Two concurrent creates can both miss the existing row (there is no + cross-database unique index on a JSON path); the earliest-created row wins + subsequent lookups. + """ + if using_sqlite(): + template_filter = func.json_extract( + Automation.preset_metadata, "$.template.id" + ) == literal(template_id) + else: + template_filter = Automation.preset_metadata.op("->")("template").op("->>")( + "id" + ) == literal(template_id) + + result = await session.execute( + select(Automation) + .where( + Automation.user_id == user.user_id, + Automation.org_id == user.org_id, + Automation.deleted_at.is_(None), + template_filter, + ) + .order_by(Automation.created_at.asc()) + .limit(1) + ) + return result.scalars().first() + + +_TEMPLATE_EXISTS_RESPONSE: dict[int | str, dict[str, Any]] = { + 200: { + "model": AutomationResponse, + "description": ( + "An automation created from this template already exists for this " + "user; it is returned unchanged." + ), + }, +} + + +@router.post( + "/prompt", status_code=status.HTTP_201_CREATED, responses=_TEMPLATE_EXISTS_RESPONSE +) async def create_automation_from_prompt( body: CreatePromptAutomationRequest, request: Request, + response: Response, user: AuthenticatedUser = Depends(authenticate_request), session: AsyncSession = Depends(get_session), file_store: FileStore = Depends(get_file_store), @@ -407,6 +517,16 @@ async def create_automation_from_prompt( 5. Execute the provided prompt 6. Report completion status back to the automation service """ + # Idempotent creation: enabling the same extension template twice returns + # the existing automation unchanged instead of creating a duplicate. + if body.template is not None: + existing = await _find_existing_template_automation( + session, user, body.template.id + ) + if existing is not None: + response.status_code = status.HTTP_200_OK + return AutomationResponse.model_validate(existing) + model = resolve_model_profile_for_user(body.model, user) # 1. Generate tarball with SDK code, prompt, and optional repos config @@ -460,6 +580,8 @@ async def create_automation_from_prompt( } if body.repos: preset_metadata["repos"] = [r.model_dump(exclude_none=True) for r in body.repos] + if body.template is not None: + preset_metadata["template"] = body.template.model_dump(exclude_none=True) try: automation = Automation( @@ -475,6 +597,7 @@ async def create_automation_from_prompt( entrypoint=_get_preset_entrypoint(), timeout=default_automation_timeout(body.timeout), keep_alive=body.keep_alive, + enabled=body.enabled, telemetry_distinct_id=get_request_telemetry_context( request ).frontend_distinct_id, @@ -501,12 +624,16 @@ async def create_automation_from_prompt( "prompt_length": len(body.prompt), }, ) + creation_properties: dict[str, Any] = {"creation_path": "prompt_preset"} + if body.template is not None: + creation_properties["template_id"] = body.template.id + creation_properties["template_version"] = body.template.version await capture_automation_event( "automation_created", request=request, user=user, automation=automation, - properties={"creation_path": "prompt_preset"}, + properties=creation_properties, ) return AutomationResponse.model_validate(automation) @@ -611,6 +738,19 @@ class CreatePluginAutomationRequest(BaseModel): "Can be a single repo or a list of repos." ), ) + template: TemplateProvenance | None = Field( + default=None, + description=( + "Opaque provenance of the extension template this automation is " + "created from. Enables idempotent creation: when a live automation " + "for the same user and template id already exists, it is returned " + "unchanged with HTTP 200 instead of creating a duplicate." + ), + ) + enabled: bool = Field( + default=True, + description="Whether the automation starts enabled.", + ) @field_validator("timeout") @classmethod @@ -751,10 +891,13 @@ def _format_plugin_sources_for_description(plugins: list[PluginSource]) -> str: return ", ".join(f"{p.source}@{p.ref}" if p.ref else p.source for p in plugins) -@router.post("/plugin", status_code=status.HTTP_201_CREATED) +@router.post( + "/plugin", status_code=status.HTTP_201_CREATED, responses=_TEMPLATE_EXISTS_RESPONSE +) async def create_automation_from_plugin( body: CreatePluginAutomationRequest, request: Request, + response: Response, user: AuthenticatedUser = Depends(authenticate_request), session: AsyncSession = Depends(get_session), file_store: FileStore = Depends(get_file_store), @@ -780,6 +923,16 @@ async def create_automation_from_plugin( - With ref: branch, tag, or commit SHA - With repo_path: subdirectory for monorepos """ + # Idempotent creation: enabling the same extension template twice returns + # the existing automation unchanged instead of creating a duplicate. + if body.template is not None: + existing = await _find_existing_template_automation( + session, user, body.template.id + ) + if existing is not None: + response.status_code = status.HTTP_200_OK + return AutomationResponse.model_validate(existing) + model = resolve_model_profile_for_user(body.model, user) variants = _resolve_experiment_variant_models( body.variants, user, default_model=model @@ -856,6 +1009,8 @@ async def create_automation_from_plugin( ] if body.repos: preset_metadata["repos"] = [r.model_dump(exclude_none=True) for r in body.repos] + if body.template is not None: + preset_metadata["template"] = body.template.model_dump(exclude_none=True) try: automation = Automation( @@ -871,6 +1026,7 @@ async def create_automation_from_plugin( entrypoint=_get_preset_entrypoint(), timeout=default_automation_timeout(body.timeout), keep_alive=body.keep_alive, + enabled=body.enabled, telemetry_distinct_id=get_request_telemetry_context( request ).frontend_distinct_id, @@ -901,15 +1057,19 @@ async def create_automation_from_plugin( log_extra["plugin_count"] = len(body.plugins) logger.info("Created automation from plugin", extra=log_extra) + creation_properties: dict[str, Any] = { + "creation_path": "plugin_preset", + "plugin_count": len(body.plugins or []), + } + if body.template is not None: + creation_properties["template_id"] = body.template.id + creation_properties["template_version"] = body.template.version await capture_automation_event( "automation_created", request=request, user=user, automation=automation, - properties={ - "creation_path": "plugin_preset", - "plugin_count": len(body.plugins or []), - }, + properties=creation_properties, ) return AutomationResponse.model_validate(automation) diff --git a/openhands/automation/router.py b/openhands/automation/router.py index 0b485a15..ca112566 100644 --- a/openhands/automation/router.py +++ b/openhands/automation/router.py @@ -41,7 +41,7 @@ get_api_key_for_automation_run, ) from openhands.automation.utils.model_profiles import resolve_model_profile_for_user -from openhands.automation.utils.run import create_pending_run +from openhands.automation.utils.run import create_pending_run, record_first_run_outcome from openhands.automation.utils.sandbox import cleanup_sandbox from openhands.automation.utils.tarball_validation import ( is_http_url, @@ -455,6 +455,7 @@ async def complete_run( run=run, properties={"trigger_source": "callback"}, ) + await record_first_run_outcome(run, new_status, "execution", session=session) # Clean up immediately when this automation owns explicit cleanup. Once # post-run callbacks exist, this path should run them before deleting. diff --git a/openhands/automation/utils/run.py b/openhands/automation/utils/run.py index b25a7bbe..7ce4e679 100644 --- a/openhands/automation/utils/run.py +++ b/openhands/automation/utils/run.py @@ -7,13 +7,22 @@ from sqlalchemy import CursorResult, select, update from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from openhands.automation.db import using_sqlite from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus +from openhands.automation.telemetry import capture_automation_event from openhands.automation.utils.time import utcnow from openhands.automation.utils.timeout import resolve_automation_timeout_seconds logger = logging.getLogger(__name__) +# Terminal statuses that count as a first-run outcome. CANCELLED and SKIPPED +# are excluded so a later real run still records the one outcome. +FIRST_RUN_OUTCOME_STATUSES = ( + AutomationRunStatus.COMPLETED, + AutomationRunStatus.FAILED, +) + async def disable_automation( session_factory: async_sessionmaker[AsyncSession], @@ -219,6 +228,103 @@ async def update_bash_command_id( logger.exception("Failed to update bash_command_id for run %s", run_id) +async def _record_first_run_outcome_in_session( + session: AsyncSession, + run: AutomationRun, + status: AutomationRunStatus, + stage: str, +) -> bool: + """Write the first-run record if this automation still lacks one. + + Returns True when a record was written (caller commits). + """ + query = select(Automation).where(Automation.id == run.automation_id) + if not using_sqlite(): + # Serialize racing terminal transitions; SQLite writes serialize anyway. + query = query.with_for_update() + automation = (await session.execute(query)).scalars().first() + if automation is None: + return False + + metadata = automation.preset_metadata + if not metadata or "template" not in metadata or "first_run" in metadata: + return False + + outcome = "success" if status == AutomationRunStatus.COMPLETED else "failure" + failure_stage = stage if status == AutomationRunStatus.FAILED else None + # Reassign the whole dict: in-place mutation of a JSON column is not + # change-tracked. + automation.preset_metadata = { + **metadata, + "first_run": { + "status": outcome, + "failure_stage": failure_stage, + "template_version": metadata["template"].get("version"), + "recorded_at": utcnow().isoformat(), + }, + } + await session.flush() + + await capture_automation_event( + "automation_template_first_run", + automation=automation, + run=run, + session=session, + properties={ + "template_id": metadata["template"].get("id"), + "template_version": metadata["template"].get("version"), + "outcome": outcome, + "failure_stage": failure_stage, + }, + ) + return True + + +async def record_first_run_outcome( + run: AutomationRun, + status: AutomationRunStatus, + stage: str, + *, + session: AsyncSession | None = None, + session_factory: async_sessionmaker[AsyncSession] | None = None, +) -> None: + """Record the one-time first terminal outcome of a template-created automation. + + Writes a non-sensitive record (no prompt, no error text) under + ``preset_metadata["first_run"]`` and emits one telemetry event. The absence + of that key is the once-guard; only automations carrying template + provenance record an outcome. Never raises — the run lifecycle must not be + affected. + + Args: + run: The run that reached a terminal status. + status: The terminal status (only COMPLETED/FAILED record an outcome). + stage: Lifecycle stage that produced the outcome: + "dispatch", "execution", or "watchdog". + session: Session to record in; the caller commits. + session_factory: Opens (and commits) a dedicated session when no + session is given. + """ + if status not in FIRST_RUN_OUTCOME_STATUSES: + return + + try: + if session is not None: + await _record_first_run_outcome_in_session(session, run, status, stage) + elif session_factory is not None: + async with session_factory() as local_session: + recorded = await _record_first_run_outcome_in_session( + local_session, run, status, stage + ) + if recorded: + await local_session.commit() + except Exception: + logger.exception( + "Failed to record first-run outcome", + extra={"run_id": str(run.id), "automation_id": str(run.automation_id)}, + ) + + async def mark_run_terminal( session_factory: async_sessionmaker[AsyncSession], run: AutomationRun, @@ -262,6 +368,11 @@ async def mark_run_terminal( ) await session.commit() logger.info("Run marked as %s", status.value, extra=extra) + # Dedicated session so a recording failure cannot affect the + # already-committed run transition. + await record_first_run_outcome( + db_run, status, "dispatch", session_factory=session_factory + ) else: logger.info( "Run not marked %s (current status: %s)", diff --git a/openhands/automation/watchdog.py b/openhands/automation/watchdog.py index 66b72ac2..62357046 100644 --- a/openhands/automation/watchdog.py +++ b/openhands/automation/watchdog.py @@ -28,6 +28,7 @@ ) from openhands.automation.telemetry import capture_automation_event from openhands.automation.utils import log_extra +from openhands.automation.utils.run import record_first_run_outcome from openhands.automation.utils.time import utcnow @@ -110,6 +111,9 @@ async def _verify_and_mark_run( "failure_kind": "verification_failed", }, ) + await record_first_run_outcome( + run, AutomationRunStatus.FAILED, "watchdog", session=session + ) return result.rowcount > 0 if verification.verified: @@ -200,6 +204,14 @@ async def _verify_and_mark_run( "verification_exit_code": exit_code, }, ) + await record_first_run_outcome( + run, + AutomationRunStatus.COMPLETED + if exit_code == 0 + else AutomationRunStatus.FAILED, + "watchdog", + session=session, + ) if result.rowcount > 0 and _should_cleanup_sandbox_after_terminal( run, keep_alive ): @@ -262,6 +274,9 @@ async def _verify_and_mark_run( "failure_kind": "timeout", }, ) + await record_first_run_outcome( + run, AutomationRunStatus.FAILED, "watchdog", session=session + ) return result.rowcount > 0 diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index fab82a82..fff7c1ca 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -22,7 +22,7 @@ from openhands.automation.exceptions import ConcurrencyLimitReachedError from openhands.automation.models import Automation, AutomationRun, AutomationRunStatus from openhands.automation.utils import utcnow -from openhands.automation.utils.run import mark_run_status +from openhands.automation.utils.run import mark_run_status, mark_run_terminal from openhands.automation.utils.tarball_validation import is_http_url @@ -210,6 +210,67 @@ async def test_sets_completed_at_on_failed(self, async_session_factory): assert before <= updated.completed_at <= after +class TestMarkRunTerminalFirstRunOutcome: + """First-run outcome recording when the dispatcher terminates a run.""" + + async def _seed_template_run(self, async_session_factory): + """A RUNNING run on an automation created from an extension template.""" + async with async_session_factory() as session: + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Template Automation", + trigger={"type": "cron", "schedule": "* * * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run main.py", + enabled=True, + preset_metadata={ + "preset_type": "prompt", + "prompt": "p", + "template": {"id": "tpl", "version": "1.0.0"}, + }, + ) + session.add(automation) + await session.commit() + + run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.RUNNING, + ) + session.add(run) + await session.commit() + return automation.id, run + + async def test_dispatch_failure_records_dispatch_stage(self, async_session_factory): + """A run failed at dispatch records the dispatch failure stage.""" + automation_id, run = await self._seed_template_run(async_session_factory) + + await mark_run_terminal( + async_session_factory, + run, + AutomationRunStatus.FAILED, + "sandbox creation failed", + ) + + async with async_session_factory() as session: + automation = await session.get(Automation, automation_id) + first_run = automation.preset_metadata["first_run"] + assert first_run["status"] == "failure" + assert first_run["failure_stage"] == "dispatch" + + async def test_skipped_run_does_not_consume_the_first_run_slot( + self, async_session_factory + ): + """A skipped run records nothing, so a later real run still can.""" + automation_id, run = await self._seed_template_run(async_session_factory) + + await mark_run_terminal(async_session_factory, run, AutomationRunStatus.SKIPPED) + + async with async_session_factory() as session: + automation = await session.get(Automation, automation_id) + assert "first_run" not in automation.preset_metadata + + class TestDispatchPendingRuns: """Tests for dispatch_pending_runs function.""" diff --git a/tests/test_preset_router.py b/tests/test_preset_router.py index 5376bb9d..64109b82 100644 --- a/tests/test_preset_router.py +++ b/tests/test_preset_router.py @@ -715,6 +715,114 @@ async def test_create_from_prompt_stores_repos_in_preset_metadata( ], } + async def test_create_from_prompt_stores_template_provenance(self, async_client): + """Template provenance is stored verbatim and returned to the client.""" + payload = { + "name": "Provenance Test", + "prompt": "Summarize open PRs", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": { + "id": "github-pr-reviewer", + "version": "1.0.0", + "config": {"reviewTone": "thorough"}, + }, + } + + response = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + + assert response.status_code == 201 + assert response.json()["preset_metadata"]["template"] == { + "id": "github-pr-reviewer", + "version": "1.0.0", + "config": {"reviewTone": "thorough"}, + } + + async def test_create_from_prompt_honors_explicit_enabled_state(self, async_client): + """An automation can be created disabled instead of PATCHed afterwards.""" + payload = { + "name": "Starts Disabled", + "prompt": "Summarize open PRs", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "enabled": False, + } + + response = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + + assert response.status_code == 201 + assert response.json()["enabled"] is False + + async def test_create_from_prompt_with_known_template_returns_existing( + self, async_client + ): + """Enabling an already-enabled template returns the first automation, 200.""" + payload = { + "name": "Resolver", + "prompt": "Respond to mentions", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": {"id": "openhands-resolver", "version": "1.0.0"}, + } + first = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + assert first.status_code == 201 + + second = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + + assert second.status_code == 200 + assert second.json()["id"] == first.json()["id"] + listing = await async_client.get("/api/automation/v1") + assert listing.json()["total"] == 1 + + async def test_create_from_prompt_rejects_oversized_template_config( + self, async_client + ): + """A template config over the serialized-size cap is a validation error.""" + payload = { + "name": "Oversized Config", + "prompt": "Summarize open PRs", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": { + "id": "big-template", + "version": "1.0.0", + "config": {"blob": "x" * 20_000}, + }, + } + + response = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + + assert response.status_code == 422 + + async def test_deleted_template_automation_does_not_block_reenabling( + self, async_client + ): + """After deleting a template automation, the template can be enabled again.""" + payload = { + "name": "Recreate Me", + "prompt": "Summarize open PRs", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": {"id": "pr-reviewer", "version": "1.0.0"}, + } + first = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + deleted = await async_client.delete(f"/api/automation/v1/{first.json()['id']}") + assert deleted.status_code == 204 + + second = await async_client.post( + "/api/automation/v1/preset/prompt", json=payload + ) + + assert second.status_code == 201 + assert second.json()["id"] != first.json()["id"] + async def test_create_from_prompt_defaults_to_active_model_profile( self, async_client, mock_authenticated_user ): @@ -1715,6 +1823,56 @@ async def test_create_from_plugin_stores_preset_metadata(self, async_client): "repos": [{"url": "owner/repo", "ref": "main", "provider": "github"}], } + async def test_create_from_plugin_stores_template_provenance(self, async_client): + """Plugin presets honor template provenance and explicit enabled state.""" + payload = { + "name": "Plugin Provenance", + "plugins": [{"source": "github:owner/plugin"}], + "prompt": "Run the plugin", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "enabled": False, + "template": {"id": "plugin-template", "version": "2.0.0"}, + } + + response = await async_client.post( + "/api/automation/v1/preset/plugin", json=payload + ) + + assert response.status_code == 201 + data = response.json() + assert data["preset_metadata"]["template"] == { + "id": "plugin-template", + "version": "2.0.0", + } + assert data["enabled"] is False + + async def test_create_from_plugin_dedupes_across_preset_kinds(self, async_client): + """A template automation is returned unchanged from either endpoint.""" + prompt_payload = { + "name": "Shared Template", + "prompt": "Respond to mentions", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": {"id": "shared-template", "version": "1.0.0"}, + } + first = await async_client.post( + "/api/automation/v1/preset/prompt", json=prompt_payload + ) + assert first.status_code == 201 + + plugin_payload = { + "name": "Shared Template Again", + "plugins": [{"source": "github:owner/plugin"}], + "prompt": "Run the plugin", + "trigger": {"type": "cron", "schedule": "0 9 * * 1"}, + "template": {"id": "shared-template", "version": "1.0.0"}, + } + second = await async_client.post( + "/api/automation/v1/preset/plugin", json=plugin_payload + ) + + assert second.status_code == 200 + assert second.json()["id"] == first.json()["id"] + async def test_create_from_plugin_defaults_to_active_model_profile( self, async_client, mock_authenticated_user ): diff --git a/tests/test_router.py b/tests/test_router.py index 2db0645a..6491eb43 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -1987,6 +1987,30 @@ async def _running_run(self, async_session): await async_session.commit() return run + async def _seed_running_run(self, async_session, preset_metadata): + """A RUNNING run on an automation carrying the given preset metadata.""" + from openhands.automation.models import AutomationRun, AutomationRunStatus + + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Template Automation", + trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run script.py", + preset_metadata=preset_metadata, + ) + async_session.add(automation) + await async_session.commit() + + run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.RUNNING, + ) + async_session.add(run) + await async_session.commit() + return automation, run + async def test_complete_run_saves_cost(self, async_client, async_session): """Complete endpoint stores the accumulated LLM cost reported by the SDK.""" run = await self._running_run(async_session) @@ -2031,6 +2055,124 @@ async def test_complete_run_without_cost_leaves_it_unset( await async_session.refresh(run) assert run.cost is None + async def test_first_completed_run_records_success_outcome( + self, async_client, async_session + ): + """The first completed run stamps a one-time success outcome.""" + automation, run = await self._seed_running_run( + async_session, + { + "preset_type": "prompt", + "prompt": "p", + "template": {"id": "tpl", "version": "1.2.0"}, + }, + ) + + response = await async_client.post( + f"/api/automation/v1/runs/{run.id}/complete", + json={"status": "COMPLETED"}, + ) + + assert response.status_code == 200 + await async_session.refresh(automation) + metadata = automation.preset_metadata + assert metadata is not None + first_run = metadata["first_run"] + assert first_run["status"] == "success" + assert first_run["failure_stage"] is None + assert first_run["template_version"] == "1.2.0" + assert first_run["recorded_at"] + + async def test_first_failed_run_records_execution_failure_stage( + self, async_client, async_session + ): + """A first-run failure records the stage, and nothing sensitive.""" + automation, run = await self._seed_running_run( + async_session, + { + "preset_type": "prompt", + "prompt": "p", + "template": {"id": "tpl", "version": "1.2.0"}, + }, + ) + + response = await async_client.post( + f"/api/automation/v1/runs/{run.id}/complete", + json={"status": "FAILED", "error": "secret stack trace"}, + ) + + assert response.status_code == 200 + await async_session.refresh(automation) + metadata = automation.preset_metadata + assert metadata is not None + first_run = metadata["first_run"] + assert first_run["status"] == "failure" + assert first_run["failure_stage"] == "execution" + # The record carries no error text or prompt by construction. + assert set(first_run) == { + "status", + "failure_stage", + "template_version", + "recorded_at", + } + + async def test_first_run_outcome_is_not_overwritten_by_later_runs( + self, async_client, async_session + ): + """Only the first terminal run records; later outcomes leave it alone.""" + from openhands.automation.models import AutomationRun, AutomationRunStatus + + automation, run = await self._seed_running_run( + async_session, + { + "preset_type": "prompt", + "prompt": "p", + "template": {"id": "tpl", "version": "1.2.0"}, + }, + ) + first = await async_client.post( + f"/api/automation/v1/runs/{run.id}/complete", + json={"status": "FAILED", "error": "boom"}, + ) + assert first.status_code == 200 + second_run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.RUNNING, + ) + async_session.add(second_run) + await async_session.commit() + + second = await async_client.post( + f"/api/automation/v1/runs/{second_run.id}/complete", + json={"status": "COMPLETED"}, + ) + + assert second.status_code == 200 + await async_session.refresh(automation) + metadata = automation.preset_metadata + assert metadata is not None + assert metadata["first_run"]["status"] == "failure" + + async def test_run_completion_without_template_records_no_outcome( + self, async_client, async_session + ): + """Automations without template provenance never record a first run.""" + automation, run = await self._seed_running_run( + async_session, + {"preset_type": "prompt", "prompt": "p"}, + ) + + response = await async_client.post( + f"/api/automation/v1/runs/{run.id}/complete", + json={"status": "COMPLETED"}, + ) + + assert response.status_code == 200 + await async_session.refresh(automation) + metadata = automation.preset_metadata + assert metadata is not None + assert "first_run" not in metadata + class TestDownloadTarball: """Tests for GET /{automation_id}/tarball endpoint.""" diff --git a/tests/test_watchdog.py b/tests/test_watchdog.py index 1ade9d37..ddaca860 100644 --- a/tests/test_watchdog.py +++ b/tests/test_watchdog.py @@ -282,6 +282,71 @@ async def test_exit_code_127_marks_failed_without_timeout( assert "Timed out" not in run.error_detail +class TestVerifyAndMarkRunFirstRunOutcome: + """First-run outcome recording when the watchdog terminates a run.""" + + @pytest.mark.asyncio + async def test_watchdog_failure_records_watchdog_stage( + self, async_session_factory, mock_settings + ): + """A stale template run failed by the watchdog records its stage.""" + async with async_session_factory() as session: + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Template Automation", + trigger={"type": "cron", "schedule": "* * * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run main.py", + enabled=True, + timeout=60, + preset_metadata={ + "preset_type": "prompt", + "prompt": "p", + "template": {"id": "tpl", "version": "1.0.0"}, + }, + ) + session.add(automation) + await session.commit() + automation_id = automation.id + + now = utcnow() + run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.RUNNING, + sandbox_id="test-sandbox-123", + started_at=now - timedelta(minutes=5), + timeout_at=now - timedelta(minutes=1), + ) + session.add(run) + await session.commit() + run_id = run.id + + verification = VerificationResult( + verified=True, + success=False, + exit_code=3, + stdout="", + stderr="boom", + ) + mock_backend = _create_mock_backend(verification) + + with patch( + "openhands.automation.watchdog.get_backend", return_value=mock_backend + ): + async with async_session_factory() as session: + run = await session.get(AutomationRun, run_id) + result = await _verify_and_mark_run(session, run, mock_settings) + await session.commit() + + assert result is True + async with async_session_factory() as session: + automation = await session.get(Automation, automation_id) + first_run = automation.preset_metadata["first_run"] + assert first_run["status"] == "failure" + assert first_run["failure_stage"] == "watchdog" + + class TestVerifyAndMarkRunVerificationFailed: """Tests for _verify_and_mark_run when verification fails."""