diff --git a/.gitignore b/.gitignore index 54f559dd..2a9f4275 100644 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,9 @@ yarn-error.log* logs +# PR artifacts / logs +.pr/*.log + # agent .envrc cache diff --git a/.pr/test_automation_run1.log b/.pr/test_automation_run1.log new file mode 100644 index 00000000..a7a3ab88 --- /dev/null +++ b/.pr/test_automation_run1.log @@ -0,0 +1,554 @@ +2026-03-23 15:10:47,637 INFO API URL: https://dispatch-phase1b.staging.all-hands.dev +2026-03-23 15:10:47,637 INFO Tarball dir: /workspace/automation/scripts/test_tarball +2026-03-23 15:10:47,637 INFO Entrypoint: python main.py +2026-03-23 15:10:47,639 INFO Built tarball from /workspace/automation/scripts/test_tarball (2354 bytes, 2 files: ['main.py', 'setup.sh']) +2026-03-23 15:10:48,892 INFO HTTP Request: POST https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes "HTTP/1.1 200 OK" +2026-03-23 15:10:48,893 INFO Created sandbox aXT6XM0L77Hj6Fu3zeQiH +2026-03-23 15:10:49,158 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:10:54,398 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:10:59,636 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:11:05,107 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:11:10,333 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:11:15,679 INFO HTTP Request: GET https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes?id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:11:15,679 INFO Sandbox aXT6XM0L77Hj6Fu3zeQiH ready at https://gbppewzgzipcfbpt.staging-runtime.all-hands.dev +2026-03-23 15:11:15,733 INFO HTTP Request: POST https://gbppewzgzipcfbpt.staging-runtime.all-hands.dev/api/file/upload//tmp/automation.tar.gz "HTTP/1.1 200 OK" +2026-03-23 15:12:49,056 INFO HTTP Request: POST https://gbppewzgzipcfbpt.staging-runtime.all-hands.dev/api/bash/execute_bash_command "HTTP/1.1 200 OK" +2026-03-23 15:12:49,718 INFO HTTP Request: DELETE https://dispatch-phase1b.staging.all-hands.dev/api/v1/sandboxes/aXT6XM0L77Hj6Fu3zeQiH?sandbox_id=aXT6XM0L77Hj6Fu3zeQiH "HTTP/1.1 200 OK" +2026-03-23 15:12:49,719 INFO Deleted sandbox aXT6XM0L77Hj6Fu3zeQiH +2026-03-23 15:12:49,719 INFO === RESULT === +2026-03-23 15:12:49,719 INFO success: True +2026-03-23 15:12:49,719 INFO sandbox_id: aXT6XM0L77Hj6Fu3zeQiH +2026-03-23 15:12:49,719 INFO exit_code: 0 +2026-03-23 15:12:49,719 INFO --- stdout --- +2026-03-23 15:12:49,719 INFO [setup] installing openhands SDK (feat/saas-runtime-mode) +2026-03-23 15:12:49,719 INFO [setup] done +2026-03-23 15:12:49,719 INFO === ENV VARS === +2026-03-23 15:12:49,719 INFO OPENHANDS_API_KEY: OK +2026-03-23 15:12:49,719 INFO OPENHANDS_CLOUD_API_URL: OK +2026-03-23 15:12:49,719 INFO SANDBOX_ID: OK +2026-03-23 15:12:49,719 INFO SESSION_API_KEY: OK +2026-03-23 15:12:49,719 INFO AUTOMATION_CALLBACK_URL: https://example.com/callback +2026-03-23 15:12:49,719 INFO AUTOMATION_RUN_ID: test-run-001 +2026-03-23 15:12:49,719 INFO +2026-03-23 15:12:49,719 INFO === SDK WORKSPACE === +2026-03-23 15:12:49,719 INFO +2026-03-23 15:12:49,719 INFO === GET_LLM === +2026-03-23 15:12:49,719 INFO model: litellm_proxy/minimax-m2.5 +2026-03-23 15:12:49,719 INFO api_key present: True +2026-03-23 15:12:49,719 INFO +2026-03-23 15:12:49,719 INFO === GET_SECRETS === +2026-03-23 15:12:49,719 INFO available: ['github_token'] +2026-03-23 15:12:49,719 INFO +2026-03-23 15:12:49,719 INFO === CONVERSATION === +2026-03-23 15:12:49,720 INFO conversation created: RemoteConversation +2026-03-23 15:12:49,720 INFO injected 1 secrets into conversation +2026-03-23 15:12:49,720 INFO sending prompt: For each of these environment variables: $github_token — print the variable name... +2026-03-23 15:12:49,720 INFO System Prompt ────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO System Prompt: +2026-03-23 15:12:49,720 INFO You are OpenHands agent, a helpful AI assistant that can interact with a +2026-03-23 15:12:49,720 INFO computer to solve tasks. +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO * Your primary role is to assist users by executing commands, modifying code, +2026-03-23 15:12:49,720 INFO and solving technical problems effectively. You should be thorough, methodical, +2026-03-23 15:12:49,720 INFO and prioritize quality over speed. +2026-03-23 15:12:49,720 INFO * If the user asks a question, like "why is X happening", don't try to fix the +2026-03-23 15:12:49,720 INFO problem. Just give an answer to the question. +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO * Use `AGENTS.md` under the repository root as your persistent memory for +2026-03-23 15:12:49,720 INFO repository-specific knowledge and context. +2026-03-23 15:12:49,720 INFO * Add important insights, patterns, and learnings to this file to improve future +2026-03-23 15:12:49,720 INFO task performance. +2026-03-23 15:12:49,720 INFO * This repository skill is automatically loaded for every conversation and helps +2026-03-23 15:12:49,720 INFO maintain context across sessions. +2026-03-23 15:12:49,720 INFO * For more information about skills, see: +2026-03-23 15:12:49,720 INFO https://docs.openhands.dev/overview/skills +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO * Each action you take is somewhat expensive. Wherever possible, combine +2026-03-23 15:12:49,720 INFO multiple actions into a single action, e.g. combine multiple bash commands into +2026-03-23 15:12:49,720 INFO one, using sed and grep to edit/view multiple files at once. +2026-03-23 15:12:49,720 INFO * When exploring the codebase, use efficient tools like find, grep, and git +2026-03-23 15:12:49,720 INFO commands with appropriate filters to minimize unnecessary operations. +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO * When a user provides a file path, do NOT assume it's relative to the current +2026-03-23 15:12:49,720 INFO working directory. First explore the file system to locate the file before +2026-03-23 15:12:49,720 INFO working on it. +2026-03-23 15:12:49,720 INFO * If asked to edit a file, edit the file directly, rather than creating a new +2026-03-23 15:12:49,720 INFO file with a different filename. +2026-03-23 15:12:49,720 INFO * For global search-and-replace operations, consider using `sed` instead of +2026-03-23 15:12:49,720 INFO opening file editors multiple times. +2026-03-23 15:12:49,720 INFO * NEVER create multiple versions of the same file with different suffixes (e.g., +2026-03-23 15:12:49,720 INFO file_test.py, file_fix.py, file_simple.py). Instead: +2026-03-23 15:12:49,720 INFO - Always modify the original file directly when making changes +2026-03-23 15:12:49,720 INFO - If you need to create a temporary file for testing, delete it once you've +2026-03-23 15:12:49,720 INFO confirmed your solution works +2026-03-23 15:12:49,720 INFO - If you decide a file you created is no longer useful, delete it instead of +2026-03-23 15:12:49,720 INFO creating a new version +2026-03-23 15:12:49,720 INFO * Do NOT include documentation files explaining your changes in version control +2026-03-23 15:12:49,720 INFO unless the user explicitly requests it +2026-03-23 15:12:49,720 INFO * When reproducing bugs or implementing fixes, use a single file rather than +2026-03-23 15:12:49,720 INFO creating multiple files with different versions +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO +2026-03-23 15:12:49,720 INFO * Write clean, efficient code with minimal comments. Avoid redundancy in +2026-03-23 15:12:49,720 INFO comments: Do not repeat information that can be easily inferred from the code +2026-03-23 15:12:49,720 INFO itself. +2026-03-23 15:12:49,720 INFO * When implementing solutions, focus on making the minimal changes needed to +2026-03-23 15:12:49,720 INFO solve the problem. +2026-03-23 15:12:49,720 INFO * Before implementing any changes, first thoroughly understand the codebase +2026-03-23 15:12:49,720 INFO through exploration. +2026-03-23 15:12:49,720 INFO * If you are adding a lot of code to a function or file, consider splitting the +2026-03-23 15:12:49,720 INFO function or file into smaller pieces when appropriate. +2026-03-23 15:12:49,720 INFO * Place all imports at the top of the file unless explicitly requested otherwise +2026-03-23 15:12:49,720 INFO or if placing imports at the top would cause issues (e.g., circular imports, +2026-03-23 15:12:49,721 INFO conditional imports, or imports that need to be delayed for specific reasons). +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO * If there are existing git user credentials already configured, use them and +2026-03-23 15:12:49,721 INFO add Co-authored-by: openhands to any commits messages +2026-03-23 15:12:49,721 INFO you make. if a git config doesn't exist use "openhands" as the user.name and +2026-03-23 15:12:49,721 INFO "openhands@all-hands.dev" as the user.email by default, unless explicitly +2026-03-23 15:12:49,721 INFO instructed otherwise. +2026-03-23 15:12:49,721 INFO * Exercise caution with git operations. Do NOT make potentially dangerous +2026-03-23 15:12:49,721 INFO changes (e.g., pushing to main, deleting repositories) unless explicitly asked +2026-03-23 15:12:49,721 INFO to do so. +2026-03-23 15:12:49,721 INFO * When committing changes, use `git status` to see all modified files, and stage +2026-03-23 15:12:49,721 INFO all files necessary for the commit. Use `git commit -a` whenever possible. +2026-03-23 15:12:49,721 INFO * Do NOT commit files that typically shouldn't go into version control (e.g., +2026-03-23 15:12:49,721 INFO node_modules/, .env files, build directories, cache files, large binaries) +2026-03-23 15:12:49,721 INFO unless explicitly instructed by the user. +2026-03-23 15:12:49,721 INFO * If unsure about committing certain files, check for the presence of .gitignore +2026-03-23 15:12:49,721 INFO files or ask the user for clarification. +2026-03-23 15:12:49,721 INFO * When running git commands that may produce paged output (e.g., `git diff`, +2026-03-23 15:12:49,721 INFO `git log`, `git show`), use `git --no-pager ` or set `GIT_PAGER=cat` to +2026-03-23 15:12:49,721 INFO prevent the command from getting stuck waiting for interactive input. +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO * **Important**: Do not push to the remote branch and/or start a pull request +2026-03-23 15:12:49,721 INFO unless explicitly asked to do so. +2026-03-23 15:12:49,721 INFO * When creating pull requests, create only ONE per session/issue unless +2026-03-23 15:12:49,721 INFO explicitly instructed otherwise. +2026-03-23 15:12:49,721 INFO * When working with an existing PR, update it with new commits rather than +2026-03-23 15:12:49,721 INFO creating additional PRs for the same issue. +2026-03-23 15:12:49,721 INFO * When updating a PR, preserve the original PR title and purpose, updating +2026-03-23 15:12:49,721 INFO description only when necessary. +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO 1. EXPLORATION: Thoroughly explore relevant files and understand the context +2026-03-23 15:12:49,721 INFO before proposing solutions +2026-03-23 15:12:49,721 INFO 2. ANALYSIS: Consider multiple approaches and select the most promising one +2026-03-23 15:12:49,721 INFO 3. TESTING: +2026-03-23 15:12:49,721 INFO * For bug fixes: Create tests to verify issues before implementing fixes +2026-03-23 15:12:49,721 INFO * For new features: Consider test-driven development when appropriate +2026-03-23 15:12:49,721 INFO * Do NOT write tests for documentation changes, README updates, configuration +2026-03-23 15:12:49,721 INFO files, or other non-functionality changes +2026-03-23 15:12:49,721 INFO * Do not use mocks in tests unless strictly necessary and justify their use +2026-03-23 15:12:49,721 INFO when they are used. You must always test real code paths in tests, NOT mocks. +2026-03-23 15:12:49,721 INFO * If the repository lacks testing infrastructure and implementing tests would +2026-03-23 15:12:49,721 INFO require extensive setup, consult with the user before investing time in building +2026-03-23 15:12:49,721 INFO testing infrastructure +2026-03-23 15:12:49,721 INFO * If the environment is not set up to run tests, consult with the user first +2026-03-23 15:12:49,721 INFO before investing time to install all dependencies +2026-03-23 15:12:49,721 INFO 4. IMPLEMENTATION: +2026-03-23 15:12:49,721 INFO * Make focused, minimal changes to address the problem +2026-03-23 15:12:49,721 INFO * Always modify existing files directly rather than creating new versions +2026-03-23 15:12:49,721 INFO with different suffixes +2026-03-23 15:12:49,721 INFO * If you create temporary files for testing, delete them after confirming +2026-03-23 15:12:49,721 INFO your solution works +2026-03-23 15:12:49,721 INFO 5. VERIFICATION: If the environment is set up to run tests, test your +2026-03-23 15:12:49,721 INFO implementation thoroughly, including edge cases. If the environment is not set +2026-03-23 15:12:49,721 INFO up to run tests, consult with the user first before investing time to run tests. +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO When the user directly asks about any of the following: +2026-03-23 15:12:49,721 INFO - OpenHands capabilities (e.g., "can OpenHands do...", "does OpenHands have...") +2026-03-23 15:12:49,721 INFO - what you're able to do in second person (e.g., "are you able...", "can +2026-03-23 15:12:49,721 INFO you...") +2026-03-23 15:12:49,721 INFO - how to use a specific OpenHands feature or product +2026-03-23 15:12:49,721 INFO - how to use the OpenHands SDK, CLI, GUI, or other OpenHands products +2026-03-23 15:12:49,721 INFO +2026-03-23 15:12:49,721 INFO Get accurate information from the official OpenHands documentation at +2026-03-23 15:12:49,722 INFO . The documentation includes: +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO **OpenHands SDK** (`/sdk/*`): Python library for building AI agents; Getting +2026-03-23 15:12:49,722 INFO Started, Architecture, Guides (agent, llm, conversation, tools), API Reference +2026-03-23 15:12:49,722 INFO **OpenHands CLI** (`/openhands/usage/run-openhands/cli-mode`): Command-line +2026-03-23 15:12:49,722 INFO interface +2026-03-23 15:12:49,722 INFO **OpenHands GUI** (`/openhands/usage/run-openhands/local-setup`): Local GUI and +2026-03-23 15:12:49,722 INFO REST API +2026-03-23 15:12:49,722 INFO **OpenHands Cloud** (`/openhands/usage/run-openhands/cloud`): Hosted solution +2026-03-23 15:12:49,722 INFO with integrations +2026-03-23 15:12:49,722 INFO **OpenHands Enterprise**: Self-hosted deployment with extended support +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO Always provide links to the relevant documentation pages for users who want to +2026-03-23 15:12:49,722 INFO learn more. +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO # 🔐 Security Policy +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO ## OK to do without Explicit User Consent +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO - Download and run code from a repository specified by a user +2026-03-23 15:12:49,722 INFO - Open pull requests on the original repositories where the code is stored +2026-03-23 15:12:49,722 INFO - Install and run popular packages from pypi, npm, or other package managers +2026-03-23 15:12:49,722 INFO - Use APIs to work with GitHub or other platforms, unless the user asks +2026-03-23 15:12:49,722 INFO otherwise or your task requires browsing +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO ## Do only with Explicit User Consent +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO - Upload code to anywhere other than the location where it was obtained from +2026-03-23 15:12:49,722 INFO - Upload API keys or tokens anywhere, except when using them to authenticate +2026-03-23 15:12:49,722 INFO with the appropriate service +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO ## Never Do +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO - Never perform any illegal activities, such as circumventing security to access +2026-03-23 15:12:49,722 INFO a system that is not under your control or performing denial-of-service attacks +2026-03-23 15:12:49,722 INFO on external servers +2026-03-23 15:12:49,722 INFO - Never run software to mine cryptocurrency +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO ## General Security Guidelines +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO - Only use GITHUB_TOKEN and other credentials in ways the user has explicitly +2026-03-23 15:12:49,722 INFO requested and would expect +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO # Security Risk Policy +2026-03-23 15:12:49,722 INFO When using tools that support the security_risk parameter, assess the safety +2026-03-23 15:12:49,722 INFO risk of your actions: +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO - **LOW**: Safe, read-only actions. +2026-03-23 15:12:49,722 INFO - Viewing/summarizing content, reading project files, simple in-memory +2026-03-23 15:12:49,722 INFO calculations. +2026-03-23 15:12:49,722 INFO - **MEDIUM**: Project-scoped edits or execution. +2026-03-23 15:12:49,722 INFO - Modify user project files, run project scripts/tests, install project-local +2026-03-23 15:12:49,722 INFO packages. +2026-03-23 15:12:49,722 INFO - **HIGH**: System-level or untrusted operations. +2026-03-23 15:12:49,722 INFO - Changing system settings, global installs, elevated (`sudo`) commands, +2026-03-23 15:12:49,722 INFO deleting critical files, downloading & executing untrusted code, or sending +2026-03-23 15:12:49,722 INFO local secrets/data out. +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO **Global Rules** +2026-03-23 15:12:49,722 INFO - Always escalate to **HIGH** if sensitive data leaves the environment. +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,722 INFO +2026-03-23 15:12:49,723 INFO * When interacting with external services like GitHub, GitLab, or Bitbucket, use +2026-03-23 15:12:49,723 INFO their respective APIs instead of browser-based interactions whenever possible. +2026-03-23 15:12:49,723 INFO * Only resort to browser-based interactions with these services if specifically +2026-03-23 15:12:49,723 INFO requested by the user or if the required operation cannot be performed via API. +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO * When user asks you to run an application, don't stop if the application is not +2026-03-23 15:12:49,723 INFO installed. Instead, please install the application and run the command again. +2026-03-23 15:12:49,723 INFO * If you encounter missing dependencies: +2026-03-23 15:12:49,723 INFO 1. First, look around in the repository for existing dependency files +2026-03-23 15:12:49,723 INFO (requirements.txt, pyproject.toml, package.json, Gemfile, etc.) +2026-03-23 15:12:49,723 INFO 2. If dependency files exist, use them to install all dependencies at once +2026-03-23 15:12:49,723 INFO (e.g., `pip install -r requirements.txt`, `npm install`, etc.) +2026-03-23 15:12:49,723 INFO 3. Only install individual packages directly if no dependency files are found +2026-03-23 15:12:49,723 INFO or if only specific packages are needed +2026-03-23 15:12:49,723 INFO * Similarly, if you encounter missing dependencies for essential tools requested +2026-03-23 15:12:49,723 INFO by the user, install them when possible. +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO * If you've made repeated attempts to solve a problem but tests still fail or +2026-03-23 15:12:49,723 INFO the user reports it's still broken: +2026-03-23 15:12:49,723 INFO 1. Step back and reflect on 5-7 different possible sources of the problem +2026-03-23 15:12:49,723 INFO 2. Assess the likelihood of each possible cause +2026-03-23 15:12:49,723 INFO 3. Methodically address the most likely causes, starting with the highest +2026-03-23 15:12:49,723 INFO probability +2026-03-23 15:12:49,723 INFO 4. Explain your reasoning process in your response to the user +2026-03-23 15:12:49,723 INFO * When you run into any major issue while executing a plan from the user, please +2026-03-23 15:12:49,723 INFO don't try to directly work around it. Instead, propose a new plan and confirm +2026-03-23 15:12:49,723 INFO with the user before proceeding. +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO * When terminating processes: +2026-03-23 15:12:49,723 INFO - Do NOT use general keywords with commands like `pkill -f server` or `pkill +2026-03-23 15:12:49,723 INFO -f python` as this might accidentally kill other important servers or processes +2026-03-23 15:12:49,723 INFO - Always use specific keywords that uniquely identify the target process +2026-03-23 15:12:49,723 INFO - Prefer using `ps aux` to find the exact process ID (PID) first, then kill +2026-03-23 15:12:49,723 INFO that specific PID +2026-03-23 15:12:49,723 INFO - When possible, use more targeted approaches like finding the PID from a +2026-03-23 15:12:49,723 INFO pidfile or using application-specific shutdown commands +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO Dynamic Context: +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO The current date and time is: 2026-03-23T15:12:03.830675 +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO +2026-03-23 15:12:49,723 INFO ### Credential Access +2026-03-23 15:12:49,723 INFO * Automatic secret injection: When you reference a registered secret key in your +2026-03-23 15:12:49,723 INFO bash command, the secret value will be automatically exported as an environment +2026-03-23 15:12:49,723 INFO variable before your command executes. +2026-03-23 15:12:49,723 INFO * How to use secrets: Simply reference the secret key in your command (e.g., +2026-03-23 15:12:49,723 INFO `curl -H "Authorization: Bearer $API_KEY" https://api.example.com`). The system +2026-03-23 15:12:49,723 INFO will detect the key name in your command text and export it as environment +2026-03-23 15:12:49,723 INFO variable before it executes your command. +2026-03-23 15:12:49,723 INFO * Secret detection: The system performs case-insensitive matching to find secret +2026-03-23 15:12:49,723 INFO keys in your command text. If a registered secret key appears anywhere in your +2026-03-23 15:12:49,723 INFO command, its value will be made available as an environment variable. +2026-03-23 15:12:49,723 INFO * Security: Secret values are automatically masked in command output to prevent +2026-03-23 15:12:49,723 INFO accidental exposure. You will see `` instead of the actual secret +2026-03-23 15:12:49,723 INFO value in the output. +2026-03-23 15:12:49,723 INFO * Avoid exposing raw secrets: Never echo or print the full value of secrets +2026-03-23 15:12:49,723 INFO (e.g., avoid `echo $SECRET`). The conversation history may be logged or shared, +2026-03-23 15:12:49,723 INFO and exposing raw secret values could compromise security. Instead, use secrets +2026-03-23 15:12:49,724 INFO directly in commands where they serve their intended purpose (e.g., in curl +2026-03-23 15:12:49,724 INFO headers or git URLs). +2026-03-23 15:12:49,724 INFO * Refreshing expired secrets: Some secrets (like GITHUB_TOKEN) may be updated +2026-03-23 15:12:49,724 INFO periodically or expire over time. If a secret stops working (e.g., +2026-03-23 15:12:49,724 INFO authentication failures), try using it again in a new command - the system +2026-03-23 15:12:49,724 INFO should automatically use the refreshed value. For example, if GITHUB_TOKEN was +2026-03-23 15:12:49,724 INFO used in a git remote URL and later expired, you can update the remote URL with +2026-03-23 15:12:49,724 INFO the current token: `git remote set-url origin +2026-03-23 15:12:49,724 INFO https://${GITHUB_TOKEN}@github.com/username/repo.git` to pick up the refreshed +2026-03-23 15:12:49,724 INFO token value. +2026-03-23 15:12:49,724 INFO * If it still fails, report it to the user. +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO You have access to the following environment variables +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO * **$github_token** - github_token provider token +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Tools Available: 5 +2026-03-23 15:12:49,724 INFO - terminal: Execute a bash command in the terminal within a persistent shell +2026-03-23 15:12:49,724 INFO session.... +2026-03-23 15:12:49,724 INFO Parameters: {"type": "object", "description": "Schema for bash command +2026-03-23 15:12:49,724 INFO execution.", "properties": {"command": {"type": "string", "description": "The +2026-03-23 15:12:49,724 INFO bash command to execute. Can be empty string to view additio... +2026-03-23 15:12:49,724 INFO - file_editor: Custom editing tool for viewing, creating and editing files in +2026-03-23 15:12:49,724 INFO plain-text format... +2026-03-23 15:12:49,724 INFO Parameters: {"type": "object", "description": "Schema for file editor +2026-03-23 15:12:49,724 INFO operations.", "properties": {"command": {"type": "string", "description": "The +2026-03-23 15:12:49,724 INFO commands to run. Allowed options are: `view`, `create`, `str... +2026-03-23 15:12:49,724 INFO - task_tracker: This tool provides structured task management capabilities for +2026-03-23 15:12:49,724 INFO development workflows.... +2026-03-23 15:12:49,724 INFO Parameters: {"type": "object", "description": "An action where the agent +2026-03-23 15:12:49,724 INFO writes or updates a task list for task management.", "properties": {"command": +2026-03-23 15:12:49,724 INFO {"type": "string", "description": "The command to execute... +2026-03-23 15:12:49,724 INFO - finish: Signals the completion of the current task or conversation.... +2026-03-23 15:12:49,724 INFO Parameters: {"type": "object", "properties": {"message": {"type": "string", +2026-03-23 15:12:49,724 INFO "description": "Final message to send to the user."}}, "required": ["message"]} +2026-03-23 15:12:49,724 INFO - think: Use the tool to think about something. It will not obtain new +2026-03-23 15:12:49,724 INFO information or make any changes to the... +2026-03-23 15:12:49,724 INFO Parameters: {"type": "object", "description": "Action for logging a thought +2026-03-23 15:12:49,724 INFO without making any changes.", "properties": {"thought": {"type": "string", +2026-03-23 15:12:49,724 INFO "description": "The thought to log."}}, "required": ["thou... +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Message from User ────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO For each of these environment variables: $github_token — print the variable name +2026-03-23 15:12:49,724 INFO and the LAST 50% of its value (i.e. the second half of the string). Then write a +2026-03-23 15:12:49,724 INFO short summary into SECRETS_CHECK.txt. +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Agent Action ─────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Summary: Print github_token name and last 50% of value +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Reasoning: +2026-03-23 15:12:49,724 INFO The user wants me to: +2026-03-23 15:12:49,724 INFO 1. For the environment variable $github_token, print the variable name and the +2026-03-23 15:12:49,724 INFO last 50% of its value +2026-03-23 15:12:49,724 INFO 2. Write a summary into SECRETS_CHECK.txt +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Let me first get the value of the github_token variable. According to the +2026-03-23 15:12:49,724 INFO context, I have access to `$github_token` as a custom secret. +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Let me check the value - but I need to be careful not to expose the full secret. +2026-03-23 15:12:49,724 INFO The user specifically asked for the last 50% of the value, which is fine. +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Let me first check what the github_token value is. I can reference it in a +2026-03-23 15:12:49,724 INFO command and it will be exported as an environment variable. +2026-03-23 15:12:49,724 INFO +2026-03-23 15:12:49,724 INFO Thought: +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO $ echo "Variable name: github_token" +2026-03-23 15:12:49,725 INFO echo "Last 50% of value: ${github_token: -${#github_token}/2}" +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Observation ──────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Tool: terminal +2026-03-23 15:12:49,725 INFO Result: +2026-03-23 15:12:49,725 INFO ❌ [An error occurred during execution.] +2026-03-23 15:12:49,725 INFO Cannot execute multiple commands at once. +2026-03-23 15:12:49,725 INFO Please run each command separately OR chain them into a single command via && or +2026-03-23 15:12:49,725 INFO ; +2026-03-23 15:12:49,725 INFO Provided commands: +2026-03-23 15:12:49,725 INFO (1) echo "Variable name: github_token" +2026-03-23 15:12:49,725 INFO (2) echo "Last 50% of value: ${github_token: -${#github_token}/2}" +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO ⏳ Process still running (soft timeout) +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Agent Action ─────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Summary: Print github_token name and last 50% of value +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Reasoning: +2026-03-23 15:12:49,725 INFO I need to run these commands separately or combine them. Let me combine them +2026-03-23 15:12:49,725 INFO into a single command using &&. +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Thought: +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO $ echo "Variable name: github_token" && echo "Last 50% of value: ${github_token: +2026-03-23 15:12:49,725 INFO -${#github_token}/2}" +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Observation ──────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Tool: terminal +2026-03-23 15:12:49,725 INFO Result: +2026-03-23 15:12:49,725 INFO Variable name: github_token +2026-03-23 15:12:49,725 INFO Last 50% of value: wTEu9HF9YGZRE04dMc5x +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO 📁 Working directory: /workspace/project +2026-03-23 15:12:49,725 INFO 🐍 Python interpreter: /usr/local/bin/python +2026-03-23 15:12:49,725 INFO ✅ Exit code: 0 +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Observation ──────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Tool: file_editor +2026-03-23 15:12:49,725 INFO Result: +2026-03-23 15:12:49,725 INFO [File /workspace/project/SECRETS_CHECK.txt edited with 1 changes.] +2026-03-23 15:12:49,725 INFO [begin of edit 1 / 1] +2026-03-23 15:12:49,725 INFO (content before edit) +2026-03-23 15:12:49,725 INFO -1| +2026-03-23 15:12:49,725 INFO (content after edit) +2026-03-23 15:12:49,725 INFO +1|github_token - Last 50%: wTEu9HF9YGZRE04dMc5x +2026-03-23 15:12:49,725 INFO [end of edit 1 / 1] +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Agent Action ─────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Summary: Write secrets check summary to file +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,725 INFO Reasoning: +2026-03-23 15:12:49,725 INFO I got the last 50% of the github_token value: wTEu9HF9YGZRE04dMc5x +2026-03-23 15:12:49,725 INFO +2026-03-23 15:12:49,726 INFO Now I need to write this to a file called SECRETS_CHECK.txt. +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Thought: +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Action: FileEditorAction +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Arguments: +2026-03-23 15:12:49,726 INFO command: "create" +2026-03-23 15:12:49,726 INFO path: "/workspace/project/SECRETS_CHECK.txt" +2026-03-23 15:12:49,726 INFO file_text: "github_token - Last 50%: wTEu9HF9YGZRE04dMc5x" +2026-03-23 15:12:49,726 INFO kind: "FileEditorAction" +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Agent Action ─────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Summary: file_editor: {"command": "view", "path": +2026-03-23 15:12:49,726 INFO "/workspace/project/SECRETS_CHECK.txt"} +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Reasoning: +2026-03-23 15:12:49,726 INFO I've successfully: +2026-03-23 15:12:49,726 INFO 1. Printed the variable name (github_token) +2026-03-23 15:12:49,726 INFO 2. Printed the last 50% of its value (wTEu9HF9YGZRE04dMc5x) +2026-03-23 15:12:49,726 INFO 3. Written this summary to SECRETS_CHECK.txt +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Let me confirm the file was created correctly. +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Thought: +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Action: FileEditorAction +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Arguments: +2026-03-23 15:12:49,726 INFO command: "view" +2026-03-23 15:12:49,726 INFO path: "/workspace/project/SECRETS_CHECK.txt" +2026-03-23 15:12:49,726 INFO kind: "FileEditorAction" +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Observation ──────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Tool: file_editor +2026-03-23 15:12:49,726 INFO Result: +2026-03-23 15:12:49,726 INFO Here's the result of running `cat -n` on /workspace/project/SECRETS_CHECK.txt: +2026-03-23 15:12:49,726 INFO 1 github_token - Last 50%: wTEu9HF9YGZRE04dMc5x +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Agent Action ─────────────────────────────────────────────────────────────────── +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Summary: Printed github_token last 50% and saved to file +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Reasoning: +2026-03-23 15:12:49,726 INFO I have successfully: +2026-03-23 15:12:49,726 INFO 1. Printed the variable name (github_token) and the last 50% of its value +2026-03-23 15:12:49,726 INFO (wTEu9HF9YGZRE04dMc5x) +2026-03-23 15:12:49,726 INFO 2. Written a summary to SECRETS_CHECK.txt +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Now I should finish the task. +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Thought: +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO +2026-03-23 15:12:49,726 INFO Finish with message: +2026-03-23 15:12:49,727 INFO Completed the task: +2026-03-23 15:12:49,727 INFO - Variable name: github_token +2026-03-23 15:12:49,727 INFO - Last 50% of value: wTEu9HF9YGZRE04dMc5x +2026-03-23 15:12:49,727 INFO - Summary written to /workspace/project/SECRETS_CHECK.txt +2026-03-23 15:12:49,727 INFO +2026-03-23 15:12:49,727 INFO Tokens: ↑ input 0 • cache hit N/A • ↓ output 0 • $ 0.00 +2026-03-23 15:12:49,727 INFO +2026-03-23 15:12:49,727 INFO cost: 0.0 +2026-03-23 15:12:49,727 INFO events received: 17 +2026-03-23 15:12:49,727 INFO conversation completed successfully +2026-03-23 15:12:49,727 INFO +2026-03-23 15:12:49,727 INFO === RESULT === +2026-03-23 15:12:49,727 INFO ALL_OK +2026-03-23 15:12:49,727 INFO --- stderr (last 500 chars) --- +2026-03-23 15:12:49,727 INFO nds.sdk.conversation.impl.remote_conversation", "filename": "remote_conversation.py", "lineno": 1041, "message": "Run completed via WebSocket notification (status: finished, elapsed: 36.1s)"} +2026-03-23 15:12:49,727 INFO {"asctime": "2026-03-23 15:12:48,513", "levelname": "WARNING", "name": "openhands.workspace.cloud.workspace", "filename": "workspace.py", "lineno": 699, "message": "Completion callback failed: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1032)"} +2026-03-23 15:12:49,727 INFO PASS +2026-03-23 15:12:49,727 INFO Total time: 122.1s diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..fd698465 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,126 @@ +# Automations Service + +Self-contained microservice that schedules and dispatches automation runs inside OpenHands Cloud sandboxes. + +## Repository Structure + +``` +automation/ +├── automation/ # Main application package +│ ├── app.py # FastAPI app, lifespan, background tasks +│ ├── auth.py # API key auth via OpenHands /api/keys/current +│ ├── config.py # Pydantic settings (Settings, env prefix AUTOMATION_) +│ ├── constants.py # Timeouts, polling intervals, sandbox constants +│ ├── db.py # Database engine and session factory (asyncpg / Cloud SQL) +│ ├── dispatcher.py # Polls PENDING runs, dispatches to sandbox (fire-and-forget) +│ ├── execution.py # Sandbox lifecycle: create → upload → execute → delete +│ ├── logger.py # JSON structured logging configuration +│ ├── models.py # SQLAlchemy models (Automation, AutomationRun, TarballUpload) +│ ├── router.py # API routes (CRUD, trigger, callback, runs list) +│ ├── scheduler.py # Cron scheduler — polls automations, creates PENDING runs +│ ├── schemas.py # Pydantic request/response schemas +│ ├── uploads.py # Tarball upload router +│ ├── watchdog.py # Staleness watchdog — marks hung runs as FAILED +│ ├── storage/ # File storage abstraction +│ │ ├── file_store.py # Abstract base class for file storage +│ │ └── google_cloud.py # GCS implementation +│ └── utils/ # Utility modules +│ ├── api_key.py # Per-user API key minting via service key +│ ├── cron.py # Cron schedule utilities (next/prev fire time) +│ ├── run.py # Run status transitions (create, mark, update) +│ ├── sandbox.py # Sandbox verification and cleanup +│ ├── tarball_validation.py # Tarball path validation (internal/external) +│ └── time.py # UTC time helpers +├── containers/ +│ └── Dockerfile # Container image definition +├── migrations/ # Alembic migrations +├── scripts/ +│ ├── test_automation.py # E2E test (sandbox lifecycle with live streaming) +│ └── test_tarball/ # Tarball contents uploaded to sandbox during test +│ ├── main.py # Test script run inside sandbox (SDK workspace test) +│ └── setup.sh # Installs SDK inside sandbox +├── tests/ # Unit tests (flat structure, no external deps) +│ ├── integration/ # Integration tests (require OPENHANDS_API_KEY) +│ ├── test_auth.py +│ ├── test_dispatcher.py +│ ├── test_execution.py +│ ├── test_router.py +│ ├── test_scheduler.py +│ └── ... +└── pyproject.toml +``` + +## Cross-Repo Coordination + +Three repos work together: + +| Repo | Branch | Purpose | +|------|--------|---------| +| `OpenHands/automation` | `dispatch-phase1b` | Automation service (this repo) | +| `OpenHands/deploy` (aka `All-Hands-AI/deploy`) | `dispatch-phase1b` | Deploys automation as a sidecar | +| `OpenHands/software-agent-sdk` | `feat/saas-runtime-mode` | SDK changes for in-sandbox execution | + +**AUTOMATION_SHA linking**: The deploy repo references a specific automation commit in two workflow files: +- `.github/workflows/deploy.yaml` → `AUTOMATION_SHA: ""` +- `.github/workflows/deploy-automation.yaml` → `AUTOMATION_SHA: ""` + +After pushing to the automation repo, update both files in the deploy repo. + +## Build & Test Commands + +```bash +# Pre-commit (run from repo root) +pre-commit run --files automation/**/*.py scripts/**/*.py tests/**/*.py --show-diff-on-failure + +# Unit tests (no external deps, skips Docker-dependent tests) +uv run pytest tests/ -v --ignore=tests/integration + +# Integration test (requires OPENHANDS_API_KEY) +OPENHANDS_API_KEY=sk-oh-... uv run pytest tests/integration/ -v + +# E2E test script (live sandbox, ~80s) +OPENHANDS_API_KEY=sk-oh-... uv run python scripts/test_automation.py --api-url https://staging.all-hands.dev +``` + +## Dispatch Pipeline + +The dispatcher uses a **fire-and-forget** model. For each PENDING run: + +1. **Fetch per-user API key** — `get_api_key_for_automation_run()` mints a key via the service key +2. **Resolve tarball** — Internal (`oh-internal://`) downloads from GCS; external (HTTP) URLs are downloaded inside the sandbox +3. **Create sandbox** — `POST /api/v1/sandboxes` (Cloud API, Bearer token auth) +4. **Wait for RUNNING** — Poll `GET /api/v1/sandboxes?id=` until status=RUNNING +5. **Upload/download tarball** — `POST /api/file/upload/` (agent-server) or `curl` inside sandbox +6. **Start entrypoint** — `POST /api/bash/start_bash_command` (agent-server) + - Extracts tarball, runs setup.sh (if present), exports env vars, runs entrypoint +7. **Return immediately** — Dispatcher does not wait for completion + +Completion is handled asynchronously: +- **Happy path**: SDK inside sandbox POSTs to `POST /api/v1/automations/runs/{id}/complete` +- **Fallback**: Watchdog scans for runs past their `timeout_at` deadline, verifies status via sandbox bash history, and marks as COMPLETED or FAILED + +### Env Vars Injected Into Sandbox + +| Variable | Source | Purpose | +|----------|--------|---------| +| `OPENHANDS_API_KEY` | Per-user key issued via service key | SDK auth for get_llm()/get_secrets() | +| `OPENHANDS_CLOUD_API_URL` | Config (`openhands_api_base_url`) | Cloud API base URL | +| `SANDBOX_ID` | From sandbox creation response | SDK reads for settings API calls | +| `SESSION_API_KEY` | From sandbox creation response | SDK reads for settings API auth | +| `AUTOMATION_CALLBACK_URL` | Constructed by dispatcher | SDK posts completion status here | +| `AUTOMATION_RUN_ID` | Run ID | Included in callback payload | +| `AUTOMATION_EVENT_PAYLOAD` | Trigger context JSON | Available to user's script | + +The SDK's `OpenHandsCloudWorkspace(local_agent_server_mode=True)` reads `SANDBOX_ID`, `SESSION_API_KEY`, and `AGENT_SERVER_PORT` from env vars automatically. + +## Callback & Race Condition Handling + +- **Callback auth**: The completion endpoint (`/runs/{id}/complete`) uses standard API key auth — the per-user `OPENHANDS_API_KEY` passed into the sandbox is validated via `authenticate_request`, and ownership is verified against the run's parent automation. +- **Optimistic locking**: Both callback endpoint and watchdog use `UPDATE ... WHERE status = 'RUNNING'` and check `CursorResult.rowcount` to handle races. Returns 409 on conflict. +- **Sandbox cleanup**: On callback, sandbox is deleted in a fire-and-forget background task (unless `keep_alive=True`). On dispatch failure, the dispatcher deletes the sandbox immediately. + +## Database + +- **Engine**: SQLAlchemy async with asyncpg; supports direct PostgreSQL (`AUTOMATION_DB_HOST`, `AUTOMATION_DB_PORT`, etc.) or GCP Cloud SQL connector (`AUTOMATION_GCP_DB_INSTANCE`) +- **Migrations**: Alembic in `migrations/` directory +- **Locking patterns**: `FOR UPDATE SKIP LOCKED` in scheduler/dispatcher polling, optimistic `UPDATE WHERE status=X` for callback/watchdog diff --git a/automation/app.py b/automation/app.py index 79dfca73..cc020857 100644 --- a/automation/app.py +++ b/automation/app.py @@ -17,6 +17,7 @@ from automation.router import router from automation.scheduler import scheduler_loop from automation.uploads import router as uploads_router +from automation.watchdog import watchdog_loop logger = logging.getLogger("automation.app") @@ -61,9 +62,15 @@ async def lifespan(app: FastAPI): logger.info("Background scheduler started") # Dispatcher: picks up PENDING runs and dispatches them + if not settings.base_url: + logger.warning( + "AUTOMATION_BASE_URL not set — using localhost. " + "Sandboxes in the cloud won't be able to reach this URL." + ) dispatcher_task = asyncio.create_task( dispatcher_loop( app.state.session_factory, + settings=settings, interval_seconds=settings.dispatcher_interval_seconds, shutdown_event=shutdown_event, ) @@ -71,16 +78,28 @@ async def lifespan(app: FastAPI): app.state.dispatcher_task = dispatcher_task logger.info("Background dispatcher started") + # Watchdog: marks stale RUNNING runs as FAILED + watchdog_task = asyncio.create_task( + watchdog_loop( + app.state.session_factory, + settings=settings, + shutdown_event=shutdown_event, + ) + ) + app.state.watchdog_task = watchdog_task + logger.info("Background watchdog started") + yield # Shutdown logger.info("Shutting down background tasks...") shutdown_event.set() - # Wait for both tasks to exit gracefully + # Wait for all tasks to exit gracefully for task_name, task in [ ("scheduler", scheduler_task), ("dispatcher", dispatcher_task), + ("watchdog", watchdog_task), ]: try: await asyncio.wait_for(task, timeout=5.0) @@ -141,7 +160,7 @@ async def readiness(): await conn.execute(text("SELECT 1")) return {"status": "ready"} except Exception as e: - logger.error("Readiness check failed: %s", e) + logger.error("Readiness check failed: %s", e, exc_info=True) return JSONResponse( status_code=503, content={"status": "not_ready", "error": "database unavailable"}, diff --git a/automation/auth.py b/automation/auth.py index 689f32f2..f3dd76c2 100644 --- a/automation/auth.py +++ b/automation/auth.py @@ -7,11 +7,11 @@ import logging import uuid -from dataclasses import dataclass import httpx from cachetools import TTLCache from fastapi import Depends, HTTPException, Request, status +from pydantic.dataclasses import dataclass from tenacity import ( RetryCallState, before_sleep_log, diff --git a/automation/config.py b/automation/config.py index 9d59d51b..7857c158 100644 --- a/automation/config.py +++ b/automation/config.py @@ -31,8 +31,14 @@ class Settings(BaseSettings): # Dispatcher (polls automation_runs table for pending jobs) dispatcher_interval_seconds: int = 10 - # Admin API key for issuing per-user automation API keys via SaaS - admin_api_key: str = "" + # Service key for authenticating with the SaaS API to fetch per-user + # API keys (called by the dispatcher before each automation run). + service_key: str = "" + + # Public URL for the automation service (used for sandbox callbacks). + # In production, this is the ingress URL (e.g., https://automation.all-hands.dev). + # If empty, falls back to http://localhost:{server_port} (dev only). + base_url: str = "" # Service host: str = "0.0.0.0" @@ -46,6 +52,11 @@ class Settings(BaseSettings): model_config = {"env_prefix": "AUTOMATION_"} + @property + def resolved_base_url(self) -> str: + """Public base URL with localhost fallback for dev.""" + return self.base_url or f"http://localhost:{self.server_port}" + # Hardcoded internal URL scheme for uploaded tarballs. # This is not configurable - changing it would require a database migration diff --git a/automation/constants.py b/automation/constants.py new file mode 100644 index 00000000..b166c797 --- /dev/null +++ b/automation/constants.py @@ -0,0 +1,27 @@ +"""Constants for the automation service.""" + +from datetime import timedelta + + +# Maximum allowed timeout for automation runs (10 minutes) +# Used for: +# - Validation in API requests (timeout field) +# - Default timeout passed to sandbox execution +# - Watchdog staleness detection +MAX_RUN_DURATION = timedelta(minutes=10) +MAX_RUN_DURATION_SECONDS = int(MAX_RUN_DURATION.total_seconds()) + +# Sandbox execution constants +SANDBOX_POLL_INTERVAL = 5 # seconds between status checks +SANDBOX_READY_TIMEOUT = 300 # max wait for sandbox to become ready +WORK_DIR = "/workspace/automation" +TARBALL_PATH = "/tmp/automation.tar.gz" + +# Limits for external tarball downloads (in sandbox) +EXTERNAL_DOWNLOAD_TIMEOUT = 120 # seconds +EXTERNAL_MAX_FILESIZE = 100 * 1024 * 1024 # 100 MB + +# Rate limit retry settings +RATE_LIMIT_MIN_WAIT = 10 # initial wait after a 429 +RATE_LIMIT_MAX_WAIT = 60 # max wait between retries +RATE_LIMIT_MAX_RETRIES = 5 diff --git a/automation/dispatcher.py b/automation/dispatcher.py index 0ae6cfdc..a5d4799d 100644 --- a/automation/dispatcher.py +++ b/automation/dispatcher.py @@ -1,113 +1,288 @@ """Dispatcher for processing pending automation runs. Polls the automation_runs table for PENDING jobs and dispatches them -for execution. Uses the same database-specific strategies as the scheduler -for multi-worker safety. +to sandboxes via the SaaS API. Uses FOR UPDATE SKIP LOCKED for +multi-worker safety. + +Completion is handled asynchronously: the SDK running inside the sandbox +POSTs to ``/api/v1/automations/runs/{id}/complete`` when the entry-point +exits, so the dispatcher does **not** block waiting for results. """ import asyncio +import json import logging +import uuid +from typing import Any from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from sqlalchemy.orm import selectinload -from automation.models import AutomationRun, AutomationRunStatus -from automation.utils.run import mark_run_status +from automation.config import Settings +from automation.constants import MAX_RUN_DURATION_SECONDS +from automation.execution import dispatch_automation +from automation.models import AutomationRun, AutomationRunStatus, TarballUpload +from automation.utils.api_key import APIKeyError, get_api_key_for_automation_run +from automation.utils.run import mark_run_status, mark_run_terminal, update_sandbox_id +from automation.utils.tarball_validation import is_http_url, parse_internal_upload_id logger = logging.getLogger("automation.dispatcher") -# Default batch size for polling pending runs -DEFAULT_BATCH_SIZE = 10 -# Minimum interval between polling the same run (seconds) +def _run_extra( + run_id: str | None = None, + automation_id: str | None = None, + sandbox_id: str | None = None, +) -> dict[str, Any]: + """Build extra dict for structured logging with run/automation/sandbox IDs.""" + extra: dict[str, Any] = {} + if run_id: + extra["run_id"] = run_id + if automation_id: + extra["automation_id"] = automation_id + if sandbox_id: + extra["sandbox_id"] = sandbox_id + return extra + + +DEFAULT_BATCH_SIZE = 10 POLL_INTERVAL_SECONDS = 30 +async def _download_internal_tarball( + upload_id: uuid.UUID, + session: AsyncSession | None, +) -> bytes: + """Download a tarball from GCS using the TarballUpload record.""" + if session is None: + raise ValueError("Database session required to resolve oh-internal:// URLs") + + result = await session.execute( + select(TarballUpload).where(TarballUpload.id == upload_id) + ) + upload = result.scalars().first() + if upload is None: + raise FileNotFoundError(f"TarballUpload {upload_id} not found") + + from automation.storage import GoogleCloudFileStore + + store = GoogleCloudFileStore() + return store.read(upload.storage_path) + + async def _poll_pending_runs( session: AsyncSession, batch_size: int, ) -> list[AutomationRun]: """Poll pending runs using FOR UPDATE SKIP LOCKED. - This allows multiple workers to dispatch concurrently without - claiming the same runs. - - Args: - session: Database session - batch_size: Maximum number of runs to fetch - - Returns: - List of claimed pending runs + Eagerly loads the ``automation`` relationship so that ``user_id``, + ``org_id``, and tarball config are available for dispatch. """ select_query = ( select(AutomationRun) + .options(selectinload(AutomationRun.automation)) .where(AutomationRun.status == AutomationRunStatus.PENDING) .order_by(AutomationRun.created_at.asc()) .limit(batch_size) .with_for_update(skip_locked=True) ) - result = await session.execute(select_query) return list(result.scalars().all()) +async def _execute_run( + run: AutomationRun, + settings: Settings, + session_factory: async_sessionmaker[AsyncSession], +) -> None: + """Execute a single run in a background task (fire-and-forget). + + 1. Fetch a per-user API key from the SaaS service (on demand, never stored). + 2. Determine tarball source: + - Internal (oh-internal://): Download from GCS and upload to sandbox. + - External (http/https): Pass URL for direct download inside sandbox. + 3. Call ``dispatch_automation()`` to spin up a sandbox and start the entrypoint. + 4. Store sandbox_id on the run for later verification. + 5. If the sandbox fails to start, mark the run FAILED. + + The SDK inside the sandbox fires the completion callback on exit. + The watchdog will verify status via sandbox if the callback is missed. + """ + run_id = str(run.id) + automation = run.automation + automation_id = str(automation.id) + tarball_path = automation.tarball_path + + # Helper for consistent structured logging + def log_extra(sandbox_id: str | None = None) -> dict[str, Any]: + return _run_extra( + run_id=run_id, automation_id=automation_id, sandbox_id=sandbox_id + ) + + callback_url = ( + f"{settings.resolved_base_url.rstrip('/')}" + f"/api/v1/automations/runs/{run_id}/complete" + ) + + try: + # 1. Fetch a per-user API key from the SaaS service + api_key = await get_api_key_for_automation_run(run) + + # 2. Determine tarball source + tarball_source: bytes | str + if is_http_url(tarball_path): + # HTTP(S) URL: download directly inside sandbox (untrusted/large) + tarball_source = tarball_path + logger.info("HTTP URL tarball, will download in sandbox", extra=log_extra()) + else: + # Internal (oh-internal://): download from GCS, upload to sandbox + upload_id = parse_internal_upload_id(tarball_path) + if upload_id is None: + raise ValueError(f"Unsupported tarball_path: {tarball_path!r}") + + async with session_factory() as session: + tarball_source = await _download_internal_tarball(upload_id, session) + logger.info( + "Internal tarball downloaded (%d bytes)", + len(tarball_source), + extra=log_extra(), + ) + + # 3. Build env vars for the sandbox + env_vars = { + "OPENHANDS_API_KEY": api_key, + "OPENHANDS_CLOUD_API_URL": settings.openhands_api_base_url, + } + + # Trigger context so the SDK script knows *why* it was invoked + event_payload = { + "trigger": automation.trigger, + "automation_id": str(automation.id), + "automation_name": automation.name, + } + env_vars["AUTOMATION_EVENT_PAYLOAD"] = json.dumps(event_payload) + + # 4. Calculate effective timeout: use automation's timeout if set, + # capped at system maximum; otherwise use system default + if automation.timeout is not None: + effective_timeout = min(automation.timeout, MAX_RUN_DURATION_SECONDS) + else: + effective_timeout = MAX_RUN_DURATION_SECONDS + + # 5. Dispatch to sandbox (fire-and-forget) + result = await dispatch_automation( + api_url=settings.openhands_api_base_url, + api_key=api_key, + entrypoint=automation.entrypoint, + tarball_source=tarball_source, + env_vars=env_vars, + timeout=effective_timeout, + callback_url=callback_url, + run_id=run_id, + ) + + sandbox_extra = log_extra(sandbox_id=result.sandbox_id) + if result.success: + # Store sandbox_id for later verification by the watchdog + if result.sandbox_id: + await update_sandbox_id(session_factory, run.id, result.sandbox_id) + logger.info( + "Automation dispatched successfully, waiting for callback", + extra=sandbox_extra, + ) + # Don't mark as COMPLETED here - wait for the callback + else: + logger.warning( + "Sandbox dispatch failed: %s", + result.error, + extra=sandbox_extra, + ) + await mark_run_terminal( + session_factory, run, AutomationRunStatus.FAILED, result.error + ) + + except (APIKeyError, ValueError) as exc: + logger.error("Dispatch error: %s", exc, exc_info=True, extra=log_extra()) + await mark_run_terminal( + session_factory, run, AutomationRunStatus.FAILED, str(exc) + ) + except Exception: + logger.exception("Background execution failed", extra=log_extra()) + await mark_run_terminal( + session_factory, run, AutomationRunStatus.FAILED, "Internal error" + ) + + async def dispatch_pending_runs( session_factory: async_sessionmaker[AsyncSession], + settings: Settings, batch_size: int = DEFAULT_BATCH_SIZE, ) -> list[AutomationRun]: - """Poll for pending runs and mark them as started. - - Uses FOR UPDATE SKIP LOCKED for multi-worker safety, allowing - multiple dispatchers to run concurrently without claiming the - same runs. - - Args: - session_factory: SQLAlchemy async session factory - batch_size: Maximum number of runs to process per batch + """Poll for pending runs, mark RUNNING, and launch sandboxes. - Returns: - List of runs that were dispatched (marked as RUNNING) + Each run is dispatched as an ``asyncio.create_task`` so the + dispatcher loop is not blocked by long-running automations. """ async with session_factory() as session: pending_runs = await _poll_pending_runs(session, batch_size) dispatched_runs = [] - for run in pending_runs: + run_id = str(run.id) + automation_id = str(run.automation_id) if run.automation_id else None + extra = _run_extra(run_id=run_id, automation_id=automation_id) try: - # PHASE 1 LIMITATION: Runs are marked RUNNING but not executed. - # Phase 1b will integrate with OpenHands SaaS API to actually - # execute the user's tarball/entrypoint. For now, this is a - # CRUD API + scheduler queue only. - logger.info("Dispatching automation run %s", run.id) + logger.info("Dispatching automation run", extra=extra) await mark_run_status(session, run, AutomationRunStatus.RUNNING) dispatched_runs.append(run) - # TODO(Phase 1b): Call SaaS API to create conversation except Exception: - logger.exception("Failed to dispatch run %s", run.id) + logger.exception("Failed to dispatch run", extra=extra) - # Always commit to release row locks from FOR UPDATE SKIP LOCKED, - # even if no runs were dispatched await session.commit() + for run in dispatched_runs: + asyncio.create_task( + _execute_run_safe(run, settings, session_factory), + name=f"execute-run-{run.id}", + ) + return dispatched_runs +async def _execute_run_safe( + run: AutomationRun, + settings: Settings, + session_factory: async_sessionmaker[AsyncSession], +) -> None: + """Wrapper around ``_execute_run`` that never lets exceptions escape. + + ``asyncio.create_task`` silently swallows exceptions from background + tasks, so this wrapper ensures every failure is logged and the run is + marked FAILED. + """ + run_id = str(run.id) + automation_id = str(run.automation_id) if run.automation_id else None + extra = _run_extra(run_id=run_id, automation_id=automation_id) + try: + await _execute_run(run, settings, session_factory) + except Exception: + logger.exception("Background execution failed", extra=extra) + await mark_run_terminal( + session_factory, run, AutomationRunStatus.FAILED, "Internal error" + ) + + async def dispatcher_loop( session_factory: async_sessionmaker[AsyncSession], + settings: Settings, interval_seconds: int = POLL_INTERVAL_SECONDS, shutdown_event: asyncio.Event | None = None, batch_size: int = DEFAULT_BATCH_SIZE, ) -> None: - """Main dispatcher loop that polls for pending runs and dispatches them. - - Args: - session_factory: SQLAlchemy async session factory - interval_seconds: Polling interval in seconds - shutdown_event: Event to signal shutdown (for graceful stop) - batch_size: Maximum number of runs to process per batch - """ + """Main dispatcher loop — polls for pending runs and dispatches them.""" logger.info( "Dispatcher started, polling every %d seconds (batch_size=%d)", interval_seconds, @@ -115,36 +290,27 @@ async def dispatcher_loop( ) while True: - # Check for shutdown signal if shutdown_event is not None and shutdown_event.is_set(): logger.info("Dispatcher received shutdown signal, exiting") break try: dispatched = await dispatch_pending_runs( - session_factory, batch_size=batch_size + session_factory, settings=settings, batch_size=batch_size ) - if dispatched: logger.info("Dispatched %d run(s)", len(dispatched)) else: logger.debug("No pending runs to dispatch") - except Exception: logger.error("Error dispatching pending runs", exc_info=True) - # Wait for the next poll interval (or shutdown) if shutdown_event is not None: try: - await asyncio.wait_for( - shutdown_event.wait(), - timeout=interval_seconds, - ) - # If we get here, shutdown was signaled + await asyncio.wait_for(shutdown_event.wait(), timeout=interval_seconds) logger.info("Dispatcher received shutdown signal, exiting") break except TimeoutError: - # Normal timeout, continue polling pass else: await asyncio.sleep(interval_seconds) diff --git a/automation/execution.py b/automation/execution.py new file mode 100644 index 00000000..327988be --- /dev/null +++ b/automation/execution.py @@ -0,0 +1,541 @@ +"""Sandbox execution for automation runs. + +One function does the whole job: spin up a sandbox, upload a tarball, +extract it, run setup, run the entrypoint, tear down. +""" + +import asyncio +import io +import logging +import tarfile +from typing import Any + +import httpx +from pydantic.dataclasses import dataclass +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception, + stop_after_attempt, + wait_exponential, +) + +from automation.constants import ( + EXTERNAL_DOWNLOAD_TIMEOUT, + EXTERNAL_MAX_FILESIZE, + MAX_RUN_DURATION_SECONDS, + RATE_LIMIT_MAX_RETRIES, + RATE_LIMIT_MAX_WAIT, + RATE_LIMIT_MIN_WAIT, + SANDBOX_POLL_INTERVAL, + SANDBOX_READY_TIMEOUT, + TARBALL_PATH, + WORK_DIR, +) +from automation.utils.sandbox import delete_sandbox + + +logger = logging.getLogger(__name__) + + +def _is_rate_limit_error(exc: BaseException) -> bool: + """Check if exception is a 429 rate limit error.""" + if isinstance(exc, httpx.HTTPStatusError): + return exc.response.status_code == 429 + return False + + +def _log_extra( + run_id: str | None = None, sandbox_id: str | None = None +) -> dict[str, Any]: + """Build extra dict for structured logging with run/sandbox IDs.""" + extra: dict[str, Any] = {} + if run_id: + extra["run_id"] = run_id + if sandbox_id: + extra["sandbox_id"] = sandbox_id + return extra + + +# Tenacity retry decorator for rate limit handling +_retry_on_rate_limit = retry( + retry=retry_if_exception(_is_rate_limit_error), + stop=stop_after_attempt(RATE_LIMIT_MAX_RETRIES), + wait=wait_exponential(min=RATE_LIMIT_MIN_WAIT, max=RATE_LIMIT_MAX_WAIT), + before_sleep=before_sleep_log(logger, logging.WARNING), + reraise=True, +) + + +def build_tarball(files: dict[str, str | bytes]) -> bytes: + """Build a .tar.gz in memory from ``{relative_path: content}``.""" + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for name, content in files.items(): + data = content.encode() if isinstance(content, str) else content + info = tarfile.TarInfo(name=name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + return buf.getvalue() + + +# -- Sandbox helpers (private) ------------------------------------------------ + + +def _find_agent_server_url(sandbox: dict) -> tuple[str, str] | None: + """Return ``(agent_url, session_key)`` if an AGENT_SERVER URL exists.""" + for url_info in sandbox.get("exposed_urls") or []: + if url_info.get("name") == "AGENT_SERVER": + return url_info["url"].rstrip("/"), sandbox.get("session_api_key", "") + return None + + +@_retry_on_rate_limit +async def _create_sandbox( + client: httpx.AsyncClient, api_url: str, headers: dict[str, str] +) -> str: + """Create a sandbox and return its ID. Retries on rate limit.""" + resp = await client.post(f"{api_url}/api/v1/sandboxes", headers=headers) + resp.raise_for_status() + return resp.json()["id"] + + +@_retry_on_rate_limit +async def _poll_sandbox( + client: httpx.AsyncClient, api_url: str, sandbox_id: str, headers: dict[str, str] +) -> dict[str, Any]: + """Poll sandbox status. Retries on rate limit.""" + resp = await client.get( + f"{api_url}/api/v1/sandboxes", + params={"id": sandbox_id}, + headers=headers, + ) + resp.raise_for_status() + items = resp.json() + if not items: + raise RuntimeError(f"Sandbox {sandbox_id} disappeared") + return items[0] + + +async def _create_and_wait( + client: httpx.AsyncClient, + api_url: str, + api_key: str, + ready_timeout: float = SANDBOX_READY_TIMEOUT, +) -> tuple[str, str, str]: + """Create a sandbox and poll until RUNNING. + + Returns ``(sandbox_id, session_api_key, agent_server_url)``. + Handles 429 rate limits via tenacity retry. + """ + headers = {"Authorization": f"Bearer {api_key}"} + + sandbox_id = await _create_sandbox(client, api_url, headers) + + elapsed = 0.0 + while elapsed < ready_timeout: + sb = await _poll_sandbox(client, api_url, sandbox_id, headers) + status = sb.get("status", "UNKNOWN") + + if status == "RUNNING": + result = _find_agent_server_url(sb) + if result is None: + raise RuntimeError(f"No AGENT_SERVER URL in sandbox {sandbox_id}") + agent_url, session_key = result + return sandbox_id, session_key, agent_url + + if status in ("ERROR", "MISSING"): + # Extract error details from sandbox response + error_code = sb.get("error_code", "") + error_message = sb.get("error_message", "") + error_detail = f"status={status}" + if error_code: + error_detail += f", error_code={error_code}" + if error_message: + error_detail += f", error_message={error_message}" + raise RuntimeError(f"Sandbox {sandbox_id} failed: {error_detail}") + + await asyncio.sleep(SANDBOX_POLL_INTERVAL) + elapsed += SANDBOX_POLL_INTERVAL + + raise TimeoutError(f"Sandbox {sandbox_id} not ready after {ready_timeout}s") + + +async def _upload( + client: httpx.AsyncClient, + agent_url: str, + session_key: str, + data: bytes, + dest: str, +) -> None: + """Upload bytes to the sandbox via the agent-server file API. + + The agent-server expects the absolute path in the URL, e.g. + ``POST /api/file/upload//tmp/file.tar.gz`` (double-slash is correct). + """ + resp = await client.post( + f"{agent_url}/api/file/upload/{dest}", + files={"file": ("upload", data)}, + headers={"X-Session-API-Key": session_key}, + ) + resp.raise_for_status() + + +async def _bash( + client: httpx.AsyncClient, + agent_url: str, + session_key: str, + command: str, + timeout: int = MAX_RUN_DURATION_SECONDS, +) -> tuple[int | None, str, str]: + """Run a bash command synchronously. Returns ``(exit_code, stdout, stderr)``.""" + resp = await client.post( + f"{agent_url}/api/bash/execute_bash_command", + json={"command": command, "timeout": timeout}, + headers={"X-Session-API-Key": session_key}, + timeout=httpx.Timeout(timeout + 30), + ) + resp.raise_for_status() + body = resp.json() + return body.get("exit_code"), body.get("stdout") or "", body.get("stderr") or "" + + +async def _start_bash( + client: httpx.AsyncClient, + agent_url: str, + session_key: str, + command: str, + timeout: int = MAX_RUN_DURATION_SECONDS, +) -> str: + """Start a bash command in the background. Returns the command ID.""" + resp = await client.post( + f"{agent_url}/api/bash/start_bash_command", + json={"command": command, "timeout": timeout}, + headers={"X-Session-API-Key": session_key}, + timeout=30.0, + ) + resp.raise_for_status() + body = resp.json() + return body.get("id") + + +async def _download_in_sandbox( + client: httpx.AsyncClient, + agent_url: str, + session_key: str, + tarball_url: str, + dest: str, + timeout: int = EXTERNAL_DOWNLOAD_TIMEOUT, + max_filesize: int = EXTERNAL_MAX_FILESIZE, +) -> None: + """Download a tarball directly inside the sandbox using curl. + + This is used for external URLs (https://) to avoid downloading + untrusted, potentially large files on the automation service. + + Raises RuntimeError if the download fails. + """ + # Use curl with safety limits: + # -f: fail silently on HTTP errors (returns exit code 22) + # -s: silent mode (no progress) + # -S: show errors even in silent mode + # -L: follow redirects + # --max-filesize: limit download size + # --max-time: limit total time + cmd = ( + f"curl -fsSL " + f"--max-filesize {max_filesize} " + f"--max-time {timeout} " + f"-o {dest} " + f"{_shell_quote(tarball_url)}" + ) + + exit_code, stdout, stderr = await _bash( + client, agent_url, session_key, cmd, timeout=timeout + 30 + ) + + if exit_code != 0: + # curl exit codes: 22 = HTTP error, 63 = max filesize exceeded + if exit_code == 63: + raise RuntimeError( + f"Tarball exceeds size limit ({max_filesize // 1024 // 1024} MB)" + ) + raise RuntimeError(f"Failed to download tarball (exit={exit_code}): {stderr}") + + +# -- Public API --------------------------------------------------------------- + + +@dataclass(frozen=True) +class DispatchResult: + """Result of dispatching an automation to a sandbox (fire-and-forget).""" + + success: bool + sandbox_id: str | None = None + error: str | None = None + + +async def dispatch_automation( + api_url: str, + api_key: str, + entrypoint: str, + tarball_source: bytes | str, + env_vars: dict[str, str] | None = None, + timeout: int = MAX_RUN_DURATION_SECONDS, + callback_url: str | None = None, + run_id: str | None = None, +) -> DispatchResult: + """Dispatch an automation to a sandbox (fire-and-forget). + + 1. Create sandbox and wait until RUNNING. + 2. Get tarball into sandbox (upload bytes OR download from URL). + 3. Extract it, run ``setup.sh`` (if present), then start *entrypoint*. + 4. Return immediately without waiting for the entrypoint to complete. + + The SDK inside the sandbox will POST to callback_url when finished. + The caller should store sandbox_id to verify status later if needed. + + *tarball_source*: Either raw bytes (uploaded to sandbox) or a URL string + (downloaded directly inside sandbox via curl). URLs avoid downloading + untrusted/large files on the automation service. + + *env_vars* are exported before the entrypoint runs. The sandbox + identity env vars (``SANDBOX_ID``, ``SESSION_API_KEY``) are + **always** injected so the SDK's ``local_agent_server_mode`` works. + If *callback_url* / *run_id* are set they are injected as + ``AUTOMATION_CALLBACK_URL`` / ``AUTOMATION_RUN_ID`` so the SDK's + ``OpenHandsCloudWorkspace`` can POST completion status on exit. + """ + env_vars = dict(env_vars) if env_vars else {} + if callback_url: + env_vars["AUTOMATION_CALLBACK_URL"] = callback_url + if run_id: + env_vars["AUTOMATION_RUN_ID"] = run_id + api_url = api_url.rstrip("/") + sandbox_id: str | None = None + + # Helper for consistent structured logging with run_id/sandbox_id + def log_extra() -> dict[str, Any]: + return _log_extra(run_id=run_id, sandbox_id=sandbox_id) + + logger.info("Dispatching automation to sandbox", extra=log_extra()) + + async with httpx.AsyncClient(timeout=60.0) as client: + try: + sandbox_id, session_key, agent_url = await _create_and_wait( + client, api_url, api_key + ) + logger.info( + "Sandbox ready: %s at %s", sandbox_id, agent_url, extra=log_extra() + ) + except Exception as e: + # If sandbox creation started but failed to reach RUNNING, + # still attempt cleanup. + logger.exception("Sandbox creation failed", extra=log_extra()) + if sandbox_id: + await delete_sandbox(client, api_url, api_key, sandbox_id) + return DispatchResult(success=False, sandbox_id=sandbox_id, error=str(e)) + + try: + # Always inject sandbox identity so the SDK can call + # get_llm() / get_secrets() inside the sandbox. + env_vars.setdefault("SANDBOX_ID", sandbox_id) + env_vars.setdefault("SESSION_API_KEY", session_key) + + # Get tarball into sandbox: upload bytes or download from URL + if isinstance(tarball_source, bytes): + logger.info("Uploading tarball to sandbox", extra=log_extra()) + await _upload( + client, agent_url, session_key, tarball_source, TARBALL_PATH + ) + else: + logger.info( + "Downloading tarball in sandbox from URL", extra=log_extra() + ) + await _download_in_sandbox( + client, agent_url, session_key, tarball_source, TARBALL_PATH + ) + + exports = "" + if env_vars: + parts = [f"export {k}={_shell_quote(v)}" for k, v in env_vars.items()] + exports = " && ".join(parts) + " && " + + cmd = ( + f"mkdir -p {WORK_DIR}" + f" && tar xzf {TARBALL_PATH} -C {WORK_DIR}" + f" && cd {WORK_DIR}" + f" && ([ ! -f setup.sh ] || bash setup.sh)" + f" && {exports}{entrypoint}" + ) + + logger.info("Starting entrypoint: %s", entrypoint, extra=log_extra()) + command_id = await _start_bash( + client, agent_url, session_key, cmd, timeout=timeout + ) + logger.info( + "Entrypoint started (command_id=%s), disconnecting", + command_id, + extra=log_extra(), + ) + + return DispatchResult(success=True, sandbox_id=sandbox_id) + + except Exception as e: + logger.exception("Automation dispatch failed", extra=log_extra()) + # Delete sandbox on dispatch failure to avoid orphaned sandboxes + if sandbox_id: + await delete_sandbox(client, api_url, api_key, sandbox_id) + return DispatchResult(success=False, sandbox_id=sandbox_id, error=str(e)) + + +@dataclass(frozen=True) +class AutomationResult: + """Result of running an automation (blocking mode).""" + + success: bool + sandbox_id: str | None = None + exit_code: int | None = None + stdout: str = "" + stderr: str = "" + error: str | None = None + + +async def run_automation( + api_url: str, + api_key: str, + entrypoint: str, + tarball_source: bytes | str, + env_vars: dict[str, str] | None = None, + timeout: int = MAX_RUN_DURATION_SECONDS, + callback_url: str | None = None, + run_id: str | None = None, + keep_sandbox: bool = False, +) -> AutomationResult: + """Execute an automation end-to-end in a fresh sandbox (blocking). + + Use this for testing or when you need to wait for the result immediately. + For production async execution, use dispatch_automation() instead. + + 1. Create sandbox and wait until RUNNING. + 2. Get tarball into sandbox (upload bytes OR download from URL). + 3. Extract it, run ``setup.sh`` (if present), then run *entrypoint*. + 4. Wait for completion and return the result. + 5. Delete the sandbox (unless *keep_sandbox* is True). + + *tarball_source*: Either raw bytes (uploaded to sandbox) or a URL string + (downloaded directly inside sandbox via curl). URLs avoid downloading + untrusted/large files on the automation service. + + *env_vars* are exported before the entrypoint runs. The sandbox + identity env vars (``SANDBOX_ID``, ``SESSION_API_KEY``) are + **always** injected so the SDK's ``local_agent_server_mode`` works. + If *callback_url* / *run_id* are set they are injected as + ``AUTOMATION_CALLBACK_URL`` / ``AUTOMATION_RUN_ID`` so the SDK's + ``OpenHandsCloudWorkspace`` can POST completion status on exit. + """ + env_vars = dict(env_vars) if env_vars else {} + if callback_url: + env_vars["AUTOMATION_CALLBACK_URL"] = callback_url + if run_id: + env_vars["AUTOMATION_RUN_ID"] = run_id + api_url = api_url.rstrip("/") + sandbox_id: str | None = None + + # Helper for consistent structured logging with run_id/sandbox_id + def log_extra() -> dict[str, Any]: + return _log_extra(run_id=run_id, sandbox_id=sandbox_id) + + logger.info("Starting automation execution", extra=log_extra()) + + async with httpx.AsyncClient(timeout=60.0) as client: + try: + sandbox_id, session_key, agent_url = await _create_and_wait( + client, api_url, api_key + ) + logger.info( + "Sandbox ready: %s at %s", sandbox_id, agent_url, extra=log_extra() + ) + except Exception as e: + # If sandbox creation started but failed to reach RUNNING, + # still attempt cleanup. + logger.exception("Sandbox creation failed", extra=log_extra()) + if sandbox_id: + await delete_sandbox(client, api_url, api_key, sandbox_id) + return AutomationResult(success=False, sandbox_id=sandbox_id, error=str(e)) + + try: + # Always inject sandbox identity so the SDK can call + # get_llm() / get_secrets() inside the sandbox. + env_vars.setdefault("SANDBOX_ID", sandbox_id) + env_vars.setdefault("SESSION_API_KEY", session_key) + + # Get tarball into sandbox: upload bytes or download from URL + if isinstance(tarball_source, bytes): + logger.info("Uploading tarball to sandbox", extra=log_extra()) + await _upload( + client, agent_url, session_key, tarball_source, TARBALL_PATH + ) + else: + logger.info( + "Downloading tarball in sandbox from URL", extra=log_extra() + ) + await _download_in_sandbox( + client, agent_url, session_key, tarball_source, TARBALL_PATH + ) + + exports = "" + if env_vars: + parts = [f"export {k}={_shell_quote(v)}" for k, v in env_vars.items()] + exports = " && ".join(parts) + " && " + + cmd = ( + f"mkdir -p {WORK_DIR}" + f" && tar xzf {TARBALL_PATH} -C {WORK_DIR}" + f" && cd {WORK_DIR}" + f" && ([ ! -f setup.sh ] || bash setup.sh)" + f" && {exports}{entrypoint}" + ) + + logger.info("Executing entrypoint: %s", entrypoint, extra=log_extra()) + exit_code, stdout, stderr = await _bash( + client, agent_url, session_key, cmd, timeout=timeout + ) + + success = exit_code == 0 + error_msg = None + if not success: + # Include both stderr and stdout tail - some errors go to stdout + error_parts = [f"exit_code={exit_code}"] + if stderr: + error_parts.append(f"stderr: {stderr[-1000:]}") + if stdout: + error_parts.append(f"stdout: {stdout[-500:]}") + error_msg = "\n".join(error_parts) + logger.warning( + "Entrypoint failed with exit_code=%s", exit_code, extra=log_extra() + ) + else: + logger.info("Entrypoint completed successfully", extra=log_extra()) + + return AutomationResult( + success=success, + sandbox_id=sandbox_id, + exit_code=exit_code, + stdout=stdout, + stderr=stderr, + error=error_msg, + ) + + except Exception as e: + logger.exception("Automation execution failed", extra=log_extra()) + return AutomationResult(success=False, sandbox_id=sandbox_id, error=str(e)) + finally: + if not keep_sandbox: + logger.info("Deleting sandbox", extra=log_extra()) + await delete_sandbox(client, api_url, api_key, sandbox_id) + + +def _shell_quote(s: str) -> str: + """Single-quote a string for safe shell interpolation.""" + return "'" + s.replace("'", "'\\''") + "'" diff --git a/automation/logger.py b/automation/logger.py index 7a11036b..45d183c4 100644 --- a/automation/logger.py +++ b/automation/logger.py @@ -27,8 +27,8 @@ FILE_PREFIX = 'File "' CWD_PREFIX = FILE_PREFIX + str(Path(os.getcwd()).parent) + "/" -_PY_VER = f"{sys.version_info.major}.{sys.version_info.minor}" -SITE_PACKAGES_PREFIX = CWD_PREFIX + f".venv/lib/python{_PY_VER}/site-packages/" +_pyver = f"{sys.version_info.major}.{sys.version_info.minor}" +SITE_PACKAGES_PREFIX = CWD_PREFIX + f".venv/lib/python{_pyver}/site-packages/" LOG_JSON_FOR_CONSOLE = int(os.getenv("LOG_JSON_FOR_CONSOLE", "0")) diff --git a/automation/models.py b/automation/models.py index 59ec4813..0d1694de 100644 --- a/automation/models.py +++ b/automation/models.py @@ -64,6 +64,9 @@ class Automation(Base): # Command to execute the automation (e.g., "uv run script.py") entrypoint: Mapped[str] = mapped_column(Text, nullable=False) + # Maximum execution time in seconds (None = use system default) + timeout: Mapped[int | None] = mapped_column(nullable=True) + # Whether the automation is enabled (can be triggered) enabled: Mapped[bool] = mapped_column(default=True, nullable=False, index=True) @@ -126,6 +129,21 @@ class AutomationRun(Base): # Error details if status is FAILED error_detail: Mapped[str | None] = mapped_column(Text, nullable=True) + # Conversation created by the SDK script (set by completion callback) + conversation_id: Mapped[str | None] = mapped_column(String(255), nullable=True) + + # Pre-computed deadline: started_at + max_duration. Set when transitioning + # to RUNNING, used by the staleness watchdog for efficient indexed queries. + timeout_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), nullable=True, index=True + ) + + # If True, sandbox is not deleted after run completes (for debugging) + keep_alive: Mapped[bool] = mapped_column(default=False, nullable=False) + + # The sandbox ID used for execution (for status verification) + sandbox_id: Mapped[str | None] = mapped_column(String(255), nullable=True) + # Timestamps created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), diff --git a/automation/router.py b/automation/router.py index eb7140fc..ec123f92 100644 --- a/automation/router.py +++ b/automation/router.py @@ -1,27 +1,35 @@ """FastAPI router for the automations CRUD API.""" +import asyncio +import logging import uuid from fastapi import APIRouter, Depends, HTTPException, Query, status -from sqlalchemy import func, select +from sqlalchemy import func, select, update +from sqlalchemy.engine import CursorResult from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import selectinload from automation.auth import AuthenticatedUser, authenticate_request from automation.db import get_session -from automation.models import Automation, AutomationRun +from automation.models import Automation, AutomationRun, AutomationRunStatus from automation.schemas import ( AutomationListResponse, AutomationResponse, AutomationRunListResponse, AutomationRunResponse, CreateAutomationRequest, + RunCompleteRequest, UpdateAutomationRequest, ) from automation.utils import utcnow from automation.utils.run import create_pending_run +from automation.utils.sandbox import cleanup_sandbox from automation.utils.tarball_validation import validate_tarball_path +logger = logging.getLogger(__name__) + router = APIRouter(prefix="/api/v1/automations", tags=["Automations"]) @@ -56,6 +64,7 @@ async def create_automation( tarball_path=body.tarball_path, setup_script_path=body.setup_script_path, entrypoint=body.entrypoint, + timeout=body.timeout, ) session.add(auto) await session.flush() @@ -199,6 +208,97 @@ async def list_automation_runs( ) +# --- Run completion callback --- + + +@router.post("/runs/{run_id}/complete") +async def complete_run( + run_id: uuid.UUID, + body: RunCompleteRequest, + user: AuthenticatedUser = Depends(authenticate_request), + session: AsyncSession = Depends(get_session), +) -> AutomationRunResponse: + """Receive completion callback from the SDK running inside a sandbox. + + Called by ``OpenHandsCloudWorkspace.__exit__`` when the automation + entry-point finishes (success or failure). Transitions the run from + RUNNING → COMPLETED or RUNNING → FAILED. + + Authenticated via the same ``OPENHANDS_API_KEY`` that was passed into + the sandbox. The key is validated against ``/api/keys/current`` (by + ``authenticate_request``) and the resulting user must own the run's + parent automation. + + If keep_alive is False, deletes the sandbox after updating the run status. + """ + result = await session.execute( + select(AutomationRun) + .where(AutomationRun.id == run_id) + .options(selectinload(AutomationRun.automation)) + ) + run = result.scalars().first() + if run is None: + raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Run not found") + + # Verify the caller owns this automation + automation = run.automation + if automation.user_id != user.user_id or automation.org_id != user.org_id: + raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Not your automation") + + # Optimistic locking: only update if the run is still RUNNING. + # This prevents races between the watchdog and the callback. + now = utcnow() + new_status = ( + AutomationRunStatus.COMPLETED + if body.status == "COMPLETED" + else AutomationRunStatus.FAILED + ) + values: dict = { + "status": new_status, + "completed_at": now, + } + if body.status == "COMPLETED" and body.conversation_id: + values["conversation_id"] = body.conversation_id + if body.status == "FAILED" and body.error: + values["error_detail"] = body.error + + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run_id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values(**values) + ) + db_result: CursorResult = await session.execute(stmt) # type: ignore[assignment] + + if db_result.rowcount == 0: + raise HTTPException( + status.HTTP_409_CONFLICT, + detail=f"Run is {run.status.value}, expected RUNNING", + ) + + await session.refresh(run) + logger.info("Run %s → %s", run_id, new_status.value) + + # Clean up sandbox if not keeping alive + if not run.keep_alive and run.sandbox_id: + # Fire-and-forget sandbox deletion in background + from automation.config import get_settings + + settings = get_settings() + asyncio.create_task( + cleanup_sandbox( + api_url=settings.openhands_api_base_url, + api_key=user.api_key, + sandbox_id=run.sandbox_id, + run_id=str(run_id), + ) + ) + + return AutomationRunResponse.model_validate(run) + + # --- Helpers --- diff --git a/automation/schemas.py b/automation/schemas.py index 8a7afbfa..4933cca2 100644 --- a/automation/schemas.py +++ b/automation/schemas.py @@ -9,6 +9,8 @@ from croniter import croniter from pydantic import BaseModel, Field, field_validator +from automation.constants import MAX_RUN_DURATION_SECONDS + # Allowed URI schemes for tarball_path (includes internal upload scheme) _TARBALL_SCHEME_RE = re.compile(r"^(s3|gs|https?|oh-internal)://") @@ -49,7 +51,8 @@ def _validate_command_string( ) -> str | None: """Validate a command/path is relative and safe. - Ensures no path traversal or shell metacharacters. + Rejects traversal patterns and shell metacharacters. + Used for both entrypoint and setup_script_path validation. Args: @@ -93,6 +96,10 @@ class CreateAutomationRequest(BaseModel): entrypoint: str = Field( ..., description='Command to execute the automation (e.g., "uv run script.py")' ) + timeout: int | None = Field( + default=None, + description="Maximum execution time in seconds (default: system maximum)", + ) @field_validator("tarball_path") @classmethod @@ -115,6 +122,19 @@ def validate_entrypoint(cls, v: str) -> str: assert result is not None # satisfy type checker return result + @field_validator("timeout") + @classmethod + def validate_timeout(cls, v: int | None) -> int | None: + if v is None: + return v + if v <= 0: + raise ValueError("timeout must be a positive number") + if v > MAX_RUN_DURATION_SECONDS: + raise ValueError( + f"timeout must not exceed {MAX_RUN_DURATION_SECONDS} seconds" + ) + return v + class UpdateAutomationRequest(BaseModel): """Request to partially update an automation.""" @@ -124,6 +144,7 @@ class UpdateAutomationRequest(BaseModel): tarball_path: str | None = Field(default=None) setup_script_path: str | None = Field(default=None) entrypoint: str | None = Field(default=None) + timeout: int | None = Field(default=None) enabled: bool | None = None @field_validator("tarball_path") @@ -145,6 +166,19 @@ def validate_setup_script_path(cls, v: str | None) -> str | None: def validate_entrypoint(cls, v: str | None) -> str | None: return _validate_command_string(v, "entrypoint") + @field_validator("timeout") + @classmethod + def validate_timeout(cls, v: int | None) -> int | None: + if v is None: + return v + if v <= 0: + raise ValueError("timeout must be a positive number") + if v > MAX_RUN_DURATION_SECONDS: + raise ValueError( + f"timeout must not exceed {MAX_RUN_DURATION_SECONDS} seconds" + ) + return v + # --- Responses --- @@ -158,6 +192,7 @@ class AutomationResponse(BaseModel): tarball_path: str setup_script_path: str | None entrypoint: str + timeout: int | None enabled: bool last_triggered_at: datetime | None created_at: datetime @@ -171,16 +206,29 @@ class AutomationListResponse(BaseModel): total: int -# Phase 1b: These schemas will be used when run-listing endpoints are added. +# --- Run schemas --- + + +class RunCompleteRequest(BaseModel): + """Payload sent by the SDK's OpenHandsCloudWorkspace on context manager exit.""" + + status: Literal["COMPLETED", "FAILED"] + run_id: str | None = None + conversation_id: str | None = None + error: str | None = None class AutomationRunResponse(BaseModel): - """Response for a single automation run (Phase 1b).""" + """Response for a single automation run.""" id: uuid.UUID automation_id: uuid.UUID status: RunStatus error_detail: str | None + conversation_id: str | None + timeout_at: datetime | None + keep_alive: bool + sandbox_id: str | None created_at: datetime started_at: datetime | None completed_at: datetime | None diff --git a/automation/storage/file_store.py b/automation/storage/file_store.py index 52ddee97..7b575304 100644 --- a/automation/storage/file_store.py +++ b/automation/storage/file_store.py @@ -2,19 +2,22 @@ class FileStore(ABC): - """Abstract base class for file storage operations. - - Note: This interface is currently upload-only. Read methods are not included - because this service only handles file uploads. Files are read by other - services (e.g., the dispatcher) that access storage directly. This may - change in the future if read functionality is needed. - """ + """Abstract base class for file storage operations.""" @abstractmethod def write(self, path: str, contents: str | bytes) -> None: """Write contents to a file at the given path.""" pass + @abstractmethod + def read(self, path: str) -> bytes: + """Read and return the contents of the file at the given path. + + Raises: + FileNotFoundError: If the file does not exist. + """ + pass + @abstractmethod def list(self, path: str) -> list[str]: """List all files under the given path prefix.""" diff --git a/automation/storage/google_cloud.py b/automation/storage/google_cloud.py index deff06a3..b2bd124d 100644 --- a/automation/storage/google_cloud.py +++ b/automation/storage/google_cloud.py @@ -2,6 +2,7 @@ from collections.abc import AsyncIterator from google.cloud import storage +from google.cloud.exceptions import NotFound from automation.storage.file_store import FileStore @@ -87,6 +88,25 @@ def write(self, path: str, contents: str | bytes) -> None: else: blob.upload_from_string(contents, content_type="application/octet-stream") + def read(self, path: str) -> bytes: + """Read file contents from GCS. + + Args: + path: The path/key in the bucket (will be prefixed with "automation/"). + + Returns: + The file contents as bytes. + + Raises: + FileNotFoundError: If the file does not exist. + """ + full_path = self._prefixed_path(path) + blob = self.bucket.blob(full_path) + try: + return blob.download_as_bytes() + except NotFound: + raise FileNotFoundError(f"File not found: {full_path}") + def list(self, path: str) -> list[str]: """ List all files under the given path prefix. diff --git a/automation/utils/__init__.py b/automation/utils/__init__.py index d64e2531..c0037a06 100644 --- a/automation/utils/__init__.py +++ b/automation/utils/__init__.py @@ -1,5 +1,6 @@ """Utility modules for the automation service.""" +from automation.utils.api_key import APIKeyError, get_api_key_for_automation_run from automation.utils.cron import ( get_next_fire_time, get_prev_fire_time, @@ -9,6 +10,8 @@ __all__ = [ + "APIKeyError", + "get_api_key_for_automation_run", "get_next_fire_time", "get_prev_fire_time", "is_automation_due", diff --git a/automation/utils/api_key.py b/automation/utils/api_key.py new file mode 100644 index 00000000..e7910c03 --- /dev/null +++ b/automation/utils/api_key.py @@ -0,0 +1,98 @@ +"""API key utilities for automation runs.""" + +import logging +from typing import TYPE_CHECKING + +import httpx + +from automation.config import get_settings + + +if TYPE_CHECKING: + from automation.models import AutomationRun + +logger = logging.getLogger(__name__) + + +class APIKeyError(Exception): + """Exception raised when API key retrieval fails.""" + + pass + + +async def get_api_key_for_automation_run(run: "AutomationRun") -> str: + """Get an API key for executing an automation run. + + Creates a temporary API key for the user/org associated with the + automation run by calling the OpenHands SaaS service API. + + Args: + run: The automation run to get an API key for. Must have its + `automation` relationship loaded with user_id and org_id. + + Returns: + The API key string for authenticating with OpenHands. + + Raises: + APIKeyError: If the API key cannot be retrieved. + ValueError: If the run's automation relationship is not loaded. + """ + if run.automation is None: + raise ValueError( + "AutomationRun.automation relationship must be loaded " + "to retrieve user_id and org_id" + ) + + settings = get_settings() + user_id = run.automation.user_id + org_id = run.automation.org_id + + url = ( + f"{settings.openhands_api_base_url}/api/service/users/{user_id}" + f"/orgs/{org_id}/api-keys" + ) + + headers = { + "X-Service-API-Key": settings.service_key, + "Content-Type": "application/json", + } + + payload = {"name": "automation"} + + try: + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.post(url, headers=headers, json=payload) + response.raise_for_status() + + data = response.json() + api_key = data.get("key") + + if not api_key: + raise APIKeyError(f"API key not found in response: {list(data.keys())}") + + logger.info( + "Created API key for automation run %s (user=%s, org=%s)", + run.id, + user_id, + org_id, + ) + return api_key + + except httpx.HTTPStatusError as e: + logger.error( + "Failed to create API key for run %s: HTTP %s - %s", + run.id, + e.response.status_code, + e.response.text, + exc_info=True, + ) + raise APIKeyError(f"HTTP {e.response.status_code}: {e.response.text}") from e + + except httpx.RequestError as e: + logger.error( + "Failed to create API key for run %s: %s", + run.id, + str(e), + exc_info=True, + ) + raise APIKeyError(f"Request failed: {str(e)}") from e diff --git a/automation/utils/run.py b/automation/utils/run.py index 059ce5fb..5c430a74 100644 --- a/automation/utils/run.py +++ b/automation/utils/run.py @@ -1,14 +1,20 @@ """Automation run utilities.""" +import logging import uuid +from datetime import timedelta from sqlalchemy import update -from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from automation.constants import MAX_RUN_DURATION from automation.models import Automation, AutomationRun, AutomationRunStatus from automation.utils.time import utcnow +logger = logging.getLogger(__name__) + + async def create_pending_run( session: AsyncSession, automation: Automation, @@ -51,30 +57,118 @@ async def mark_run_status( session: AsyncSession, run: AutomationRun, status: AutomationRunStatus, + error_detail: str | None = None, + max_duration: timedelta = MAX_RUN_DURATION, ) -> None: """Update a run's status and set the appropriate timestamp. - Sets started_at when transitioning to RUNNING, or completed_at when - transitioning to COMPLETED or FAILED. Caller is responsible for - committing the transaction. + Sets started_at + timeout_at when transitioning to RUNNING, or + completed_at when transitioning to COMPLETED or FAILED. Caller is + responsible for committing the transaction. Args: session: Database session run: The run to update status: The new status to set + error_detail: Optional error message (only used for FAILED status) + max_duration: Maximum run duration for computing timeout_at """ now = utcnow() values: dict = {"status": status} if status == AutomationRunStatus.RUNNING: values["started_at"] = now + values["timeout_at"] = now + max_duration run.started_at = now + run.timeout_at = now + max_duration elif status in (AutomationRunStatus.COMPLETED, AutomationRunStatus.FAILED): values["completed_at"] = now run.completed_at = now + if error_detail and status == AutomationRunStatus.FAILED: + values["error_detail"] = error_detail + run.error_detail = error_detail + await session.execute( update(AutomationRun).where(AutomationRun.id == run.id).values(**values) ) run.status = status + + +async def update_sandbox_id( + session_factory: async_sessionmaker[AsyncSession], + run_id: uuid.UUID, + sandbox_id: str, +) -> None: + """Store the sandbox ID on the automation run for later verification. + + Args: + session_factory: Async session factory + run_id: The run ID to update + sandbox_id: The sandbox ID to store + """ + try: + async with session_factory() as session: + await session.execute( + update(AutomationRun) + .where(AutomationRun.id == run_id) + .values(sandbox_id=sandbox_id) + ) + await session.commit() + except Exception: + logger.exception("Failed to update sandbox_id for run %s", run_id) + + +async def mark_run_terminal( + session_factory: async_sessionmaker[AsyncSession], + run: AutomationRun, + status: AutomationRunStatus, + error: str | None = None, +) -> None: + """Mark a run with a terminal status (COMPLETED or FAILED) if still RUNNING. + + This is a safe wrapper around mark_run_status that: + 1. Opens a new session + 2. Re-fetches the run to check current status + 3. Only updates if the run is still RUNNING (avoids race conditions) + 4. Commits and handles errors gracefully + + Args: + session_factory: Async session factory + run: The run to update (used to get the ID) + status: The terminal status to set (COMPLETED or FAILED) + error: Optional error message (only used for FAILED status) + """ + from sqlalchemy import select + + run_id = str(run.id) + automation_id = str(run.automation_id) if run.automation_id else None + extra = {"run_id": run_id} + if automation_id: + extra["automation_id"] = automation_id + + try: + async with session_factory() as session: + db_result = await session.execute( + select(AutomationRun).where(AutomationRun.id == run.id) + ) + db_run = db_result.scalars().first() + if db_run and db_run.status == AutomationRunStatus.RUNNING: + await mark_run_status( + session, + db_run, + status, + error_detail=error, + ) + await session.commit() + logger.info("Run marked as %s", status.value, extra=extra) + else: + logger.info( + "Run not marked %s (current status: %s)", + status.value, + db_run.status.value if db_run else "not found", + extra=extra, + ) + except Exception: + logger.exception("Failed to mark run as %s", status.value, extra=extra) diff --git a/automation/utils/sandbox.py b/automation/utils/sandbox.py new file mode 100644 index 00000000..78ba737a --- /dev/null +++ b/automation/utils/sandbox.py @@ -0,0 +1,276 @@ +"""Sandbox verification and cleanup utilities. + +Provides functions to verify automation run status by querying the sandbox's +bash command history, and to clean up sandboxes after runs complete. +""" + +import logging +from typing import Any + +import httpx +from pydantic.dataclasses import dataclass + + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class BashCommandResult: + """Result of querying a sandbox for the last bash command.""" + + found: bool + exit_code: int | None = None + stdout: str = "" + stderr: str = "" + error: str | None = None + + +def _log_extra( + run_id: str | None = None, sandbox_id: str | None = None +) -> dict[str, Any]: + """Build extra dict for structured logging.""" + extra: dict[str, Any] = {} + if run_id: + extra["run_id"] = run_id + if sandbox_id: + extra["sandbox_id"] = sandbox_id + return extra + + +async def get_sandbox_agent_url( + client: httpx.AsyncClient, + api_url: str, + api_key: str, + sandbox_id: str, +) -> tuple[str, str] | None: + """Get the agent server URL and session key for a sandbox. + + Returns (agent_url, session_key) if the sandbox is running with an agent server, + or None if the sandbox is not available. + """ + try: + resp = await client.get( + f"{api_url}/api/v1/sandboxes", + params={"id": sandbox_id}, + headers={"Authorization": f"Bearer {api_key}"}, + ) + resp.raise_for_status() + items = resp.json() + if not items: + return None + + sandbox = items[0] + if sandbox.get("status") != "RUNNING": + return None + + for url_info in sandbox.get("exposed_urls") or []: + if url_info.get("name") == "AGENT_SERVER": + return url_info["url"].rstrip("/"), sandbox.get("session_api_key", "") + return None + except Exception as e: + logger.warning("Failed to get sandbox %s: %s", sandbox_id, e) + return None + + +async def get_last_bash_command_result( + client: httpx.AsyncClient, + agent_url: str, + session_key: str, +) -> BashCommandResult: + """Query the sandbox for the last bash command's result. + + Returns the exit code and output of the most recent bash command. + """ + try: + # Search for the most recent BashOutput event + resp = await client.get( + f"{agent_url}/api/bash/bash_events/search", + params={ + "kind__eq": "BashOutput", + "sort_order": "TIMESTAMP_DESC", + "limit": 1, + }, + headers={"X-Session-API-Key": session_key}, + timeout=30.0, + ) + resp.raise_for_status() + page = resp.json() + + items = page.get("items", []) + if not items: + return BashCommandResult(found=False, error="No bash output found") + + output = items[0] + exit_code = output.get("exit_code") + + # If exit_code is None, the command is still running + if exit_code is None: + return BashCommandResult( + found=True, + exit_code=None, + error="Command still running", + ) + + return BashCommandResult( + found=True, + exit_code=exit_code, + stdout=output.get("stdout") or "", + stderr=output.get("stderr") or "", + ) + except Exception as e: + logger.warning("Failed to get bash command result: %s", e) + return BashCommandResult(found=False, error=str(e)) + + +async def delete_sandbox( + client: httpx.AsyncClient, + api_url: str, + api_key: str, + sandbox_id: str, +) -> bool: + """Delete a sandbox using an existing client. Returns True if successful.""" + try: + resp = await client.delete( + f"{api_url}/api/v1/sandboxes/{sandbox_id}", + params={"sandbox_id": sandbox_id}, + headers={"Authorization": f"Bearer {api_key}"}, + ) + if resp.status_code >= 300: + logger.warning("Delete sandbox %s failed: %s", sandbox_id, resp.text) + return False + return True + except Exception as e: + logger.warning("Error deleting sandbox %s: %s", sandbox_id, e) + return False + + +async def cleanup_sandbox( + api_url: str, + api_key: str, + sandbox_id: str, + run_id: str | None = None, +) -> bool: + """Delete a sandbox (best-effort, creates its own HTTP client). + + This is the main entry point for sandbox cleanup. Use this from routes + and background tasks. + + Args: + api_url: OpenHands API URL + api_key: API key for authentication + sandbox_id: The sandbox to delete + run_id: Optional run ID for logging + + Returns: + True if sandbox was deleted successfully + """ + api_url = api_url.rstrip("/") + extra = _log_extra(run_id=run_id, sandbox_id=sandbox_id) + + try: + async with httpx.AsyncClient(timeout=30.0) as client: + deleted = await delete_sandbox(client, api_url, api_key, sandbox_id) + if deleted: + logger.info("Sandbox deleted", extra=extra) + else: + logger.warning("Failed to delete sandbox", extra=extra) + return deleted + except Exception: + logger.exception("Error deleting sandbox", extra=extra) + return False + + +@dataclass(frozen=True) +class VerificationResult: + """Result of verifying an automation run's sandbox status.""" + + verified: bool + success: bool | None = None # None if not verified + exit_code: int | None = None + stdout: str = "" + stderr: str = "" + error: str | None = None + + +async def verify_run_status( + api_url: str, + api_key: str, + sandbox_id: str, + keep_alive: bool = False, + run_id: str | None = None, +) -> VerificationResult: + """Verify an automation run's status by querying its sandbox. + + Connects to the sandbox, queries the last bash command's exit code, + and optionally deletes the sandbox. + + Args: + api_url: OpenHands API URL + api_key: API key for authentication + sandbox_id: The sandbox to query + keep_alive: If True, don't delete the sandbox after verification + run_id: Optional run ID for logging + + Returns: + VerificationResult with the verification outcome + """ + api_url = api_url.rstrip("/") + extra = _log_extra(run_id=run_id, sandbox_id=sandbox_id) + + async with httpx.AsyncClient(timeout=60.0) as client: + # Get sandbox agent URL + result = await get_sandbox_agent_url(client, api_url, api_key, sandbox_id) + if result is None: + logger.info("Sandbox not available for verification", extra=extra) + return VerificationResult( + verified=False, + error="Sandbox not available", + ) + + agent_url, session_key = result + logger.info("Connected to sandbox for verification", extra=extra) + + # Get last bash command result + bash_result = await get_last_bash_command_result(client, agent_url, session_key) + + if not bash_result.found: + logger.warning( + "Could not find bash command result: %s", + bash_result.error, + extra=extra, + ) + # Still try to clean up if needed + if not keep_alive: + await delete_sandbox(client, api_url, api_key, sandbox_id) + return VerificationResult( + verified=False, + error=bash_result.error, + ) + + if bash_result.exit_code is None: + logger.info("Bash command still running", extra=extra) + return VerificationResult( + verified=False, + error="Command still running", + ) + + success = bash_result.exit_code == 0 + logger.info( + "Verified run status: exit_code=%s, success=%s", + bash_result.exit_code, + success, + extra=extra, + ) + + # Clean up sandbox if not keeping alive + if not keep_alive: + logger.info("Deleting sandbox", extra=extra) + await delete_sandbox(client, api_url, api_key, sandbox_id) + + return VerificationResult( + verified=True, + success=success, + exit_code=bash_result.exit_code, + stdout=bash_result.stdout, + stderr=bash_result.stderr, + ) diff --git a/automation/utils/tarball_validation.py b/automation/utils/tarball_validation.py index d4cc6c94..8a5e163e 100644 --- a/automation/utils/tarball_validation.py +++ b/automation/utils/tarball_validation.py @@ -19,6 +19,9 @@ # Valid external URL schemes (must be publicly accessible) EXTERNAL_URL_SCHEMES = ("https://", "s3://", "gs://") +# HTTP(S) URL schemes that can be downloaded with curl inside a sandbox +HTTP_URL_SCHEMES = ("http://", "https://") + # Internal URL prefix for uploaded tarballs INTERNAL_URL_PREFIX = f"{INTERNAL_URL_SCHEME}://uploads/" @@ -63,6 +66,11 @@ def is_valid_external_url(tarball_path: str) -> bool: return tarball_path.startswith(EXTERNAL_URL_SCHEMES) +def is_http_url(tarball_path: str) -> bool: + """Check if the tarball_path is an HTTP(S) URL downloadable with curl.""" + return tarball_path.startswith(HTTP_URL_SCHEMES) + + async def validate_tarball_path( tarball_path: str, user_id: UUID, diff --git a/automation/watchdog.py b/automation/watchdog.py new file mode 100644 index 00000000..6e3f8fef --- /dev/null +++ b/automation/watchdog.py @@ -0,0 +1,277 @@ +"""Staleness watchdog for stuck RUNNING automation runs. + +Periodically scans for runs stuck in RUNNING state past their pre-computed +``timeout_at`` deadline. Before marking as FAILED, attempts to verify the +actual run status by querying the sandbox's bash command history. + +The ``timeout_at`` column is set to ``started_at + max_duration`` when the +dispatcher transitions a run to RUNNING (see ``mark_run_status``). +""" + +import asyncio +import logging +from typing import Any + +from sqlalchemy import select, update +from sqlalchemy.engine import CursorResult +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from sqlalchemy.orm import selectinload + +from automation.config import Settings +from automation.models import AutomationRun, AutomationRunStatus +from automation.utils.api_key import get_api_key_for_automation_run +from automation.utils.sandbox import cleanup_sandbox, verify_run_status +from automation.utils.time import utcnow + + +logger = logging.getLogger("automation.watchdog") + +# Default scan interval +WATCHDOG_INTERVAL_SECONDS = 120 + + +def _run_extra( + run_id: str | None = None, + sandbox_id: str | None = None, +) -> dict[str, Any]: + """Build extra dict for structured logging.""" + extra: dict[str, Any] = {} + if run_id: + extra["run_id"] = run_id + if sandbox_id: + extra["sandbox_id"] = sandbox_id + return extra + + +async def _verify_and_mark_run( + session: AsyncSession, + run: AutomationRun, + settings: Settings, +) -> bool: + """Verify run status via sandbox and mark accordingly. + + Attempts to connect to the sandbox and check the last bash command's exit code. + If verification succeeds, marks the run based on the actual result. + If verification fails (sandbox unavailable), marks as FAILED with timeout error. + + Returns True if the run was marked with a terminal status. + """ + run_id = str(run.id) + sandbox_id = run.sandbox_id + extra = _run_extra(run_id=run_id, sandbox_id=sandbox_id) + now = utcnow() + + # If no sandbox_id, we can't verify - mark as failed + if not sandbox_id: + logger.warning("No sandbox_id for stale run, marking FAILED", extra=extra) + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run.id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values( + status=AutomationRunStatus.FAILED, + completed_at=now, + error_detail="Timed out: no sandbox_id available for verification", + ) + ) + result: CursorResult = await session.execute(stmt) # type: ignore[assignment] + return result.rowcount > 0 + + # Get API key for sandbox access + try: + api_key = await get_api_key_for_automation_run(run) + except Exception as e: + logger.warning("Failed to get API key for verification: %s", e, extra=extra) + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run.id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values( + status=AutomationRunStatus.FAILED, + completed_at=now, + error_detail=f"Timed out: could not get API key for verification: {e}", + ) + ) + result = await session.execute(stmt) # type: ignore[assignment] + return result.rowcount > 0 + + # Try to verify via sandbox + verification = await verify_run_status( + api_url=settings.openhands_api_base_url, + api_key=api_key, + sandbox_id=sandbox_id, + keep_alive=run.keep_alive, + run_id=run_id, + ) + + if verification.verified: + # We got an actual result from the sandbox + if verification.success: + logger.info( + "Verified run completed successfully (exit_code=%s)", + verification.exit_code, + extra=extra, + ) + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run.id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values( + status=AutomationRunStatus.COMPLETED, + completed_at=now, + ) + ) + else: + error_parts = [f"exit_code={verification.exit_code}"] + if verification.stderr: + error_parts.append(f"stderr: {verification.stderr[-1000:]}") + if verification.stdout: + error_parts.append(f"stdout: {verification.stdout[-500:]}") + error_detail = "\n".join(error_parts) + + logger.warning( + "Verified run failed (exit_code=%s)", + verification.exit_code, + extra=extra, + ) + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run.id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values( + status=AutomationRunStatus.FAILED, + completed_at=now, + error_detail=error_detail, + ) + ) + result = await session.execute(stmt) # type: ignore[assignment] + return result.rowcount > 0 + + # Verification failed - sandbox not available or command still running + # This likely means the sandbox crashed or was cleaned up + logger.warning( + "Could not verify run status: %s, marking FAILED", + verification.error, + extra=extra, + ) + + # Clean up sandbox if not keep_alive (best effort, may already be gone) + if not run.keep_alive and sandbox_id: + await cleanup_sandbox( + api_url=settings.openhands_api_base_url, + api_key=api_key, + sandbox_id=sandbox_id, + run_id=run_id, + ) + + error_msg = verification.error or "no completion callback received" + stmt = ( + update(AutomationRun) + .where( + AutomationRun.id == run.id, + AutomationRun.status == AutomationRunStatus.RUNNING, + ) + .values( + status=AutomationRunStatus.FAILED, + completed_at=now, + error_detail=f"Timed out: {error_msg}", + ) + ) + result = await session.execute(stmt) # type: ignore[assignment] + return result.rowcount > 0 + + +async def mark_stale_runs( + session_factory: async_sessionmaker[AsyncSession], + settings: Settings, +) -> int: + """Find and process stale RUNNING runs. + + A run is stale if ``timeout_at < now()`` (pre-computed at dispatch time). + Before marking as FAILED, attempts to verify the actual status by querying + the sandbox. Uses optimistic locking so concurrent callbacks win. + + Returns the number of runs marked with terminal status. + """ + now = utcnow() + marked = 0 + + async with session_factory() as session: + # Fetch stale runs with their automation relationship for API key access + result = await session.execute( + select(AutomationRun) + .options(selectinload(AutomationRun.automation)) + .where( + AutomationRun.status == AutomationRunStatus.RUNNING, + AutomationRun.timeout_at.isnot(None), + AutomationRun.timeout_at < now, + ) + ) + stale_runs = result.scalars().all() + + for run in stale_runs: + run_id = str(run.id) + extra = _run_extra(run_id=run_id, sandbox_id=run.sandbox_id) + + logger.info( + "Processing stale run (timeout_at=%s, now=%s)", + run.timeout_at, + now, + extra=extra, + ) + + try: + if await _verify_and_mark_run(session, run, settings): + marked += 1 + else: + logger.info("Run already completed, skipping", extra=extra) + except Exception: + logger.exception("Error processing stale run", extra=extra) + + if marked: + await session.commit() + + return marked + + +async def watchdog_loop( + session_factory: async_sessionmaker[AsyncSession], + settings: Settings, + interval_seconds: int = WATCHDOG_INTERVAL_SECONDS, + shutdown_event: asyncio.Event | None = None, +) -> None: + """Main watchdog loop — scans for stale runs periodically.""" + logger.info( + "Watchdog started, scanning every %ds", + interval_seconds, + ) + + while True: + if shutdown_event is not None and shutdown_event.is_set(): + logger.info("Watchdog received shutdown signal, exiting") + break + + try: + marked = await mark_stale_runs(session_factory, settings) + if marked: + logger.info("Processed %d stale run(s)", marked) + except Exception: + logger.exception("Error in watchdog scan") + + if shutdown_event is not None: + try: + await asyncio.wait_for(shutdown_event.wait(), timeout=interval_seconds) + logger.info("Watchdog received shutdown signal, exiting") + break + except TimeoutError: + pass + else: + await asyncio.sleep(interval_seconds) diff --git a/migrations/versions/001_initial_schema.py b/migrations/versions/001_initial_schema.py index 2c17ff46..a6e7137d 100644 --- a/migrations/versions/001_initial_schema.py +++ b/migrations/versions/001_initial_schema.py @@ -33,6 +33,7 @@ def upgrade() -> None: sa.Column("tarball_path", sa.Text, nullable=False), sa.Column("setup_script_path", sa.Text, nullable=True), sa.Column("entrypoint", sa.Text, nullable=False), + sa.Column("timeout", sa.Integer, nullable=True), sa.Column("enabled", sa.Boolean, nullable=False, server_default="true"), sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), sa.Column("last_triggered_at", sa.DateTime(timezone=True), nullable=True), diff --git a/migrations/versions/003_run_timeout_conversation.py b/migrations/versions/003_run_timeout_conversation.py new file mode 100644 index 00000000..7c1bcb68 --- /dev/null +++ b/migrations/versions/003_run_timeout_conversation.py @@ -0,0 +1,58 @@ +"""Add conversation_id, timeout_at, keep_alive, sandbox_id to automation_runs. + +timeout_at: Pre-computed deadline for the staleness watchdog. +conversation_id: Set by the completion callback when SDK creates a conversation. +keep_alive: If True, sandbox is not deleted after run completes (for debugging). +sandbox_id: The sandbox ID used for execution (for status verification). + +Revision ID: 003 +Revises: 002 +Create Date: 2026-03-20 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + + +revision: str = "003" +down_revision: str | None = "002" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column( + "automation_runs", + sa.Column("conversation_id", sa.String(255), nullable=True), + ) + op.add_column( + "automation_runs", + sa.Column( + "timeout_at", + sa.DateTime(timezone=True), + nullable=True, + ), + ) + op.add_column( + "automation_runs", + sa.Column("keep_alive", sa.Boolean(), nullable=False, server_default="false"), + ) + op.add_column( + "automation_runs", + sa.Column("sandbox_id", sa.String(255), nullable=True), + ) + op.create_index( + "ix_automation_runs_timeout_at", + "automation_runs", + ["timeout_at"], + ) + + +def downgrade() -> None: + op.drop_index("ix_automation_runs_timeout_at", table_name="automation_runs") + op.drop_column("automation_runs", "sandbox_id") + op.drop_column("automation_runs", "keep_alive") + op.drop_column("automation_runs", "timeout_at") + op.drop_column("automation_runs", "conversation_id") diff --git a/pyproject.toml b/pyproject.toml index 936b5667..6af53fb5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,6 +87,7 @@ force-single-line = false lines-after-imports = 2 # Pytest configuration + [tool.pytest.ini_options] testpaths = [ "tests" @@ -98,11 +99,15 @@ addopts = "-v --tb=short" asyncio_mode = "auto" # Pyright configuration + [tool.pyright] include = [ "automation", "tests", ] +exclude = [ + "scripts/test_tarball", +] venvPath = "." venv = ".venv" pythonVersion = "3.12" diff --git a/scripts/test_automation.py b/scripts/test_automation.py new file mode 100644 index 00000000..52a0d9c6 --- /dev/null +++ b/scripts/test_automation.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""End-to-end test for ``automation.execution.run_automation()``. + +Exercises the **exact same code path** that the dispatcher uses, +without needing a database, cron job, or callback server. This lets +you independently validate the execution layer against a live +OpenHands Cloud environment. + +Usage +----- + export OPENHANDS_API_KEY="sk-oh-..." + python scripts/test_automation.py + python scripts/test_automation.py --api-url https://staging.all-hands.dev + python scripts/test_automation.py --tarball-dir ./my_custom_tarball +""" + +from __future__ import annotations + +import argparse +import asyncio +import io +import logging +import os +import sys +import tarfile +import time +from pathlib import Path + +from automation.execution import AutomationResult, run_automation + + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)-8s %(message)s", +) +log = logging.getLogger("test_automation") + +DEFAULT_API_URL = "https://staging.all-hands.dev" +SCRIPT_DIR = Path(__file__).resolve().parent +DEFAULT_TARBALL_DIR = SCRIPT_DIR / "test_tarball" + + +def build_tarball_from_dir(src: Path) -> bytes: + """Pack a directory into a .tar.gz in memory.""" + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for path in sorted(src.rglob("*")): + if path.is_file(): + tar.add(path, arcname=path.relative_to(src)) + data = buf.getvalue() + files = [str(p.relative_to(src)) for p in sorted(src.rglob("*")) if p.is_file()] + log.info( + "Built tarball from %s (%d bytes, %d files: %s)", + src, + len(data), + len(files), + files, + ) + return data + + +def check_result(result: AutomationResult) -> bool: + """Pretty-print the result and return True if the test passed.""" + log.info("=== RESULT ===") + log.info(" success: %s", result.success) + log.info(" sandbox_id: %s", result.sandbox_id) + log.info(" exit_code: %s", result.exit_code) + if result.error: + log.error(" error: %s", result.error) + + if result.stdout: + log.info("--- stdout ---") + for line in result.stdout.splitlines(): + log.info(" %s", line) + + if result.stderr: + log.info("--- stderr (last 500 chars) ---") + for line in result.stderr[-500:].splitlines(): + log.info(" %s", line) + + passed = result.success and "ALL_OK" in result.stdout + log.info("PASS" if passed else "FAIL") + return passed + + +async def run_test( + api_url: str, + api_key: str, + tarball_dir: Path, + entrypoint: str = "python main.py", +) -> bool: + """Build a tarball and run it through ``run_automation()``.""" + tarball = build_tarball_from_dir(tarball_dir) + + env_vars = { + "OPENHANDS_API_KEY": api_key, + "OPENHANDS_CLOUD_API_URL": api_url, + } + + result = await run_automation( + api_url=api_url, + api_key=api_key, + entrypoint=entrypoint, + tarball_source=tarball, + env_vars=env_vars, + callback_url="https://example.com/callback", + run_id="test-run-001", + ) + + return check_result(result) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="E2E test for automation.execution.run_automation()", + ) + parser.add_argument( + "--api-url", + default=os.environ.get("OPENHANDS_API_URL", DEFAULT_API_URL), + ) + parser.add_argument( + "--api-key", + default=os.environ.get("OPENHANDS_API_KEY", ""), + ) + parser.add_argument( + "--tarball-dir", + type=Path, + default=DEFAULT_TARBALL_DIR, + help="Directory to pack into the tarball (default: scripts/test_tarball)", + ) + parser.add_argument( + "--entrypoint", + default="python main.py", + help="Command to run inside the sandbox (default: python main.py)", + ) + args = parser.parse_args() + + if not args.api_key: + print("Set OPENHANDS_API_KEY or use --api-key", file=sys.stderr) + sys.exit(1) + + if not args.tarball_dir.is_dir(): + print(f"Tarball dir not found: {args.tarball_dir}", file=sys.stderr) + sys.exit(1) + + log.info("API URL: %s", args.api_url) + log.info("Tarball dir: %s", args.tarball_dir) + log.info("Entrypoint: %s", args.entrypoint) + + start = time.monotonic() + ok = asyncio.run( + run_test(args.api_url, args.api_key, args.tarball_dir, args.entrypoint) + ) + elapsed = time.monotonic() - start + log.info("Total time: %.1fs", elapsed) + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/scripts/test_tarball/main.py b/scripts/test_tarball/main.py new file mode 100644 index 00000000..0ff7c970 --- /dev/null +++ b/scripts/test_tarball/main.py @@ -0,0 +1,130 @@ +"""Automation test script — runs inside an OpenHands Cloud sandbox. + +Tests the full dispatch pipeline using the SDK: + 1. Verify env vars injected by the dispatcher + 2. Open OpenHandsCloudWorkspace with local_agent_server_mode=True + 3. Fetch LLM config via workspace.get_llm() + 4. Fetch secrets via workspace.get_secrets() + 5. Create a Conversation using the LLM and secrets + 6. Send a message and run the conversation + 7. On context manager exit, the workspace sends a completion callback + +Env vars injected by the dispatcher (read by the SDK automatically): + OPENHANDS_API_KEY - per-user automation API key + OPENHANDS_CLOUD_API_URL - SaaS API base URL + SANDBOX_ID - this sandbox's Cloud API identifier + SESSION_API_KEY - session key for sandbox settings auth + AUTOMATION_CALLBACK_URL - completion callback endpoint (optional) + AUTOMATION_RUN_ID - run ID for the callback payload (optional) +""" + +import os +import sys +import time + + +api_key = os.environ.get("OPENHANDS_API_KEY", "") +api_url = os.environ.get("OPENHANDS_CLOUD_API_URL", "") +sandbox_id = os.environ.get("SANDBOX_ID", "") +session_key = os.environ.get("SESSION_API_KEY", "") + +# 1. Verify dispatcher-injected env vars +print("=== ENV VARS ===") +for name, val in [ + ("OPENHANDS_API_KEY", api_key), + ("OPENHANDS_CLOUD_API_URL", api_url), + ("SANDBOX_ID", sandbox_id), + ("SESSION_API_KEY", session_key), +]: + print(f" {name}: {'OK' if val else 'MISSING'}") + if not val: + print(f"FAIL: {name} not set", file=sys.stderr) + sys.exit(1) + +print( + f" AUTOMATION_CALLBACK_URL: {os.environ.get('AUTOMATION_CALLBACK_URL') or 'NONE'}" +) +print(f" AUTOMATION_RUN_ID: {os.environ.get('AUTOMATION_RUN_ID') or 'NONE'}") + +# 2. Test SDK workspace in local_agent_server_mode +from openhands.sdk import Conversation, RemoteConversation # noqa: E402 +from openhands.tools.preset.default import get_default_agent # noqa: E402 +from openhands.workspace import OpenHandsCloudWorkspace # noqa: E402 + + +print("\n=== SDK WORKSPACE ===") +with OpenHandsCloudWorkspace( + local_agent_server_mode=True, + cloud_api_url=api_url, + cloud_api_key=api_key, +) as workspace: + # get_llm() — fetches LLM config from the user's SaaS account + print("\n=== GET_LLM ===") + llm = workspace.get_llm() + print(f" model: {llm.model}") + print(f" api_key present: {bool(llm.api_key)}") + + # get_secrets() — builds LookupSecret references for the user's secrets + print("\n=== GET_SECRETS ===") + secrets = {} + try: + secrets = workspace.get_secrets() + print(f" available: {list(secrets.keys()) or '(none)'}") + except Exception as e: + # Not a hard failure — user may not have secrets configured + print(f" get_secrets() failed (ok if no secrets): {e}") + + # 3. Create an agent and conversation using the LLM and secrets + print("\n=== CONVERSATION ===") + agent = get_default_agent(llm=llm, cli_mode=True) + + received_events: list = [] + last_event_time = {"ts": time.time()} + + def event_callback(event) -> None: + received_events.append(event) + last_event_time["ts"] = time.time() + + conversation = Conversation( + agent=agent, workspace=workspace, callbacks=[event_callback] + ) + assert isinstance(conversation, RemoteConversation) + print(f" conversation created: {type(conversation).__name__}") + + # Inject SaaS secrets into the conversation + if secrets: + conversation.update_secrets(secrets) + print(f" injected {len(secrets)} secrets into conversation") + + # Build a prompt that exercises the injected secrets + secret_names = list(secrets.keys()) if secrets else [] + if secret_names: + names_str = ", ".join(f"${name}" for name in secret_names) + prompt = ( + f"For each of these environment variables: {names_str} — " + "print the variable name and the LAST 50% of its value " + "(i.e. the second half of the string). " + "Then write a short summary into SECRETS_CHECK.txt." + ) + else: + prompt = "Write 'Hello from automation!' into HELLO.txt" + + try: + print(f" sending prompt: {prompt[:80]}...") + conversation.send_message(prompt) + conversation.run() + + # Wait for the stream to settle + while time.time() - last_event_time["ts"] < 2.0: + time.sleep(0.1) + + cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost + print(f" cost: {cost}") + print(f" events received: {len(received_events)}") + finally: + conversation.close() + + print(" conversation completed successfully") + +print("\n=== RESULT ===") +print("ALL_OK") diff --git a/scripts/test_tarball/setup.sh b/scripts/test_tarball/setup.sh new file mode 100644 index 00000000..702fa039 --- /dev/null +++ b/scripts/test_tarball/setup.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# Install the OpenHands SDK from the saas-runtime-mode feature branch. +# Once merged, switch to a released version or @main. +set -e + +SDK_REF="feat/saas-runtime-mode" +echo "[setup] installing openhands SDK ($SDK_REF)" +pip install -q --no-cache-dir \ + "openhands-workspace @ git+https://github.com/OpenHands/software-agent-sdk.git@${SDK_REF}#subdirectory=openhands-workspace" \ + "openhands-sdk @ git+https://github.com/OpenHands/software-agent-sdk.git@${SDK_REF}#subdirectory=openhands-sdk" \ + "openhands-tools @ git+https://github.com/OpenHands/software-agent-sdk.git@${SDK_REF}#subdirectory=openhands-tools" +echo "[setup] done" diff --git a/tests/conftest.py b/tests/conftest.py index 33365cd7..71654e92 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -21,6 +21,7 @@ authenticate_request, create_http_client, ) +from automation.config import Settings # noqa: E402 from automation.db import get_session # noqa: E402 from automation.models import Base # noqa: E402 @@ -142,3 +143,13 @@ def sync_client(async_engine, async_session_factory): yield TestClient(app) # Cleanup http_client to prevent resource leak asyncio.get_event_loop().run_until_complete(http_client.aclose()) + + +@pytest.fixture +def mock_settings(): + """Return a mock Settings instance for dispatcher tests.""" + return Settings( + openhands_api_base_url="https://test.example.com", + service_key="test-service-key", + base_url="http://localhost:8000", + ) diff --git a/tests/test_auth.py b/tests/test_auth.py index c1508c56..2187a9ee 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -150,7 +150,7 @@ class TestAuthIntegration: """ async def test_valid_key_through_api(self, async_engine, async_session_factory): - """Valid API key flows through real auth middleware to protected endpoint.""" + """Valid API key flows through auth middleware to endpoint.""" mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = { @@ -220,7 +220,7 @@ async def override_get_session(): app.dependency_overrides.clear() async def test_invalid_key_through_api(self, async_engine, async_session_factory): - """Invalid API key is rejected after real auth middleware calls OpenHands.""" + """Invalid API key is rejected by auth middleware.""" mock_response = MagicMock() mock_response.status_code = 401 diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index 9a62943a..dee4ddcf 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -6,6 +6,7 @@ import asyncio import uuid from datetime import timedelta +from unittest.mock import AsyncMock, patch import pytest from sqlalchemy import select @@ -17,6 +18,7 @@ from automation.models import Automation, AutomationRun, AutomationRunStatus from automation.utils import utcnow from automation.utils.run import mark_run_status +from automation.utils.tarball_validation import is_http_url # Test UUIDs @@ -24,6 +26,33 @@ TEST_ORG_ID = uuid.UUID("87654321-4321-8765-4321-876543218765") +class TestIsHttpUrl: + """Tests for is_http_url helper function.""" + + def test_https_url_is_http(self): + """HTTPS URLs are HTTP URLs (downloadable with curl in sandbox).""" + assert is_http_url("https://example.com/file.tar.gz") is True + github_url = "https://github.com/user/repo/archive/main.tar.gz" + assert is_http_url(github_url) is True + + def test_http_url_is_http(self): + """HTTP URLs are HTTP URLs (downloadable with curl in sandbox).""" + assert is_http_url("http://example.com/file.tar.gz") is True + + def test_internal_url_is_not_http(self): + """Internal URLs (oh-internal://) are not HTTP URLs.""" + internal_url = "oh-internal://uploads/12345678-1234-5678-1234-567812345678" + assert is_http_url(internal_url) is False + + def test_s3_url_is_not_http(self): + """S3 URLs are not HTTP URLs (need special handling, not curl).""" + assert is_http_url("s3://bucket/key.tar.gz") is False + + def test_gs_url_is_not_http(self): + """GCS URLs are not HTTP URLs (need special handling, not curl).""" + assert is_http_url("gs://bucket/key.tar.gz") is False + + class TestMarkRunStatus: """Tests for mark_run_status function.""" @@ -173,7 +202,10 @@ async def test_sets_completed_at_on_failed(self, async_session_factory): class TestDispatchPendingRuns: """Tests for dispatch_pending_runs function.""" - async def test_dispatches_pending_runs(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_dispatches_pending_runs( + self, mock_execute, async_session_factory, mock_settings + ): """Pending runs are dispatched and marked as RUNNING.""" async with async_session_factory() as session: automation = Automation( @@ -196,7 +228,7 @@ async def test_dispatches_pending_runs(self, async_session_factory): await session.commit() run_id = run.id - dispatched = await dispatch_pending_runs(async_session_factory) + dispatched = await dispatch_pending_runs(async_session_factory, mock_settings) assert len(dispatched) == 1 assert dispatched[0].id == run_id @@ -209,7 +241,10 @@ async def test_dispatches_pending_runs(self, async_session_factory): updated = result.scalars().first() assert updated.status == AutomationRunStatus.RUNNING - async def test_ignores_running_runs(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_ignores_running_runs( + self, mock_execute, async_session_factory, mock_settings + ): """Runs already in RUNNING status are not dispatched.""" async with async_session_factory() as session: automation = Automation( @@ -232,11 +267,14 @@ async def test_ignores_running_runs(self, async_session_factory): session.add(run) await session.commit() - dispatched = await dispatch_pending_runs(async_session_factory) + dispatched = await dispatch_pending_runs(async_session_factory, mock_settings) assert len(dispatched) == 0 - async def test_ignores_completed_runs(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_ignores_completed_runs( + self, mock_execute, async_session_factory, mock_settings + ): """Completed runs are not dispatched.""" async with async_session_factory() as session: automation = Automation( @@ -260,11 +298,14 @@ async def test_ignores_completed_runs(self, async_session_factory): session.add(run) await session.commit() - dispatched = await dispatch_pending_runs(async_session_factory) + dispatched = await dispatch_pending_runs(async_session_factory, mock_settings) assert len(dispatched) == 0 - async def test_respects_batch_size(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_respects_batch_size( + self, mock_execute, async_session_factory, mock_settings + ): """Only batch_size runs are dispatched at once.""" async with async_session_factory() as session: automation = Automation( @@ -288,11 +329,16 @@ async def test_respects_batch_size(self, async_session_factory): session.add(run) await session.commit() - dispatched = await dispatch_pending_runs(async_session_factory, batch_size=2) + dispatched = await dispatch_pending_runs( + async_session_factory, mock_settings, batch_size=2 + ) assert len(dispatched) == 2 - async def test_orders_by_created_at(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_orders_by_created_at( + self, mock_execute, async_session_factory, mock_settings + ): """Oldest pending runs are dispatched first.""" async with async_session_factory() as session: automation = Automation( @@ -322,7 +368,9 @@ async def test_orders_by_created_at(self, async_session_factory): await session.commit() old_run_id = old_run.id - dispatched = await dispatch_pending_runs(async_session_factory, batch_size=1) + dispatched = await dispatch_pending_runs( + async_session_factory, mock_settings, batch_size=1 + ) assert len(dispatched) == 1 assert dispatched[0].id == old_run_id # Old run should be first @@ -331,13 +379,17 @@ async def test_orders_by_created_at(self, async_session_factory): class TestDispatcherLoop: """Tests for dispatcher_loop function.""" - async def test_dispatcher_loop_exits_on_shutdown(self, async_session_factory): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_dispatcher_loop_exits_on_shutdown( + self, mock_execute, async_session_factory, mock_settings + ): """Dispatcher exits gracefully when shutdown event is set.""" shutdown_event = asyncio.Event() task = asyncio.create_task( dispatcher_loop( async_session_factory, + mock_settings, interval_seconds=1, shutdown_event=shutdown_event, ) @@ -352,7 +404,10 @@ async def test_dispatcher_loop_exits_on_shutdown(self, async_session_factory): task.cancel() pytest.fail("Dispatcher did not exit on shutdown signal") - async def test_dispatcher_loop_dispatches_runs(self, async_session_factory, caplog): + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_dispatcher_loop_dispatches_runs( + self, mock_execute, async_session_factory, mock_settings, caplog + ): """Dispatcher polls and dispatches pending runs.""" async with async_session_factory() as session: automation = Automation( @@ -383,6 +438,7 @@ async def test_dispatcher_loop_dispatches_runs(self, async_session_factory, capl task = asyncio.create_task( dispatcher_loop( async_session_factory, + mock_settings, interval_seconds=60, shutdown_event=shutdown_event, ) @@ -406,3 +462,78 @@ async def test_dispatcher_loop_dispatches_runs(self, async_session_factory, capl ) updated = result.scalars().first() assert updated.status == AutomationRunStatus.RUNNING + + +class TestEffectiveTimeout: + """Tests for effective timeout calculation in dispatcher.""" + + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_uses_automation_timeout_when_set( + self, mock_execute, async_session_factory, mock_settings + ): + """Dispatcher uses automation's timeout when set.""" + + async with async_session_factory() as session: + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="With Timeout", + trigger={"type": "cron", "schedule": "* * * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run main.py", + enabled=True, + timeout=120, # Custom timeout + ) + session.add(automation) + await session.commit() + + run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.PENDING, + ) + session.add(run) + await session.commit() + + await dispatch_pending_runs(async_session_factory, mock_settings) + + # Verify _execute_run_safe was called + mock_execute.assert_called_once() + # The automation passed should have timeout=120 + call_args = mock_execute.call_args + run_arg = call_args[0][0] + assert run_arg.automation.timeout == 120 + + @patch("automation.dispatcher._execute_run_safe", new_callable=AsyncMock) + async def test_uses_default_timeout_when_not_set( + self, mock_execute, async_session_factory, mock_settings + ): + """Dispatcher uses MAX_RUN_DURATION_SECONDS when automation timeout is None.""" + async with async_session_factory() as session: + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="No Timeout", + trigger={"type": "cron", "schedule": "* * * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run main.py", + enabled=True, + timeout=None, # No custom timeout + ) + session.add(automation) + await session.commit() + + run = AutomationRun( + automation_id=automation.id, + status=AutomationRunStatus.PENDING, + ) + session.add(run) + await session.commit() + + await dispatch_pending_runs(async_session_factory, mock_settings) + + # Verify _execute_run_safe was called + mock_execute.assert_called_once() + # The automation passed should have timeout=None + call_args = mock_execute.call_args + run_arg = call_args[0][0] + assert run_arg.automation.timeout is None diff --git a/tests/test_execution.py b/tests/test_execution.py new file mode 100644 index 00000000..1cc4eae1 --- /dev/null +++ b/tests/test_execution.py @@ -0,0 +1,140 @@ +"""Tests for the execution module — build_tarball, _shell_quote, and result types. + +Only tests pure logic that can run without a network. The e2e flow +(run_automation/dispatch_automation against a real sandbox) lives in +scripts/test_automation.py. +""" + +import io +import tarfile + +import pytest + +from automation.execution import ( + EXTERNAL_DOWNLOAD_TIMEOUT, + EXTERNAL_MAX_FILESIZE, + AutomationResult, + DispatchResult, + _shell_quote, + build_tarball, +) + + +class TestBuildTarball: + def test_produces_valid_tarball(self): + tb = build_tarball({"hello.txt": "world", "bin.dat": b"\x00\x01"}) + with tarfile.open(fileobj=io.BytesIO(tb), mode="r:gz") as tar: + names = sorted(tar.getnames()) + assert names == ["bin.dat", "hello.txt"] + hello = tar.extractfile("hello.txt") + assert hello is not None + assert hello.read() == b"world" + bindat = tar.extractfile("bin.dat") + assert bindat is not None + assert bindat.read() == b"\x00\x01" + + def test_empty_files(self): + tb = build_tarball({}) + with tarfile.open(fileobj=io.BytesIO(tb), mode="r:gz") as tar: + assert tar.getnames() == [] + + def test_setup_and_entrypoint(self): + tb = build_tarball( + { + "setup.sh": "#!/bin/bash\npip install requests\n", + "run.py": 'print("ok")\n', + } + ) + with tarfile.open(fileobj=io.BytesIO(tb), mode="r:gz") as tar: + assert "setup.sh" in tar.getnames() + assert "run.py" in tar.getnames() + setup_file = tar.extractfile("setup.sh") + assert setup_file is not None + setup = setup_file.read().decode() + assert "pip install" in setup + + +class TestShellQuote: + def test_simple_string(self): + assert _shell_quote("hello") == "'hello'" + + def test_string_with_spaces(self): + assert _shell_quote("hello world") == "'hello world'" + + def test_string_with_single_quotes(self): + assert _shell_quote("it's") == "'it'\\''s'" + + def test_empty_string(self): + assert _shell_quote("") == "''" + + def test_special_characters(self): + assert _shell_quote("$HOME") == "'$HOME'" + + +class TestAutomationResult: + """Tests for AutomationResult (blocking execution result).""" + + def test_frozen_dataclass(self): + r = AutomationResult(success=True, sandbox_id="sb-1", exit_code=0, stdout="ok") + assert r.success is True + assert r.sandbox_id == "sb-1" + assert r.exit_code == 0 + assert r.stdout == "ok" + with pytest.raises(AttributeError): + r.success = False # type: ignore[misc] + + def test_with_error(self): + r = AutomationResult( + success=False, + sandbox_id="sb-1", + exit_code=1, + stderr="error", + error="Failed", + ) + assert r.success is False + assert r.exit_code == 1 + assert r.stderr == "error" + assert r.error == "Failed" + + +class TestDispatchResult: + """Tests for DispatchResult (fire-and-forget execution result).""" + + def test_frozen_dataclass(self): + r = DispatchResult(success=True, sandbox_id="sb-1") + assert r.success is True + assert r.sandbox_id == "sb-1" + with pytest.raises(AttributeError): + r.success = False # type: ignore[misc] + + def test_with_error(self): + r = DispatchResult(success=False, sandbox_id="sb-1", error="Failed to start") + assert r.success is False + assert r.error == "Failed to start" + + +class TestAutomationTarballSource: + """Tests for tarball_source parameter.""" + + def test_tarball_source_accepts_bytes(self): + """tarball_source accepts bytes (will be uploaded).""" + # This just validates the type - actual execution would need mocking + source: bytes | str = b"test tarball content" + assert isinstance(source, bytes) + + def test_tarball_source_accepts_str(self): + """tarball_source accepts str URL (will be downloaded in sandbox).""" + source: bytes | str = "https://example.com/file.tar.gz" + assert isinstance(source, str) + + +class TestExternalDownloadConstants: + """Tests for external download configuration constants.""" + + def test_timeout_is_reasonable(self): + """External download timeout should be reasonable (60-300s).""" + assert 60 <= EXTERNAL_DOWNLOAD_TIMEOUT <= 300 + + def test_max_filesize_is_reasonable(self): + """Max filesize should be reasonable (10MB - 500MB).""" + assert 10 * 1024 * 1024 <= EXTERNAL_MAX_FILESIZE <= 500 * 1024 * 1024 diff --git a/tests/test_router.py b/tests/test_router.py index f73b507d..17d1b3fc 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -215,6 +215,95 @@ async def test_create_automation_setup_script_valid(self, async_client): assert response.status_code == 201 assert response.json()["setup_script_path"] == "scripts/setup.sh" + async def test_create_automation_with_timeout(self, async_client): + """Automation can be created with a valid timeout.""" + payload = { + "name": "With Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + "timeout": 300, + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 201 + data = response.json() + assert data["timeout"] == 300 + + async def test_create_automation_without_timeout(self, async_client): + """Automation can be created without timeout (uses system default).""" + payload = { + "name": "No Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 201 + data = response.json() + assert data["timeout"] is None + + async def test_create_automation_timeout_zero_rejected(self, async_client): + """Timeout of zero is rejected.""" + payload = { + "name": "Zero Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + "timeout": 0, + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 422 + + async def test_create_automation_timeout_negative_rejected(self, async_client): + """Negative timeout is rejected.""" + payload = { + "name": "Negative Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + "timeout": -100, + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 422 + + async def test_create_automation_timeout_exceeds_max_rejected(self, async_client): + """Timeout exceeding system maximum is rejected.""" + payload = { + "name": "Too Long Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + "timeout": 601, # MAX_RUN_DURATION_SECONDS is 600 (10 minutes) + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 422 + + async def test_create_automation_timeout_at_max_allowed(self, async_client): + """Timeout at exactly system maximum is allowed.""" + payload = { + "name": "Max Timeout", + "trigger": {"type": "cron", "schedule": "0 9 * * *"}, + "tarball_path": "s3://bucket/code.tar.gz", + "entrypoint": "python main.py", + "timeout": 600, # MAX_RUN_DURATION_SECONDS is 600 (10 minutes) + } + + response = await async_client.post("/api/v1/automations", json=payload) + + assert response.status_code == 201 + data = response.json() + assert data["timeout"] == 600 + class TestListAutomations: """Tests for GET /api/v1/automations endpoint.""" @@ -538,6 +627,70 @@ async def test_update_automation_wrong_user(self, async_client, async_session): assert response.status_code == 404 + async def test_update_automation_timeout(self, async_client, async_session): + """Can update automation timeout.""" + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Update Timeout", + trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run script.py", + timeout=300, + ) + async_session.add(automation) + await async_session.commit() + + response = await async_client.patch( + f"/api/v1/automations/{automation.id}", + json={"timeout": 120}, + ) + + assert response.status_code == 200 + assert response.json()["timeout"] == 120 + + async def test_update_automation_timeout_invalid(self, async_client, async_session): + """Cannot update timeout to invalid value.""" + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Invalid Timeout Update", + trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run script.py", + ) + async_session.add(automation) + await async_session.commit() + + response = await async_client.patch( + f"/api/v1/automations/{automation.id}", + json={"timeout": -10}, + ) + + assert response.status_code == 422 + + async def test_update_automation_timeout_exceeds_max( + self, async_client, async_session + ): + """Cannot update timeout to exceed system maximum.""" + automation = Automation( + user_id=TEST_USER_ID, + org_id=TEST_ORG_ID, + name="Max Timeout Update", + trigger={"type": "cron", "schedule": "0 9 * * *", "timezone": "UTC"}, + tarball_path="s3://bucket/code.tar.gz", + entrypoint="uv run script.py", + ) + async_session.add(automation) + await async_session.commit() + + response = await async_client.patch( + f"/api/v1/automations/{automation.id}", + json={"timeout": 700}, # MAX_RUN_DURATION_SECONDS is 600 (10 minutes) + ) + + assert response.status_code == 422 + class TestDispatchAutomation: """Tests for POST /api/v1/automations/{id}/dispatch endpoint."""