核心用法与用例(2/3)

Using OpenHands to investigate and resolve production incidents

Check out the complete Datadog debugging workflow with ready-to-use code and configuration.

When production incidents occur, speed matters. OpenHands can help you quickly investigate issues, analyze logs and errors, identify root causes, and generate fixes—reducing your mean time to resolution (MTTR).

This guide is based on our blog post Debugging Production Issues with AI Agents: Automating Datadog Error Analysis.

Overview

Running a production service is hard. Errors and bugs crop up due to product updates, infrastructure changes, or unexpected user behavior. When these issues arise, it's critical to identify and fix them quickly to minimize downtime and maintain user trust—but this is challenging, especially at scale.

What if AI agents could handle the initial investigation automatically? This allows engineers to start with a detailed report of the issue, including root cause analysis and specific recommendations for fixes, dramatically speeding up the debugging process.

OpenHands accelerates incident response by:

  • Automated error analysis: AI agents investigate errors and provide detailed reports
  • Root cause identification: Connect symptoms to underlying issues in your codebase
  • Fix recommendations: Generate specific, actionable recommendations for resolving issues
  • Integration with monitoring tools: Work directly with platforms like Datadog

Automated Datadog Error Analysis

The OpenHands Software Agent SDK provides powerful capabilities for building autonomous AI agents that can integrate with monitoring platforms like Datadog. A ready-to-use GitHub Actions workflow demonstrates how to automate error analysis.

How It Works

Datadog is a popular monitoring and analytics platform that provides comprehensive error tracking capabilities. It aggregates logs, metrics, and traces from your applications, making it easier to identify and investigate issues in production.

Datadog's Error Tracking groups similar errors together and provides detailed insights into their occurrences, stack traces, and affected services. OpenHands can automatically analyze these errors and provide detailed investigation reports.

Triggering Automated Debugging

The GitHub Actions workflow can be triggered in two ways:

  1. Search Query: Provide a search query (e.g., "JSONDecodeError") to find all recent errors matching that pattern. This is useful for investigating categories of errors.

  2. Specific Error ID: Provide a specific Datadog error tracking ID to deep-dive into a known issue. You can copy the error ID from DataDog's error tracking UI using the "Actions" button.

Automated Investigation Process

When the workflow runs, it automatically performs the following steps:

  1. Get detailed info from the DataDog API
  2. Create or find an existing GitHub issue to track the error
  3. Clone all relevant repositories to get full code context
  4. Run an OpenHands agent to analyze the error and investigate the code
  5. Post the findings as a comment on the GitHub issue

The agent identifies the exact file and line number where errors originate, determines root causes, and provides specific recommendations for fixes.

The workflow posts findings to GitHub issues for human review before any code changes are made. If you want the agent to create a fix, you can follow up using the OpenHands GitHub integration and say @openhands go ahead and create a pull request to fix this issue based on your analysis.

Setting Up the Workflow

To set up automated Datadog debugging in your own repository:

  1. Copy the workflow file to .github/workflows/ in your repository
  2. Configure the required secrets (Datadog API keys, LLM API key)
  3. Customize the default queries and repository lists for your needs
  4. Run the workflow manually or set up scheduled runs

The workflow is fully customizable. You can modify the prompts to focus on specific types of analysis, adjust the agent's tools to fit your workflow, or extend it to integrate with other services beyond GitHub and Datadog.

Find the full implementation on GitHub, including the workflow YAML file, Python script, and prompt template.

Manual Incident Investigation

You can also use OpenHands directly to investigate incidents without the automated workflow.

Log Analysis

OpenHands can analyze logs to identify patterns and anomalies:

Analyze these application logs for the incident that occurred at 14:32 UTC:

1. Identify the first error or warning that appeared
2. Trace the sequence of events leading to the failure
3. Find any correlated errors across services
4. Identify the user or request that triggered the issue
5. Summarize the timeline of events

Log analysis capabilities:

Log Type Analysis Capabilities
Application logs Error patterns, exception traces, timing anomalies
Access logs Traffic patterns, slow requests, error responses
System logs Resource exhaustion, process crashes, system errors
Database logs Slow queries, deadlocks, connection issues

