# How to Use the Flame Graph Assistant for Performance Bottleneck Analysis in OpenDerisk

> Learn how to use the OpenDerisk flame graph assistant to analyze performance bottlenecks. Discover flamegraph_overview and flamegraph_drill_down tools for programmatic CPU profiling.

- Repository: [derisk-ai/openderisk](https://github.com/derisk-ai/openderisk)
- Tags: performance
- Published: 2026-02-28

---

**The flame graph assistant in derisk-ai/openderisk provides two Derisk tools—`flamegraph_overview` for high-level CPU profiling summaries and `flamegraph_drill_down` for deep call-stack investigation—that parse SVG flame graphs to identify performance bottlenecks programmatically.**

The derisk-ai/openderisk repository includes a specialized flame graph assistant that transforms raw CPU profiler output into actionable insights. This toolset parses flame graph SVGs generated by profilers like `perf`, `py-spy`, or `gprof2dot`, enabling developers to diagnose performance bottlenecks through automated hierarchical analysis. By leveraging the Derisk ReAct framework, these tools integrate seamlessly into conversational AI agents for interactive debugging workflows.

## Overview of the Flame Graph Assistant Tools

The flame graph assistant exposes two primary tools defined in [`packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/tools/flamegraph_cpu_analyzer.py`](https://github.com/derisk-ai/openderisk/blob/main/packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/tools/flamegraph_cpu_analyzer.py). Both functions are decorated with `@tool` imported from `derisk.agent.resource.tool` at lines 9–10, making them discoverable by the Derisk ReAct engine.

### flamegraph_overview: High-Level Performance Summary

The `flamegraph_overview` tool, defined at lines 99–104, generates a hierarchical summary of the most CPU-intensive functions per stack level. It parses the flame graph SVG and returns a JSON payload containing the total function count, sample statistics, and a ranked list of hot functions organized by depth level (L1 through LN).

### flamegraph_drill_down: Targeted Call-Stack Investigation

The `flamegraph_drill_down` tool, implemented at lines 77–84, enables precise investigation of specific function call paths. Users provide a target function name, and the tool locates the corresponding rectangle in the SVG—supporting both exact and fuzzy matching—then extracts the complete sub-tree of child calls up to a specified depth.

## Architecture and Implementation Details

The assistant operates through a multi-stage pipeline that converts visual SVG elements into structured performance data.

### SVG Parsing and Call-Stack Extraction

The `_fetch_flamegraph_svg` function at lines 19–28 handles file I/O with encoding error handling, while `_parse_flamegraph_svg` uses Python's `xml.etree.ElementTree` to iterate through all `<rect>` elements. The parser extracts coordinates, sample counts, percentages, and function names from associated `<title>` tags.

Critically, the parser detects SVG orientation by locating the "all" root function and comparing its Y-coordinate to the median at lines 93–122. This `is_inverted` flag ensures accurate level mapping whether the flame graph places the root at the top or bottom. Each rectangle's Y-coordinate maps to a specific stack depth via `y_to_level` calculation at lines 123–135, producing a flattened list of functions and a `functions_by_level` dictionary at lines 152–182.

### Hierarchical View Generation

The `_build_hierarchical_view` function at lines 89–124 transforms parsed data into human-readable summaries. It traverses levels from lowest to highest, merges duplicate function names within levels, sorts by sample count, and formats entries as `L3 function_name (samples, percentage)`. The results reverse to display highest-level functions first.

### Tool Registration with the Derisk Framework

Both tools register automatically through the `@tool` decorator. This registration makes the functions invokable by agents or external APIs without additional boilerplate. The `__main__` block at lines 219–260 provides a standalone CLI for testing, demonstrating usage with sample SVG paths.

## Practical Usage Examples

These examples demonstrate how to invoke the flame graph assistant programmatically using Python's `asyncio`.

### Generating a Performance Overview

To obtain a high-level summary of CPU usage across call-stack levels:

```python
import asyncio
from derisk_ext.agent.agents.open_ta.tools.flamegraph_cpu_analyzer import flamegraph_overview

profile_path = "./pilot/data/f162eff6-330b-4388-9a31-bf8777dcbd60.svg"

overview_json = asyncio.run(
    flamegraph_overview(profile_path, max_functions_per_level=5, limit=30)
)

print(overview_json)

```

The returned JSON includes `total_functions`, `total_samples`, `total_levels`, and a `hierarchical_view` array listing the hottest functions per level with their sample counts and percentages.

### Investigating Specific Functions

For deep analysis of a particular bottleneck:

```python
import asyncio
from derisk_ext.agent.agents.open_ta.tools.flamegraph_cpu_analyzer import flamegraph_drill_down

profile_path = "./pilot/data/f162eff6-330b-4388-9a31-bf8777dcbd60.svg"

result = asyncio.run(
    flamegraph_drill_down(
        profile_path, 
        function_name="C2_CompilerThre", 
        fuzzy_match=False, 
        levels_to_show=5
    )
)

print(result)

```

This returns the target function's metadata (samples, percentage, level) and a hierarchical view of its callees, marked with `[TARGET]` to identify the entry point.

### Using Fuzzy Matching for Exploration

When exact function names are unknown, fuzzy matching locates partial matches:

```python
result = asyncio.run(
    flamegraph_drill_down(
        profile_path,
        function_name="Compiler",
        fuzzy_match=True,
        levels_to_show=4
    )
)

```

The algorithm selects the matching function with the highest sample count as the primary target, displaying its sub-tree while listing other matches separately.

## Key Files and Integration Points

The flame graph assistant integrates with the broader OpenDerisk ecosystem through these components:

- **[`packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/tools/flamegraph_cpu_analyzer.py`](https://github.com/derisk-ai/openderisk/blob/main/packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/tools/flamegraph_cpu_analyzer.py)**: Core implementation containing SVG parsing logic, hierarchical view builders, and tool definitions.

- **[`packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/flamegraph_analyze_react_agent.py`](https://github.com/derisk-ai/openderisk/blob/main/packages/derisk-ext/src/derisk_ext/agent/agents/open_ta/flamegraph_analyze_react_agent.py)**: Skeleton agent configuration demonstrating how to expose these tools within a ReAct-based conversational workflow.

- **[`derisk/agent/resource/tool.py`](https://github.com/derisk-ai/openderisk/blob/main/derisk/agent/resource/tool.py)**: Provides the `@tool` decorator infrastructure that enables automatic tool discovery and registration.

The drill-down tool specifically implements X-range overlap detection at lines 115–165 to accurately associate child rectangles with their parents in the flame graph's visual hierarchy, ensuring correct call-tree reconstruction regardless of SVG complexity.

## Summary

- The **flame graph assistant** converts CPU profiler SVGs into structured performance data through two specialized tools.
- **`flamegraph_overview`** provides ranked, level-by-level summaries of hot functions to quickly identify bottlenecks.
- **`flamegraph_drill_down`** investigates specific call paths using exact or fuzzy matching with X-range overlap logic for accurate sub-tree extraction.
- Both tools are implemented in [`flamegraph_cpu_analyzer.py`](https://github.com/derisk-ai/openderisk/blob/main/flamegraph_cpu_analyzer.py) and registered via the Derisk `@tool` decorator for seamless agent integration.
- The parser handles both normal and inverted flame graph orientations automatically.

## Frequently Asked Questions

### What profiler output formats does the flame graph assistant support?

The assistant processes standard SVG flame graphs generated by tools like Linux `perf`, `py-spy`, `gprof2dot`, or any profiler producing SVG visualizations with `<rect>` and `<title>` elements. The parser automatically detects whether the SVG uses standard or inverted stacking (root at top vs. bottom) and extracts sample counts from the title text.

### How does the drill-down tool determine which functions are children of the target?

The tool uses X-coordinate range overlap detection implemented at lines 115–165 of [`flamegraph_cpu_analyzer.py`](https://github.com/derisk-ai/openderisk/blob/main/flamegraph_cpu_analyzer.py). After locating the target function's rectangle, the algorithm examines subsequent levels and selects rectangles whose X-ranges overlap with the target's X-range, accurately reconstructing the call hierarchy from the visual layout.

### Can I use these tools outside of the Derisk agent framework?

Yes. While the `@tool` decorator registration enables discovery by the Derisk ReAct engine, both `flamegraph_overview` and `flamegraph_drill_down` are standard Python async functions importable from `derisk_ext.agent.agents.open_ta.tools.flamegraph_cpu_analyzer`. The `__main__` block at lines 219–260 demonstrates standalone CLI usage without agent orchestration.

### What is the difference between exact and fuzzy matching in the drill-down tool?

Exact matching requires the `function_name` parameter to match the SVG function name completely (`function['name'] == function_name`), while fuzzy matching performs a case-insensitive substring search (`function_name.lower() in function['name'].lower()`). When multiple functions match fuzzily, the tool selects the one with the highest sample count as the primary target for sub-tree analysis.