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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 52 additions & 24 deletions duckdb/query_graph/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def __init__(self, phase: str, time: float, depth: int) -> None: # noqa: D107
self.percentage = 0

def calculate_percentage(self, total_time: float) -> None: # noqa: D102
self.percentage = self.time / total_time
self.percentage = self.time / total_time if total_time else 0

def combine_timing(self, r: "NodeTiming") -> "NodeTiming": # noqa: D102
# TODO: can only add timings for same-phase nodes # noqa: TD002, TD003
Expand Down Expand Up @@ -319,6 +319,39 @@ def open_utf8(fpath: str, flags: str) -> object: # noqa: D103
return Path(fpath).open(mode=flags, encoding="utf8")


def _profile_tree_node(node: dict) -> dict:
return {
"operator_type": node["type"],
"operator_timing": node.get("timing", 0),
"operator_cardinality": node.get("intermediate_rows", 0),
"result_set_size": node.get("intermediate_size_bytes", 0),
"extra_info": node.get("extra_info", {}),
"children": [_profile_tree_node(child) for child in node.get("children", [])],
}


def _profile_for_html(profile: dict) -> dict:
if "operator" not in profile and "query" not in profile:
return profile
query = profile.get("query", {})
system = profile.get("system", {})
io = profile.get("io", {})
# DuckDB 2 groups metrics by section. Keep the renderer compatible with saved flat profiles.
metrics = {
"latency": query.get("total_time"),
"query_name": query.get("sql"),
"cumulative_rows_scanned": query.get("total_rows_scanned"),
"system_peak_buffer_memory": system.get("peak_buffer_memory"),
"total_bytes_read": io.get("total_bytes_read"),
"total_bytes_written": io.get("total_bytes_written"),
}
return {
"cpu_time": query.get("cpu_time", 0),
"children": [_profile_tree_node(node) for node in profile.get("operator", [])],
**{key: value for key, value in metrics.items() if value is not None},
}


class ProfilingInfo: # noqa: D101
def __init__(self, conn: DuckDBPyConnection | None = None, from_file: str | None = None) -> None: # noqa: D107
self.conn = conn
Expand Down Expand Up @@ -367,7 +400,8 @@ def _get_node_body(
self, name: str, result: str, cpu_time: float, card: int, est: int, result_size: int, extra_info: str
) -> str:
"""Generate the HTML body for a single node in the tree."""
node_style = f"background-color: {self._get_f7fff0_shade_hex(float(result) / cpu_time)};"
fraction = float(result) / cpu_time if cpu_time else 0
node_style = f"background-color: {self._get_f7fff0_shade_hex(fraction)};"
new_name = "BRIDGE" if (name == "INVALID") else name.replace("_", " ")
formatted_num = f"{float(result):.4f}"

Expand Down Expand Up @@ -426,9 +460,8 @@ def _generate_tree_recursive(self, json_graph: object, cpu_time: float) -> str:
return node_prefix_html + node_body + children_html + node_suffix_html