Stack Trace Analysis

Deep dive into stack traces:

Analyze this stack trace from our production error:

[paste full stack trace]

1. Identify the exception type and message
2. Trace back to our code (not framework code)
3. Identify the likely cause
4. Check if this code path has changed recently
5. Suggest a fix

Multi-language support:

Analyze this Java exception:

java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3210)
    at java.util.ArrayList.grow(ArrayList.java:265)
    at com.myapp.DataProcessor.loadAllRecords(DataProcessor.java:142)

Identify:
1. What operation is consuming memory?
2. Is there a memory leak or just too much data?
3. What's the fix?
Analyze this Python traceback:

Traceback (most recent call last):
  File "app/api/orders.py", line 45, in create_order
    order = OrderService.create(data)
  File "app/services/order.py", line 89, in create
    inventory.reserve(item_id, quantity)
AttributeError: 'NoneType' object has no attribute 'reserve'

What's None and why?
Analyze this Node.js error:

TypeError: Cannot read property 'map' of undefined
    at processItems (/app/src/handlers/items.js:23:15)
    at async handleRequest (/app/src/api/router.js:45:12)

What's undefined and how should we handle it?

Root Cause Analysis

Identify the underlying cause of an incident:

Perform root cause analysis for this incident:

Symptoms:
- API response times increased 5x at 14:00
- Error rate jumped from 0.1% to 15%
- Database CPU spiked to 100%

Available data:
- Application metrics (Grafana dashboard attached)
- Recent deployments: v2.3.1 deployed at 13:45
- Database slow query log (attached)

Identify the root cause using the 5 Whys technique.

Common Incident Patterns

OpenHands can recognize and help diagnose these common patterns:

  • Connection pool exhaustion: Increasing connection errors followed by complete failure
  • Memory leaks: Gradual memory increase leading to OOM
  • Cascading failures: One service failure triggering others
  • Thundering herd: Simultaneous requests overwhelming a service
  • Split brain: Inconsistent state across distributed components

Quick Fix Generation

Once the root cause is identified, generate fixes:

We've identified the root cause: a missing null check in OrderProcessor.java line 156.

Generate a fix that:
1. Adds proper null checking
2. Logs when null is encountered
3. Returns an appropriate error response
4. Includes a unit test for the edge case
5. Is minimally invasive for a hotfix

Best Practices

Investigation Checklist

Use this checklist when investigating:

  1. Scope the impact
  2. How many users affected?
  3. What functionality is broken?
  4. What's the business impact?

  5. Establish timeline

  6. When did it start?
  7. What changed around that time?
  8. Is it getting worse or stable?

  9. Gather data

  10. Application logs
  11. Infrastructure metrics
  12. Recent deployments
  13. Configuration changes

  14. Form hypotheses

  15. List possible causes
  16. Rank by likelihood
  17. Test systematically

  18. Implement fix

  19. Choose safest fix
  20. Test before deploying
  21. Monitor after deployment

Common Pitfalls

Avoid these common incident response mistakes:

  • Jumping to conclusions: Gather data before assuming the cause
  • Changing multiple things: Make one change at a time to isolate effects
  • Not documenting: Record all actions for the post-mortem
  • Ignoring rollback: Always have a rollback plan before deploying fixes

For production incidents, always follow your organization's incident response procedures. OpenHands is a tool to assist your investigation, not a replacement for proper incident management.

Automate This

You can set up continuous health monitoring using OpenHands Automations. Copy this prompt into a new conversation to set one up:

Create an automation called "API Health Monitor" that runs every 30 minutes.

It should check https://api.example.com/health and:
- If the response is not 200 OK, send an alert to #alerts with the status code and response body
- If healthy, just log success without alerting anyone

Learn more at https://docs.openhands.dev/openhands/usage/use-cases/incident-triage

For deeper error analysis with Datadog integration, see the Datadog debugging workflow.


Using OpenHands to identify and fix security vulnerabilities in your codebase

Check out the complete vulnerability remediation plugin with ready-to-use code and configuration.

Security vulnerabilities are a constant challenge for software teams. Every day, new security issues are discovered—from vulnerabilities in dependencies to code security flaws detected by static analysis tools. The National Vulnerability Database (NVD) reports thousands of new vulnerabilities annually, and organizations struggle to keep up with this constant influx.

The Challenge

The traditional approach to vulnerability remediation is manual and time-consuming:

  1. Scan repositories for vulnerabilities
  2. Review each vulnerability and its impact
  3. Research the fix (usually a version upgrade)
  4. Update dependency files
  5. Test the changes
  6. Create pull requests
  7. Get reviews and merge

This process can take hours per vulnerability, and with hundreds or thousands of vulnerabilities across multiple repositories, it becomes an overwhelming task. Security debt accumulates faster than teams can address it.

What if we could automate this entire process using AI agents?

Automated Vulnerability Remediation with OpenHands

The OpenHands Software Agents SDK provides powerful capabilities for building autonomous AI agents capable of interacting with codebases. These agents can tackle one of the most tedious tasks in software maintenance: security vulnerability remediation.

OpenHands assists with vulnerability remediation by:

  • Identifying vulnerabilities: Analyzing code for common security issues
  • Understanding impact: Explaining the risk and exploitation potential
  • Implementing fixes: Generating secure code to address vulnerabilities
  • Validating remediation: Verifying fixes are effective and complete

Two Approaches to Vulnerability Fixing

1. Point to a GitHub Repository

Build a workflow where users can point to a GitHub repository, scan it for vulnerabilities, and have OpenHands AI agents automatically create pull requests with fixes—all with minimal human intervention.

2. Upload Security Scanner Reports

Enable users to upload reports from security scanners such as Snyk (as well as other third-party security scanners) where OpenHands agents automatically detect the report format, identify the issues, and apply fixes.

This solution goes beyond automation—it focuses on making security remediation accessible, fast, and scalable.

Architecture Overview

A vulnerability remediation agent can be built as a web application that orchestrates agents using the OpenHands Software Agents SDK and OpenHands Cloud to perform security scans and automate remediation fixes.

The key architectural components include:

  • Frontend: Communicates directly with the OpenHands Agent Server through the TypeScript Client
  • WebSocket interface: Enables real-time status updates on agent actions and operations
  • LLM flexibility: OpenHands supports multiple LLMs, minimizing dependency on any single provider
  • Scalable execution: The Agent Server can be hosted locally, with self-hosted models, or integrated with OpenHands Cloud

This architecture allows the frontend to remain lightweight while heavy lifting happens in the agent's execution environment.

Example: Vulnerability Fixer Application

An example implementation is available at github.com/OpenHands/vulnerability-fixer. This React web application demonstrates the full workflow:

  1. User points to a repository or uploads a security scan report
  2. Agent analyzes the vulnerabilities
  3. Agent creates fixes and pull requests automatically
  4. User reviews and merges the changes

Security Scanning Integration

Use OpenHands to analyze security scanner output:

We ran a security scan and found these issues. Analyze each one:

1. SQL Injection in src/api/users.py:45
2. XSS in src/templates/profile.html:23
3. Hardcoded credential in src/config/database.py:12
4. Path traversal in src/handlers/files.py:67

For each vulnerability:
- Explain what the vulnerability is
- Show how it could be exploited
- Rate the severity (Critical/High/Medium/Low)
- Suggest a fix

Common Vulnerability Patterns

OpenHands can detect these common vulnerability patterns:

Vulnerability Pattern Example
SQL Injection String concatenation in queries query = "SELECT * FROM users WHERE id=" + user_id
XSS Unescaped user input in HTML <div>${user_comment}</div>
Path Traversal Unvalidated file paths open(user_supplied_path)
Command Injection Shell commands with user input os.system("ping " + hostname)
Hardcoded Secrets Credentials in source code password = "admin123"

Automated Remediation

Applying Security Patches

Fix identified vulnerabilities:

Fix the SQL injection vulnerability in src/api/users.py:

Current code:
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)

Requirements:
1. Use parameterized queries
2. Add input validation
3. Maintain the same functionality
4. Add a test case for the fix
**Fixed code:**
# Using parameterized query
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
Fix the XSS vulnerability in src/templates/profile.html:

Current code:
<div class="bio">${user.bio}</div>