# For generating the table in the top left with expandable phases
def _generate_timing_html(self, graph_json: object, query_timings: object) -> object:
def _generate_timing_html(self, json_graph: dict, query_timings: object) -> object:
"""Generates timing HTML table with expandable phases."""
json_graph = json.loads(graph_json)
self._gather_timing_information(json_graph, query_timings)
table_head = """
<table>
Expand Down Expand Up @@ -499,10 +532,10 @@ def _generate_timing_html(self, graph_json: object, query_timings: object) -> ob
return table_head + table_body

@staticmethod
def _generate_metric_grid_html(graph_json: str) -> str:
json_graph = json.loads(graph_json)
def _generate_metric_grid_html(json_graph: dict) -> str:
latency = json_graph.get("latency", "N/A")
metrics = {
"Execution Time (s)": f"{float(json_graph.get('latency', 'N/A')):.4f}",
"Execution Time (s)": f"{float(latency):.4f}" if latency != "N/A" else "N/A",
"Total GB Read": f"{float(json_graph.get('total_bytes_read', 'N/A')) / (1024**3):.4f}"
if json_graph.get("total_bytes_read", "N/A") != "N/A"
else "N/A",
Expand All @@ -528,8 +561,7 @@ def _generate_metric_grid_html(graph_json: str) -> str:
return metric_grid_html

@staticmethod
def _generate_sql_query_html(graph_json: str) -> str:
json_graph = json.loads(graph_json)
def _generate_sql_query_html(json_graph: dict) -> str:
sql_query = json_graph.get("query_name", "N/A")
sql_html = f"""
<details><summary><b>SQL Query</b></summary>
Expand All @@ -542,14 +574,11 @@ def _generate_sql_query_html(graph_json: str) -> str:
"""
return sql_html

def _generate_tree_html(self, graph_json: object) -> str:
json_graph = json.loads(graph_json)
cpu_time = float(json_graph["cpu_time"])
def _generate_tree_html(self, json_graph: dict) -> str:
cpu_time = float(json_graph.get("cpu_time", 0))
tree_prefix = '<div class="tf-tree tf-gap-sm"> \n <ul>'
tree_suffix = "</ul> </div>"
# first level of json is general overview
# TODO: make sure json output first level always has only 1 level # noqa: TD002, TD003
tree_body = self._generate_tree_recursive(json_graph["children"][0], cpu_time)
tree_body = "".join(self._generate_tree_recursive(node, cpu_time) for node in json_graph["children"])
return tree_prefix + tree_body + tree_suffix

def _generate_ipython(self, json_input: str) -> str:
Expand All @@ -572,11 +601,9 @@ def _generate_style_html(graph_json: str, include_meta_info: bool) -> None: # n
libraries = '<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">\n' # noqa: E501
return {"treeflex_css": treeflex_css, "duckdb_css": qgraph_css, "libraries": libraries, "chart_script": ""}

def _gather_timing_information(self, json: str, query_timings: object) -> None:
# add up all of the times
# measure each time as a percentage of the total time.
# then you can return a list of [phase, time, percentage]
self._get_child_timings(json["children"][0], query_timings)
def _gather_timing_information(self, profile: dict, query_timings: object) -> None:
for node in profile["children"]:
self._get_child_timings(node, query_timings)

def _translate_json_to_html(
self, input_file: str | None = None, input_text: str | None = None, output_file: str = "profile.html"
Expand All @@ -591,10 +618,11 @@ def _translate_json_to_html(
print("please provide either input file or input text")
exit(1)
html_output = self._generate_style_html(text, True)
highlight_metric_grid = self._generate_metric_grid_html(text)
timing_table = self._generate_timing_html(text, query_timings)
tree_output = self._generate_tree_html(text)
sql_query_html = self._generate_sql_query_html(text)
profile = _profile_for_html(json.loads(text))
highlight_metric_grid = self._generate_metric_grid_html(profile)
timing_table = self._generate_timing_html(profile, query_timings)
tree_output = self._generate_tree_html(profile)
sql_query_html = self._generate_sql_query_html(profile)
# finally create and write the html
with open_utf8(output_file, "w+") as f:
html = """<!DOCTYPE html>
Expand Down
52 changes: 41 additions & 11 deletions tests/fast/test_profiler.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import json

import pytest

import duckdb
Expand Down Expand Up @@ -36,15 +38,43 @@ def test_profiler_matches_expected_format(self, profiling_connection, tmp_path_f
}
assert expected_keys.issubset(profiling_dict.keys())

@pytest.mark.xfail(
reason="query_graph HTML renderer (duckdb/query_graph/__main__.py) is not yet updated for the "
"restructured profiling output: it still walks the old flat children/operator_type/cpu_time tree and "
"reads flat metric keys (latency, total_bytes_read, ...) that are now grouped under "
"query/system/io/operator. Needs a renderer rewrite. See memory: project_query_graph_renderer_outdated.",
strict=False,
)
def test_profiler_html_output(self, profiling_connection, tmp_path_factory):
tmp_dir = tmp_path_factory.mktemp("profiler", numbered=True)
def test_profiler_html_output(self, profiling_connection, tmp_path):
profiling_info = ProfilingInfo(profiling_connection)
# Test HTML execution works, nothing to assert!
profiling_info.to_html(output_file=f"{tmp_dir}/profiler_output.html")
output = tmp_path / "profiler_output.html"
profiling_info.to_html(output_file=str(output))

html = output.read_text(encoding="utf8")
assert "SELECT 42" in html
assert "<b>PROJECTION</b>" in html
assert "Execution Time (s)" in html
total_time = profiling_info.to_pydict()["query"]["total_time"]
assert f'<div class="metric-value">{total_time:.4f}</div>' in html

def test_saved_flat_profile_html_output(self, tmp_path):
source = tmp_path / "profile.json"
source.write_text(
json.dumps(
{
"query_name": "SELECT 1",
"latency": 0.0,
"cpu_time": 0.0,
"children": [
{
"operator_type": "PROJECTION",
"operator_timing": 0.0,
"operator_cardinality": 1,
"result_set_size": 4,
"extra_info": {},
"children": [],
}
],
}
),
encoding="utf8",
)
output = tmp_path / "profile.html"
ProfilingInfo(from_file=str(source)).to_html(output_file=str(output))

html = output.read_text(encoding="utf8")
assert "SELECT 1" in html
assert "<b>PROJECTION</b>" in html