Requirements:
1. Properly escape user content
2. Consider Content Security Policy
3. Handle rich text if needed
4. Test with malicious input
**Fixed code:**
<!-- Using auto-escaping template engine -->
<div class="bio">{{ user.bio | escape }}</div>
Fix the command injection in src/utils/network.py:

Current code:
def ping_host(hostname):
    os.system(f"ping -c 1 {hostname}")

Requirements:
1. Use safe subprocess calls
2. Validate input format
3. Avoid shell=True
4. Handle errors properly
**Fixed code:**
import subprocess
import re

def ping_host(hostname):
    # Validate hostname format
    if not re.match(r'^[a-zA-Z0-9.-]+$', hostname):
        raise ValueError("Invalid hostname")

    # Use subprocess without shell
    result = subprocess.run(
        ["ping", "-c", "1", hostname],
        capture_output=True,
        text=True
    )
    return result.returncode == 0

Code-Level Vulnerability Fixes

Fix application-level security issues:

Fix the broken access control in our API:

Issue: Users can access other users' data by changing the ID in the URL.

Current code:
@app.get("/api/users/{user_id}/documents")
def get_documents(user_id: int):
    return db.get_documents(user_id)

Requirements:
1. Add authorization check
2. Verify requesting user matches or is admin
3. Return 403 for unauthorized access
4. Log access attempts
5. Add tests for authorization

Fixed code:

@app.get("/api/users/{user_id}/documents")
def get_documents(user_id: int, current_user: User = Depends(get_current_user)):
    # Check authorization
    if current_user.id != user_id and not current_user.is_admin:
        logger.warning(f"Unauthorized access attempt: user {current_user.id} tried to access user {user_id}'s documents")
        raise HTTPException(status_code=403, detail="Not authorized")

    return db.get_documents(user_id)

Security Testing

Test your fixes thoroughly:

Create security tests for the SQL injection fix:

1. Test with normal input
2. Test with SQL injection payloads:
   - ' OR '1'='1
   - '; DROP TABLE users; --
   - UNION SELECT * FROM passwords
3. Test with special characters
4. Test with null/empty input
5. Verify error handling doesn't leak information

Automated Remediation Pipeline

Create an end-to-end automated pipeline:

Create an automated vulnerability remediation pipeline:

1. Parse Snyk/Dependabot/CodeQL alerts
2. Categorize by severity and type
3. For each vulnerability:
   - Create a branch
   - Apply the fix
   - Run tests
   - Create a PR with:
     - Description of vulnerability
     - Fix applied
     - Test results
4. Request review from security team
5. Auto-merge low-risk fixes after tests pass

Building Your Own Vulnerability Fixer

The example application demonstrates that AI agents can effectively automate security maintenance at scale. Tasks that required hours of manual effort per vulnerability can now be completed in minutes with minimal human intervention.

To build your own vulnerability remediation agent:

  1. Use the OpenHands Software Agent SDK to create your agent
  2. Integrate with your security scanning tools (Snyk, Dependabot, CodeQL, etc.)
  3. Configure the agent to create pull requests automatically
  4. Set up human review workflows for critical fixes

As agent capabilities continue to evolve, an increasing number of repetitive and time-consuming security tasks can be automated, enabling developers to focus on higher-level design, innovation, and problem-solving rather than routine maintenance.

Automate This

You can run vulnerability scans on a schedule using OpenHands Automations. Copy this prompt into a new conversation to set one up:

Create an automation called "Security Scan" that runs daily at 3 AM.

It should run a security audit:
1. Check for known vulnerabilities in dependencies
2. Scan for hardcoded secrets or API keys
3. Look for common security misconfigurations

Create a detailed report and alert #security if any high or critical issues are found.

Learn more at https://docs.openhands.dev/openhands/usage/use-cases/vulnerability-remediation

You can also use the vulnerability-remediation plugin for automated fix PRs alongside the scan.


Migrating Apache Spark applications with OpenHands

Check out the migration scoring plugin to evaluate and validate your Spark migration quality.

Apache Spark is constantly evolving, and keeping your data pipelines up to date is essential for performance, security, and access to new features. OpenHands can help you analyze, migrate, and validate Spark applications.

Overview

Spark version upgrades are deceptively difficult. The Spark 3.0 migration guide alone documents hundreds of behavioral changes, deprecated APIs, and removed features, and many of these changes are semantic. That means the same code compiles and runs but produces different results across different Spark versions: for example, a date parsing expression that worked correctly in Spark 2.4 may silently return different values in Spark 3.x due to the switch from the Julian calendar to the Gregorian calendar.

Version upgrades are also made difficult due to the scale of typical enterprise Spark codebases. When you have dozens of jobs across ETL, reporting, and ML pipelines, each with its own combination of DataFrame operations, UDFs, and configuration, manual migration stops scaling well and becomes prone to subtle regressions.

Spark migration requires careful analysis, targeted code changes, and thorough validation to ensure that migrated pipelines produce identical results. The migration needs to be driven by an experienced data engineering team, but even that isn't sufficient to ensure the job is done quickly or without regressions. This is where OpenHands comes in.

Such migrations need to be driven by experienced data engineering teams that understand how your Spark pipelines interact, but even that isn't sufficient to ensure the job is done quickly or without regression. This is where OpenHands comes in. OpenHands assists in migrating Spark applications along every step of the process:

  1. Understanding: Analyze the existing codebase to identify what needs to change and why
  2. Migration: Apply targeted code transformations that address API changes and behavioral differences
  3. Validation: Verify that migrated pipelines produce identical results to the originals

In this document, we will explore how OpenHands contributes to Spark migrations, with example prompts and techniques to use in your own efforts. While the examples focus on Spark 2.x to 3.x upgrades, the same principles apply to cloud platform migrations, framework conversions (MapReduce, Hive, Pig to Spark), and upgrades between Spark 3.x minor versions.

Understanding

Before changing any code, it helps to build a clear picture of what is affected and where the risk is concentrated. Spark migrations touch a large surface area, between API deprecations, behavioral changes, configuration defaults, and dependency versions, and the interactions between them are hard to reason about manually.

Apache releases detailed lists of changes between each major and minor version of Spark. OpenHands can utilize this list of changes while scanning your codebase to produce a structured inventory of everything that needs attention. This inventory becomes the foundation for the migration itself, helping you prioritize work and track progress.

If your Spark project is in /src and you're migrating from 2.4 to 3.0, the following prompt will generate this inventory:

Analyze the Spark application in `/src` for a migration from Spark 2.4 to Spark 3.0.

Examine the migration guidelines at https://spark.apache.org/docs/latest/migration-guide.html.

Then, for each source file, identify

1. Deprecated or removed API usages (e.g., `registerTempTable`, `unionAll`, `SQLContext`)
2. Behavioral changes that could affect output (e.g., date/time parsing, CSV parsing, CAST semantics)
3. Configuration properties that have changed defaults or been renamed
4. Dependencies that need version updates

Save the results in `migration_inventory.json` in the following format:

{
  ...,
  "src/main/scala/etl/TransformJob.scala": {
    "deprecated_apis": [
      {"line": 42, "current": "df.registerTempTable(\"temp\")", "replacement": "df.createOrReplaceTempView(\"temp\")"}
    ],
    "behavioral_changes": [
      {"line": 78, "description": "to_date() uses proleptic Gregorian calendar in Spark 3.x; verify date handling with test data"}
    ],
    "config_changes": [],
    "risk": "medium"
  },
  ...
}

Tools like grep and find (both used by OpenHands) are helpful for identifying where APIs are used, but the real value comes from OpenHands' ability to understand the context around each usage. A simple registerTempTable call is migrated via a rename, but a date parsing expression requires understanding how the surrounding pipeline uses the result. This contextual analysis helps developers distinguish between mechanical fixes and changes that need careful testing.

Migration

With a clear inventory of what needs to change, the next step is applying the transformations. Spark migrations involve a mix of straightforward API renames and subtler behavioral adjustments, and it's important to handle them differently.

To handle simple renames, we prompt OpenHands to use tools like grep and ast-grep instead of manually manipulating source code. This saves tokens and also simplifies future migrations, as agents can reliably re-run the tools via a script.

The main risk in migration is that many Spark 3.x behavioral changes are silent. The migrated code will compile and run without errors, but may produce different results. Date and timestamp handling is the most common source of these silent failures: Spark 3.x switched to the Gregorian calendar by default, which changes how dates before 1582-10-15 are interpreted. CSV and JSON parsing also became stricter in Spark 3.x, rejecting malformed inputs that Spark 2.x would silently accept.

An example prompt is below:

Migrate the Spark application in `/src` from Spark 2.4 to Spark 3.0.

Use `migration_inventory.json` to guide the changes.

For all low-risk changes (minor syntax changes, updated APIs, etc.), use tools like `grep` or `ast-grep`. Make sure you write the invocations to a `migration.sh` script for future use.

Requirements:
1. Replace all deprecated APIs with their Spark 3.0 equivalents
2. For behavioral changes (especially date handling and CSV parsing), add explicit configuration to preserve Spark 2.4 behavior where needed (e.g., spark.sql.legacy.timeParserPolicy=LEGACY)
3. Update build.sbt / pom.xml dependencies to Spark 3.0 compatible versions
4. Replace RDD-based operations with DataFrame/Dataset equivalents where practical
5. Replace UDFs with built-in Spark SQL functions where a direct equivalent exists
6. Update import statements for any relocated classes
7. Preserve all existing business logic and output schemas

Note the inclusion of the known problems in requirement 2. We plan to catch the silent failures associated with these systems in the validation step, but including them explicitly while migrating helps avoid them altogether.

Validation

Spark migrations are particularly prone to silent regressions: jobs appear to run successfully but produce subtly different output. Jobs dealing with dates, CSVs, or using CAST semantics are all vulnerable, especially when migrating between major versions of Spark.

The most reliable way to ensure silent regressions do not exist is by data-level comparison, where both the new and old pipelines are run on the same input data and their outputs directly compared. This catches subtle errors that unit tests might miss, especially in complex pipelines where a behavioral change in one stage propagates through downstream transformations.

An example prompt for data-level comparison:

Validate the migrated Spark application in `/src` against the original.

1. For each job, run both the Spark 2.4 and 3.0 versions on the test data in `/test_data`
2. Compare outputs:
   - Row counts must match exactly
   - Perform column-level comparison using checksums for numeric columns and exact match for string/date columns
   - Flag any NULL handling differences
3. For any discrepancies, trace them back to specific migration changes using the MIGRATION comments
4. Generate a performance comparison: job duration, shuffle bytes, and peak executor memory

Save the results in `validation_report.json` in the following format:

{
  "jobs": [
    {
      "name": "daily_etl",
      "data_match": true,
      "row_count": {"v2": 1000000, "v3": 1000000},
      "column_diffs": [],
      "performance": {
        "duration_seconds": {"v2": 340, "v3": 285},
        "shuffle_bytes": {"v2": "2.1GB", "v3": "1.8GB"}
      }
    },
    ...
  ]
}

Note this prompt relies on existing data in /test_data. This can be generated by standard fuzzing tools, but in a pinch OpenHands can also help construct synthetic data that stresses the potential corner cases in the relevant systems.

Every migration is unique, and developer experience is crucial to ensure the testing strategy covers your organization's requirements. Pay particular attention to jobs that involve date arithmetic, decimal precision in financial calculations, or custom UDFs that may depend on Spark internals. A solid validation suite not only ensures the migrated code works as expected, but also builds the organizational confidence needed to deploy the new version to production.

Beyond Version Upgrades

While this document focuses on Spark version upgrades, the same Understanding → Migration → Validation workflow applies to other Spark migration scenarios:

  • Cloud platform migrations (e.g., EMR to Databricks, on-premises to Dataproc): The "understanding" step inventories platform-specific code (S3 paths, IAM roles, EMR bootstrap scripts), the migration step converts them to the target platform's equivalents, and validation confirms that jobs produce identical output in the new environment.
  • Framework migrations (MapReduce, Hive, or Pig to Spark): The "understanding" step maps the existing framework's operations to Spark equivalents, the migration step performs the conversion, and validation compares outputs between the old and new frameworks.

In each case, the key principle is the same: build a structured inventory of what needs to change, apply targeted transformations, and validate rigorously before deploying.