diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ed692035e..67594df09 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -42,7 +42,7 @@ repos: pass_filenames: false args: [ duckdb, _duckdb-stubs ] files: ^(duckdb/|_duckdb-stubs/|pyproject\.toml$) - exclude: ^duckdb/(experimental|query_graph)/ + exclude: ^duckdb/experimental/ additional_dependencies: [ numpy, polars ] - repo: local diff --git a/AGENTS.md b/AGENTS.md index 4a06749cb..5d2a92ba9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -334,7 +334,7 @@ engine's frames (tests skip those cases on 3.12). │ ├── filesystem.py # fsspec integration │ ├── func/, sqltypes/, value/ │ ├── polars_io.py, udf.py -│ └── query_graph/ # (old, unmaintained) +│ └── query_graph/ # renders a JSON profile as an HTML page ├── adbc_driver_duckdb/ # ADBC driver package ├── _duckdb-stubs/ # type stubs (*.pyi) ├── src/ # C++ extension source (nanobind), one object library per subdirectory diff --git a/duckdb/query_graph/__init__.py b/duckdb/query_graph/__init__.py index 340dd8d37..f208ad1df 100644 --- a/duckdb/query_graph/__init__.py +++ b/duckdb/query_graph/__init__.py @@ -1,3 +1,684 @@ -from .__main__ import ProfilingInfo # noqa: D104 +"""Render a DuckDB JSON profile as an HTML page with the query metrics and the operator tree. -__all__ = ["ProfilingInfo"] +The profile is the grouped document a DuckDB 2.x engine writes with ``SET enable_profiling = 'json'`` and +``SET profile_output = 'profile.json'``, or returns from ``connection.get_profiling_information("json")``. +""" + +import argparse +import html +import json +import re +import sys +import webbrowser +from pathlib import Path +from typing import IO, Any, NoReturn + +from duckdb import DuckDBPyConnection + +__all__ = ["ProfilingInfo", "main"] + +Profile = dict[str, Any] +Node = dict[str, Any] + +qgraph_css = """ +:root { + --text-primary-color: #0d0d0d; + --text-secondary-color: #444; + --doc-codebox-border-color: #e6e6e6; + --doc-codebox-background-color: #f7f7f7; + --doc-scrollbar-bg: #e6e6e6; + --doc-scrollbar-slider: #ccc; + --duckdb-accent: #009982; + --duckdb-accent-light: #00b89a; + --card-bg: #fff; + --border-radius: 8px; + --shadow: 0 4px 14px rgba(0,0,0,0.05); +} + +html, body { + margin: 0; + padding: 0; + font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + color: var(--text-primary-color); + background: #fafafa; + line-height: 1.55; +} + +.container { + max-width: 1000px; + margin: 40px auto; + padding: 0 20px; +} + +header { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 5px; +} + +header img { + width: 100px; + height: 100px; +} + +header h1 { + font-size: 1.5rem; + font-weight: 600; + margin: 0; + color: var(--text-primary-color); +} + +/* === Table Styling (DuckDB documentation style, flat header) === */ +table { + border-collapse: collapse; + width: 100%; + margin-bottom: 20px; + text-align: left; + font-variant-numeric: tabular-nums; + border: 1px solid var(--doc-codebox-border-color); + border-radius: var(--border-radius); + overflow: hidden; + box-shadow: var(--shadow); + background: var(--card-bg); +} + +thead { + background-color: var(--duckdb-accent); + color: white; +} + +th, td { + padding: 10px 12px; + font-size: 14px; + vertical-align: top; +} + +th { + font-weight: 700; +} + +tbody tr { + border-bottom: 1px solid var(--doc-codebox-border-color); +} + +tbody tr:last-child td { + border-bottom: none; +} + +tbody tr:hover { + background: var(--doc-codebox-border-color); +} + +tbody tr.phase-details-row { + border-bottom: none; +} + +tbody tr.phase-details-row:hover { + background: transparent; +} + +tbody tr.phase-details-row details summary { + font-size: 12px; + padding: 4px 0; +} + +tbody tr.phase-details-row details[open] summary { + margin-bottom: 4px; +} + +/* === Chart/Card Section === */ +.chart { + padding: 20px; + border: 1px solid var(--doc-codebox-border-color); + border-radius: var(--border-radius); + background: var(--card-bg); + box-shadow: var(--shadow); + overflow: visible; +} + +/* === Tree Layout Styling === */ +.tf-tree { + overflow-x: visible; + overflow-y: visible; + padding-top: 20px; +} + +.tf-nc { + background: var(--card-bg); + border: 1px solid var(--doc-codebox-border-color); + border-radius: var(--border-radius); + padding: 6px; + display: inline-block; +} + +.node-body { + font-size: 13px; + text-align: left; + padding: 10px; + white-space: nowrap; +} + +.node-body p { + margin: 2px 0; +} + +.node-details { + white-space: nowrap; + overflow: visible; + display: inline-block; +} + +/* === Metric Boxes === */ +.chart .metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + gap: 16px; + margin-bottom: 20px; +} + +.chart .metric-box { + background: var(--card-bg); + border: 1px solid var(--doc-codebox-border-color); + border-radius: var(--border-radius); + box-shadow: var(--shadow); + padding: 12px 16px; + text-align: center; + transition: transform 0.2s ease, box-shadow 0.2s ease; +} + +.chart .metric-box:hover { + transform: translateY(-2px); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08); +} + +.chart .metric-title { + font-size: 13px; + color: var(--text-secondary-color); + margin-bottom: 4px; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.chart .metric-value { + font-size: 18px; + font-weight: 600; + color: var(--duckdb-accent); +} + + +/* === SQL Query Block === */ +.chart.sql-block { + background: var(--doc-codebox-background-color); + border: 1px solid var(--doc-codebox-border-color); + border-radius: var(--border-radius); + box-shadow: var(--shadow); + padding: 16px; + overflow-x: auto; + margin-top: 20px; +} + +.chart.sql-block pre { + margin: 0; + font-family: "JetBrains Mono", "Fira Code", Consolas, monospace; + font-size: 13.5px; + line-height: 1.5; + color: var(--text-primary-color); + white-space: pre; +} + +.chart.sql-block code { + color: var(--duckdb-accent); + font-weight: 500; +} + + +/* === Links, Typography, and Consistency === */ +a { + color: var(--duckdb-accent); + text-decoration: underline; + transition: color 0.3s; +} + +a:hover { + color: black; +} + +strong { + font-weight: 600; +} + +/* === Dark Mode Support === */ +@media (prefers-color-scheme: dark) { + :root { + --text-primary-color: #e6e6e6; + --text-secondary-color: #b3b3b3; + --doc-codebox-border-color: #2a2a2a; + --doc-codebox-background-color: #1e1e1e; + --card-bg: #111; + } + body { + background: #0b0b0b; + } + thead { + background-color: var(--duckdb-accent); + } + tbody tr:hover { + background: #222; + } + + /* Fix tree node text visibility in dark mode */ + .tf-nc .node-body, + .tf-nc .node-body p, + .tf-nc .node-details { + color: #1a1a1a !important; + } + + /* Fix metric title visibility in dark mode */ + .chart .metric-title { + color: #b3b3b3; + } +} +""" # noqa: W293 + + +def open_utf8(fpath: str, flags: str) -> IO[Any]: + return Path(fpath).open(mode=flags, encoding="utf8") + + +def _escape(text: object) -> str: + return html.escape(str(text), quote=False) + + +def _seconds(value: float | None) -> str: + return "N/A" if value is None else f"{float(value):.4f}" + + +def _gigabytes(value: float | None) -> str: + return "N/A" if value is None else f"{float(value) / (1024**3):.4f}" + + +def _count(value: int | None) -> str: + return "N/A" if value is None else f"{int(value):,}" + + +def _percent(time: float, total: float) -> str: + return f"{time / total * 100 if total else 0.0:.4f}%" + + +def _group(profile: Profile, name: str) -> Profile: + group = profile.get(name) + return group if isinstance(group, dict) else {} + + +def _children(node: Node) -> list[Node]: + children = node.get("children") + return [child for child in children if isinstance(child, dict)] if isinstance(children, list) else [] + + +def _operators(roots: list[Node]) -> list[tuple[Node, int]]: + """Every operator with its depth, in the order the engine wrote them, without recursion.""" + result = [] + stack = [(root, 0) for root in reversed(roots)] + while stack: + node, depth = stack.pop() + result.append((node, depth)) + stack.extend((child, depth + 1) for child in reversed(_children(node))) + return result + + +def _headline(node: Node) -> str: + label = node.get("type", node.get("name")) + return "OPERATOR" if label is None else str(label).replace("_", " ") + + +# The compressed materialization optimizer names its functions __internal_compress_integral_; a details line +# full of them reads better short, and no other text is touched. +_ENGINE_COMPRESS_FUNCTION = re.compile(r"\b__internal_((?:de)?compress)_integral_(\w+)\(") + + +def _detail_value(value: object) -> str: + text = ", ".join(str(item) for item in value) if isinstance(value, list) else str(value) + return _ENGINE_COMPRESS_FUNCTION.sub(r"__\1_\2(", text) + + +SCAN_KEYS = ("rows_scanned", "row_groups_scanned", "total_row_groups_to_scan", "bytes_scanned") + + +class ProfilingInfo: + """The profile of the last query on a connection, or a profile read from a file.""" + + def __init__(self, conn: DuckDBPyConnection | None = None, from_file: str | None = None) -> None: # noqa: D107 + self.conn = conn + self.from_file = from_file + + def to_json(self) -> str: # noqa: D102 + if self.from_file is not None: + with open_utf8(self.from_file, "r") as f: + text: str = f.read() + return text + if self.conn is None: + msg = "ProfilingInfo needs a connection or a file to read the profile from" + raise ValueError(msg) + profile: str = self.conn.get_profiling_information(format="json") + return profile + + def to_pydict(self) -> Profile: # noqa: D102 + profile: Profile = json.loads(self.to_json()) + return profile + + def to_html(self, output_file: str = "profile.html") -> str: + """Write the profile as an HTML page to output_file and return the page text.""" + page = self._render_html() + with open_utf8(output_file, "w") as f: + f.write(page) + return page + + def _render_html(self) -> str: + try: + text = self.to_json() + except UnicodeDecodeError as e: + msg = f"{self._source_name()} is not a UTF-8 text file: {e}" + raise ValueError(msg) from e + return self._render_page(self._parse_profile(text)) + + def _source_name(self) -> str: + return self.from_file if self.from_file is not None else "the connection's profiling output" + + def _parse_profile(self, text: str) -> Profile: + source = self._source_name() + try: + profile = json.loads(text) + except json.JSONDecodeError as e: + msg = f"{source} is not a JSON profile: {e}" + raise ValueError(msg) from e + except RecursionError as e: + # An operator nests two JSON levels. Python 3.11's decoder counts them against the recursion limit of + # 1000, so about 500 operators; 3.12 and 3.13 against the platform's C recursion limit, about 5000 + # operators on Linux and macOS, about 1500 on Windows (also ARM64 with 3.12) and about 500 on Windows + # ARM64 with 3.13; 3.14 is bounded by the thread's stack, 20000 and more in the main thread on Linux. + msg = f"{source} nests its operators deeper than this Python's JSON decoder can read" + raise ValueError(msg) from e + if not isinstance(profile, dict): + msg = f"{source} is not a profile: expected a JSON object, got {type(profile).__name__}" + raise ValueError(msg) # noqa: TRY004 + # Every flat profile, from DuckDB 1.0 on and under legacy_metrics_format, has a top level "children" list. + if "children" in profile: + msg = ( + f"{source} is in the flat profiling format of DuckDB 1.x, which a 2.x engine writes only with " + "legacy_metrics_format = true; profile the query with a 2.x engine's default format to render it" + ) + raise ValueError(msg) + if set(profile) == {"result"}: + msg = f"{source} holds no query to render (result: {profile['result']})" + raise ValueError(msg) + return profile + + @staticmethod + def _metric_grid_html(profile: Profile) -> str: + query = _group(profile, "query") + io = _group(profile, "io") + system = _group(profile, "system") + metrics = { + "Execution Time (s)": _seconds(query.get("total_time")), + "CPU Time (s)": _seconds(query.get("cpu_time")), + "Total GB Read": _gigabytes(io.get("total_bytes_read")), + "Total GB Written": _gigabytes(io.get("total_bytes_written")), + "Peak Memory (GB)": _gigabytes(system.get("peak_buffer_memory")), + "Rows Scanned": _count(query.get("total_rows_scanned")), + } + boxes = "".join( + f""" +
+
{title}
+
{value}
+
+ """ + for title, value in metrics.items() + ) + return f'
{boxes}
' + + @staticmethod + def _sql_html(profile: Profile) -> str: + sql = _group(profile, "query").get("sql") + return f""" +
SQL Query +
+
{_escape(sql) if sql is not None else "N/A"}
+
+

+ """ + + @staticmethod + def _timing_table_html(nodes: list[tuple[Node, int]]) -> str: + timed = [(node, depth) for node, depth in nodes if "timing" in node] + if not timed: + return "" + total = sum(float(node["timing"]) for node, _ in timed) + + per_type: dict[str, list[tuple[float, int]]] = {} + for node, depth in timed: + per_type.setdefault(_headline(node), []).append((float(node["timing"]), depth)) + phases = sorted(per_type, key=lambda phase: sum(time for time, _ in per_type[phase]), reverse=True) + + rows = f""" + + Execution Time (CPU) + {round(total, 8)} + {_percent(total, total)} + + """ + for phase in phases: + timings = per_type[phase] + phase_time = sum(time for time, _ in timings) + rows += f""" + + {_escape(phase)} + {round(phase_time, 8)} + {_percent(phase_time, total)} + + """ + if len(timings) > 1: + node_rows = "".join( + f""" + + {" " * (depth * 4)}↳ Depth {depth} + {round(time, 8)} + {_percent(time, total)} + + """ # noqa: E501 + for time, depth in sorted(timings, key=lambda entry: entry[0], reverse=True) + ) + rows += f""" + + +
+ + Show {len(timings)} nodes + + + {node_rows} + +
+
+ + + """ + return f""" + + + + + + + + {rows}
PhaseTime (s)Percentage
""" + + @staticmethod + def _shade_hex(fraction: float) -> str: + """A shade from very light (#f7fff0) to a darker green-yellow for a fraction between 0 and 1.""" + fraction = max(0.0, min(1.0, fraction)) + light_color = (247, 255, 240) + dark_color = (200, 255, 150) + r, g, b = (int(light + (dark - light) * fraction) for light, dark in zip(light_color, dark_color, strict=True)) + return f"#{r:02x}{g:02x}{b:02x}" + + def _node_html(self, node: Node, shade_total: float | None) -> str: + extra_info = node.get("extra_info") + extra_info = extra_info if isinstance(extra_info, dict) else {} + timing = node.get("timing") + fraction = float(timing) / shade_total if timing is not None and shade_total else 0.0 + + body = f'' + body += '
' + body += f"

{_escape(_headline(node))}

" + if "type" in node and "name" in node and node["name"] != node["type"]: + body += f"

name: {_escape(node['name'])}

" + if timing is not None: + body += f"

time: {float(timing):.4f}s

" + if "intermediate_rows" in node: + body += f"

cardinality: {_escape(node['intermediate_rows'])}

" + if "Estimated Cardinality" in extra_info: + body += f"

estimate: {_escape(extra_info['Estimated Cardinality'])}

" + if "intermediate_size_bytes" in node: + body += f"

result size: {_escape(node['intermediate_size_bytes'])} bytes

" + + details = [(key, node[key]) for key in SCAN_KEYS if key in node] + details += [(key, value) for key, value in extra_info.items() if key != "Estimated Cardinality"] + lines = "".join(f"{_escape(key)}: {_escape(_detail_value(value))}
" for key, value in details) + body += "
" + body += "Extra info" + body += '
' + body += f"

{lines}

" + body += "
" + body += "
" + body += "
" + body += "
" + return body + + def _tree_html(self, profile: Profile, roots: list[Node], nodes: list[tuple[Node, int]]) -> str: + if not roots: + return ( + '

The profile holds no operator metrics; ' + "set tracked_metrics to include operator.* to see the operator tree.

" + ) + cpu_time = _group(profile, "query").get("cpu_time") + if cpu_time: + shade_total = float(cpu_time) + else: + shade_total = sum(float(node["timing"]) for node, _ in nodes if "timing" in node) + + # An explicit stack keeps a deep plan from hitting the recursion limit; a string entry closes a parent. + parts = ['
\n
") + return "".join(parts) + + def _render_page(self, profile: Profile) -> str: + operator = profile.get("operator") + roots = [root for root in operator if isinstance(root, dict)] if isinstance(operator, list) else [] + nodes = _operators(roots) + metric_grid = self._metric_grid_html(profile) + sql_block = self._sql_html(profile) + timing_table = self._timing_table_html(nodes) + tree = self._tree_html(profile, roots, nodes) + return f""" + + + + + Query Profile Graph for Query + + + + +
+
+ DuckDB Logo +

Query Profile Graph

+
+
+ {metric_grid} +
+
+ {sql_block} + {timing_table} +
+ {tree} +
+ + + """ # noqa: E501 + + +def _fail(message: str) -> NoReturn: + print(f"query_graph: {message}", file=sys.stderr) + sys.exit(1) + + +def main() -> None: + """Render a JSON profile file to HTML from the command line.""" + parser = argparse.ArgumentParser( + prog="python -m duckdb.query_graph", + description="Given a JSON profile written by DuckDB, generate an HTML file showing the query graph and the " + "timings of its operators.", + ) + parser.add_argument("profile", nargs="?", help="the JSON profile written with SET enable_profiling = 'json'") + parser.add_argument("--profile_input", help="the same path as the positional argument, kept for older scripts") + parser.add_argument("--out", help="the HTML file to write; defaults to the profile path with .html") + parser.add_argument( + "--open", + action=argparse.BooleanOptionalAction, + default=True, + help="open the HTML file in the browser once written (the default)", + ) + args = parser.parse_args() + + if args.profile is not None and args.profile_input is not None and args.profile != args.profile_input: + parser.error("the profile path was given twice with different values") + profile_path: str | None = args.profile if args.profile is not None else args.profile_input + if profile_path is None: + parser.error("the path of a JSON profile is required") + + if args.out is not None: + if not args.out.endswith(".html"): + _fail("the output file must end in .html") + output_path: str = args.out + elif profile_path.endswith(".json"): + output_path = profile_path[: -len(".json")] + ".html" + else: + _fail("the profile must be a .json file when --out is not given") + + if Path(output_path).resolve() == Path(profile_path).resolve(): + _fail(f"the output path {output_path} is the input profile; choose another --out") + + try: + page = ProfilingInfo(from_file=profile_path)._render_html() + except ValueError as e: + _fail(str(e)) + except OSError as e: + _fail(f"could not read the profile {profile_path}: {e.strerror or e}") + try: + with open_utf8(output_path, "w") as f: + f.write(page) + except OSError as e: + _fail(f"could not write the output file {output_path}: {e.strerror or e}") + + print(f"query_graph: wrote {output_path}") + if args.open: + webbrowser.open(Path(output_path).resolve().as_uri(), new=2) diff --git a/duckdb/query_graph/__main__.py b/duckdb/query_graph/__main__.py index dd4ff9591..6aa330469 100644 --- a/duckdb/query_graph/__main__.py +++ b/duckdb/query_graph/__main__.py @@ -1,672 +1,6 @@ -import argparse # noqa: D100 -import json -import re -import webbrowser -from functools import reduce -from pathlib import Path - -from duckdb import DuckDBPyConnection - -qgraph_css = """ -:root { - --text-primary-color: #0d0d0d; - --text-secondary-color: #444; - --doc-codebox-border-color: #e6e6e6; - --doc-codebox-background-color: #f7f7f7; - --doc-scrollbar-bg: #e6e6e6; - --doc-scrollbar-slider: #ccc; - --duckdb-accent: #009982; - --duckdb-accent-light: #00b89a; - --card-bg: #fff; - --border-radius: 8px; - --shadow: 0 4px 14px rgba(0,0,0,0.05); -} - -html, body { - margin: 0; - padding: 0; - font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; - color: var(--text-primary-color); - background: #fafafa; - line-height: 1.55; -} - -.container { - max-width: 1000px; - margin: 40px auto; - padding: 0 20px; -} - -header { - display: flex; - align-items: center; - gap: 10px; - margin-bottom: 5px; -} - -header img { - width: 100px; - height: 100px; -} - -header h1 { - font-size: 1.5rem; - font-weight: 600; - margin: 0; - color: var(--text-primary-color); -} - -/* === Table Styling (DuckDB documentation style, flat header) === */ -table { - border-collapse: collapse; - width: 100%; - margin-bottom: 20px; - text-align: left; - font-variant-numeric: tabular-nums; - border: 1px solid var(--doc-codebox-border-color); - border-radius: var(--border-radius); - overflow: hidden; - box-shadow: var(--shadow); - background: var(--card-bg); -} - -thead { - background-color: var(--duckdb-accent); - color: white; -} - -th, td { - padding: 10px 12px; - font-size: 14px; - vertical-align: top; -} - -th { - font-weight: 700; -} - -tbody tr { - border-bottom: 1px solid var(--doc-codebox-border-color); -} - -tbody tr:last-child td { - border-bottom: none; -} - -tbody tr:hover { - background: var(--doc-codebox-border-color); -} - -tbody tr.phase-details-row { - border-bottom: none; -} - -tbody tr.phase-details-row:hover { - background: transparent; -} - -tbody tr.phase-details-row details summary { - font-size: 12px; - padding: 4px 0; -} - -tbody tr.phase-details-row details[open] summary { - margin-bottom: 4px; -} - -/* === Chart/Card Section === */ -.chart { - padding: 20px; - border: 1px solid var(--doc-codebox-border-color); - border-radius: var(--border-radius); - background: var(--card-bg); - box-shadow: var(--shadow); - overflow: visible; -} - -/* === Tree Layout Styling === */ -.tf-tree { - overflow-x: visible; - overflow-y: visible; - padding-top: 20px; -} - -.tf-nc { - background: var(--card-bg); - border: 1px solid var(--doc-codebox-border-color); - border-radius: var(--border-radius); - padding: 6px; - display: inline-block; -} - -.node-body { - font-size: 13px; - text-align: left; - padding: 10px; - white-space: nowrap; -} - -.node-body p { - margin: 2px 0; -} - -.node-details { - white-space: nowrap; - overflow: visible; - display: inline-block; -} - -/* === Metric Boxes === */ -.chart .metrics-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); - gap: 16px; - margin-bottom: 20px; -} - -.chart .metric-box { - background: var(--card-bg); - border: 1px solid var(--doc-codebox-border-color); - border-radius: var(--border-radius); - box-shadow: var(--shadow); - padding: 12px 16px; - text-align: center; - transition: transform 0.2s ease, box-shadow 0.2s ease; -} - -.chart .metric-box:hover { - transform: translateY(-2px); - box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08); -} - -.chart .metric-title { - font-size: 13px; - color: var(--text-secondary-color); - margin-bottom: 4px; - text-transform: uppercase; - letter-spacing: 0.5px; -} - -.chart .metric-value { - font-size: 18px; - font-weight: 600; - color: var(--duckdb-accent); -} - - -/* === SQL Query Block === */ -.chart.sql-block { - background: var(--doc-codebox-background-color); - border: 1px solid var(--doc-codebox-border-color); - border-radius: var(--border-radius); - box-shadow: var(--shadow); - padding: 16px; - overflow-x: auto; - margin-top: 20px; -} - -.chart.sql-block pre { - margin: 0; - font-family: "JetBrains Mono", "Fira Code", Consolas, monospace; - font-size: 13.5px; - line-height: 1.5; - color: var(--text-primary-color); - white-space: pre; -} - -.chart.sql-block code { - color: var(--duckdb-accent); - font-weight: 500; -} - - -/* === Links, Typography, and Consistency === */ -a { - color: var(--duckdb-accent); - text-decoration: underline; - transition: color 0.3s; -} - -a:hover { - color: black; -} - -strong { - font-weight: 600; -} - -/* === Dark Mode Support === */ -@media (prefers-color-scheme: dark) { - :root { - --text-primary-color: #e6e6e6; - --text-secondary-color: #b3b3b3; - --doc-codebox-border-color: #2a2a2a; - --doc-codebox-background-color: #1e1e1e; - --card-bg: #111; - } - body { - background: #0b0b0b; - } - thead { - background-color: var(--duckdb-accent); - } - tbody tr:hover { - background: #222; - } - - /* Fix tree node text visibility in dark mode */ - .tf-nc .node-body, - .tf-nc .node-body p, - .tf-nc .node-details { - color: #1a1a1a !important; - } - - /* Fix metric title visibility in dark mode */ - .chart .metric-title { - color: #b3b3b3; - } -} -""" # noqa: W293 - - -class NodeTiming: # noqa: D101 - def __init__(self, phase: str, time: float, depth: int) -> None: # noqa: D107 - self.phase = phase - self.time = time - self.depth = depth - # percentage is determined later. - self.percentage = 0 - - def calculate_percentage(self, total_time: float) -> None: # noqa: D102 - self.percentage = self.time / total_time - - def combine_timing(self, r: "NodeTiming") -> "NodeTiming": # noqa: D102 - # TODO: can only add timings for same-phase nodes # noqa: TD002, TD003 - total_time = self.time + r.time - return NodeTiming(self.phase, total_time, self.depth) - - -class AllTimings: # noqa: D101 - def __init__(self) -> None: # noqa: D107 - self.phase_to_timings = {} - - def add_node_timing(self, node_timing: NodeTiming) -> None: # noqa: D102 - if node_timing.phase in self.phase_to_timings: - self.phase_to_timings[node_timing.phase].append(node_timing) - else: - self.phase_to_timings[node_timing.phase] = [node_timing] - - def get_phase_timings(self, phase: str) -> list[NodeTiming]: # noqa: D102 - return self.phase_to_timings[phase] - - def get_summary_phase_timings(self, phase: str) -> NodeTiming: # noqa: D102 - return reduce(NodeTiming.combine_timing, self.phase_to_timings[phase]) - - def get_phases(self) -> list[NodeTiming]: # noqa: D102 - phases = list(self.phase_to_timings.keys()) - phases.sort(key=lambda x: (self.get_summary_phase_timings(x)).time) - phases.reverse() - return phases - - def get_sum_of_all_timings(self) -> float: # noqa: D102 - total_timing_sum = 0 - for phase in self.phase_to_timings: - total_timing_sum += self.get_summary_phase_timings(phase).time - return total_timing_sum - - -def open_utf8(fpath: str, flags: str) -> object: # noqa: D103 - return Path(fpath).open(mode=flags, encoding="utf8") - - -class ProfilingInfo: # noqa: D101 - def __init__(self, conn: DuckDBPyConnection | None = None, from_file: str | None = None) -> None: # noqa: D107 - self.conn = conn - self.from_file = from_file - - def to_json(self) -> str: # noqa: D102 - if self.from_file is not None: - with open_utf8(self.from_file, "r") as f: - return f.read() - - return self.conn.get_profiling_information(format="json") - - def to_pydict(self) -> dict: # noqa: D102 - return json.loads(self.to_json()) - - def to_html(self, output_file: str = "profile.html") -> str: # noqa: D102 - profiling_info_text = self.to_json() - html_output = self._translate_json_to_html(input_text=profiling_info_text, output_file=output_file) - return html_output - - def _get_child_timings(self, top_node: object, query_timings: object, depth: int = 0) -> str: - node_timing = NodeTiming(top_node["operator_type"], float(top_node["operator_timing"]), depth) - query_timings.add_node_timing(node_timing) - for child in top_node["children"]: - self._get_child_timings(child, query_timings, depth + 1) - - @staticmethod - def _get_f7fff0_shade_hex(fraction: float) -> str: - """Returns a shade between very light (#f7fff0) and a slightly darker green-yellow, - depending on the fraction (0..1). - """ # noqa: D205 - fraction = max(0, min(1, fraction)) - - # Define RGB for light and dark end - light_color = (247, 255, 240) # #f7fff0 - dark_color = (200, 255, 150) # slightly darker/more saturated green-yellow - - # Interpolate RGB channels - r = int(light_color[0] + (dark_color[0] - light_color[0]) * fraction) - g = int(light_color[1] + (dark_color[1] - light_color[1]) * fraction) - b = int(light_color[2] + (dark_color[2] - light_color[2]) * fraction) - - return f"#{r:02x}{g:02x}{b:02x}" - - 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)};" - new_name = "BRIDGE" if (name == "INVALID") else name.replace("_", " ") - formatted_num = f"{float(result):.4f}" - - body = f'' - body += '
' - body += f"

{new_name}

" - if result_size > 0: - body += f"

time: {formatted_num}s

" - body += f"

cardinality: {card}

" - body += f"

estimate: {est}

" - body += f"

result size: {result_size} bytes

" - body += "
" - body += "Extra info" - body += '
' - body += f"

{extra_info}

" - # TODO: Expand on timing. Usually available from a detailed profiling # noqa: TD002, TD003 - body += "
" - body += "
" - body += "
" - body += "
" - return body - - def _generate_tree_recursive(self, json_graph: object, cpu_time: float) -> str: - node_prefix_html = "
  • " - node_suffix_html = "
  • " - - extra_info = "" - estimate = 0 - for key in json_graph["extra_info"]: - value = json_graph["extra_info"][key] - if key == "Estimated Cardinality": - estimate = int(value) - else: - extra_info += f"{key}: {value}
    " - - # get rid of some typically long names - extra_info = re.sub(r"__internal_\s*", "__", extra_info) - extra_info = re.sub(r"compress_integral\s*", "compress", extra_info) - - node_body = self._get_node_body( - json_graph["operator_type"], - json_graph["operator_timing"], - cpu_time, - json_graph["operator_cardinality"], - estimate, - json_graph["result_set_size"], - re.sub(r",\s*", ", ", extra_info), - ) - - children_html = "" - if len(json_graph["children"]) >= 1: - children_html += "" - 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: - """Generates timing HTML table with expandable phases.""" - json_graph = json.loads(graph_json) - self._gather_timing_information(json_graph, query_timings) - table_head = """ - - - - - - - - """ - - table_body = "" - table_end = "
    PhaseTime (s)Percentage
    " - - execution_time = query_timings.get_sum_of_all_timings() - - all_phases = query_timings.get_phases() - query_timings.add_node_timing(NodeTiming("Execution Time (CPU)", execution_time, None)) - all_phases = ["Execution Time (CPU)", *all_phases] - - for phase in all_phases: - summarized_phase = query_timings.get_summary_phase_timings(phase) - summarized_phase.calculate_percentage(execution_time) - phase_column = f"{phase}" if phase == "Execution Time (CPU)" else phase - - # Main phase row - table_body += f""" - - {phase_column} - {round(summarized_phase.time, 8)} - {str(summarized_phase.percentage * 100)[:6]}% - - """ - - # Add expandable details for individual nodes (except for Execution Time) - if phase != "Execution Time (CPU)": - phase_timings = query_timings.get_phase_timings(phase) - if len(phase_timings) > 1: # Only show details if there are multiple nodes - table_body += f""" - - -
    - - Show {len(phase_timings)} nodes - - - - """ - for node_timing in sorted(phase_timings, key=lambda x: x.time, reverse=True): - node_timing.calculate_percentage(execution_time) - depth_indent = " " * (node_timing.depth * 4) - table_body += f""" - - - - - - """ # noqa: E501 - table_body += """ - -
    {depth_indent}↳ Depth {node_timing.depth}{round(node_timing.time, 8)}{str(node_timing.percentage * 100)[:6]}%
    -
    - - - """ - - table_body += table_end - return table_head + table_body - - @staticmethod - def _generate_metric_grid_html(graph_json: str) -> str: - json_graph = json.loads(graph_json) - metrics = { - "Execution Time (s)": f"{float(json_graph.get('latency', 'N/A')):.4f}", - "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", - "Total GB Written": f"{float(json_graph.get('total_bytes_written', 'N/A')) / (1024**3):.4f}" - if json_graph.get("total_bytes_written", "N/A") != "N/A" - else "N/A", - "Peak Memory (GB)": f"{float(json_graph.get('system_peak_buffer_memory', 'N/A')) / (1024**3):.4f}" - if json_graph.get("system_peak_buffer_memory", "N/A") != "N/A" - else "N/A", - "Rows Scanned": f"{json_graph.get('cumulative_rows_scanned', 'N/A'):,}" - if json_graph.get("cumulative_rows_scanned", "N/A") != "N/A" - else "N/A", - } - metric_grid_html = """
    """ - for key in metrics: - metric_grid_html += f""" -
    -
    {key}
    -
    {metrics[key]}
    -
    - """ - metric_grid_html += "
    " - return metric_grid_html - - @staticmethod - def _generate_sql_query_html(graph_json: str) -> str: - json_graph = json.loads(graph_json) - sql_query = json_graph.get("query_name", "N/A") - sql_html = f""" -
    SQL Query -
    -
    
    -    {sql_query}
    -            
    -
    -

    - """ - 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"]) - tree_prefix = '
    \n
    " - # 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) - return tree_prefix + tree_body + tree_suffix - - def _generate_ipython(self, json_input: str) -> str: - from IPython.core.display import HTML - - html_output = self._generate_html(json_input, False) - - return HTML( - ( - '\n ${CSS}\n ${LIBRARIES}\n
    \n ${CHART_SCRIPT}\n ' - ) - .replace("${CSS}", html_output["css"]) - .replace("${CHART_SCRIPT}", html_output["chart_script"]) - .replace("${LIBRARIES}", html_output["libraries"]) - ) - - @staticmethod - def _generate_style_html(graph_json: str, include_meta_info: bool) -> None: # noqa: FBT001 - treeflex_css = '\n' - libraries = '\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 _translate_json_to_html( - self, input_file: str | None = None, input_text: str | None = None, output_file: str = "profile.html" - ) -> None: - query_timings = AllTimings() - if input_text is not None: - text = input_text - elif input_file is not None: - with open_utf8(input_file, "r") as f: - text = f.read() - else: - 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) - # finally create and write the html - with open_utf8(output_file, "w+") as f: - html = """ - - - - - Query Profile Graph for Query - ${TREEFLEX_CSS} - - - -
    -
    - DuckDB Logo -

    Query Profile Graph

    -
    -
    - ${METRIC_GRID} -
    -
    - ${SQL_QUERY} - ${TIMING_TABLE} -
    - ${TREE} - - - """ # noqa: E501 - html = html.replace("${TREEFLEX_CSS}", html_output["treeflex_css"]) - html = html.replace("${DUCKDB_CSS}", html_output["duckdb_css"]) - html = html.replace("${METRIC_GRID}", highlight_metric_grid) - html = html.replace("${SQL_QUERY}", sql_query_html) - html = html.replace("${TIMING_TABLE}", timing_table) - html = html.replace("${TREE}", tree_output) - f.write(html) - - -def main() -> None: # noqa: D103 - parser = argparse.ArgumentParser( - prog="Query Graph Generator", - description="""Given a json profile output, generate a html file showing the query graph and - timings of operators""", - ) - parser.add_argument("--profile_input", help="profile input in json") - parser.add_argument("--out", required=False, default=False) - parser.add_argument("--open", required=False, action="store_true", default=True) - args = parser.parse_args() - - input = args.profile_input - output = args.out - if not args.out: - if ".json" in input: - output = input.replace(".json", ".html") - else: - print("please provide profile output in json") - exit(1) - else: - if ".html" in args.out: - output = args.out - else: - print("please provide valid .html file for output name") - exit(1) - - open_output = args.open - profiling_info = ProfilingInfo(from_file=input) - profiling_info.to_html(output_file=output) - - if open_output: - webbrowser.open(f"file://{Path(output).resolve()}", new=2) +from duckdb.query_graph import ProfilingInfo, main # noqa: D100 +__all__ = ["ProfilingInfo", "main"] if __name__ == "__main__": main() diff --git a/pyproject.toml b/pyproject.toml index e8972c4de..2588e0fc4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ Changelog = "https://github.com/duckdb/duckdb-python/releases" [project.optional-dependencies] all = [ # users can install duckdb with 'duckdb[all]', which will install this list - "ipython", # used in duckdb.query_graph + "ipython", # used by the Jupyter progress bar and the relation display in duckdb/_relation.py "fsspec", # used in duckdb.filesystem "numpy", # used in duckdb.fetchnumpy() "pandas", # used for pandas dataframes all over the place @@ -390,7 +390,6 @@ pretty = true python_version = "3.12" exclude = [ "duckdb/experimental/", # not checking the pyspark API - "duckdb/query_graph/", # old and unmaintained (should probably remove) "tests", "scripts", ] diff --git a/tests/fast/test_profiler.py b/tests/fast/test_profiler.py index d46e3d706..632c937d2 100644 --- a/tests/fast/test_profiler.py +++ b/tests/fast/test_profiler.py @@ -1,7 +1,15 @@ +import json +import re +import subprocess +import sys +import webbrowser +from html.parser import HTMLParser + import pytest import duckdb from duckdb.query_graph import ProfilingInfo +from duckdb.query_graph import main as query_graph_main @pytest.fixture(scope="session") @@ -36,15 +44,746 @@ 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) profiling_info = ProfilingInfo(profiling_connection) - # Test HTML execution works, nothing to assert! - profiling_info.to_html(output_file=f"{tmp_dir}/profiler_output.html") + page = profiling_info.to_html(output_file=f"{tmp_dir}/profiler_output.html") + assert page == (tmp_dir / "profiler_output.html").read_text(encoding="utf8") + assert "SELECT 42" in page + + +JOIN_SQL = "SELECT a.i, b.j\nFROM range(100) a(i) JOIN range(50) b(j) ON a.i = b.j\nWHERE a.i % 2 = 0\nORDER BY 1" + +GRID_TITLES = ( + "Execution Time (s)", + "CPU Time (s)", + "Total GB Read", + "Total GB Written", + "Peak Memory (GB)", + "Rows Scanned", +) + + +def engine_profile(sql: str, *settings: str) -> dict: + """The JSON profile the running engine writes for one query, as a dict.""" + con = duckdb.connect() + try: + for setting in settings: + con.execute(setting) + con.execute("SET enable_profiling = 'no_output'") + con.execute(sql).fetchall() + return json.loads(con.get_profiling_information("json")) + finally: + con.close() + + +def walk(node: dict) -> list[tuple[dict, int]]: + """The operator and its descendants with their depth, in the order the engine wrote them.""" + result = [] + stack = [(node, 0)] + while stack: + current, depth = stack.pop() + result.append((current, depth)) + stack.extend((child, depth + 1) for child in reversed(current.get("children", []))) + return result + + +def chain_profile(depth: int) -> dict: + """A plan of PROJECTION operators nested depth deep, as a dict.""" + root: dict = {"type": "PROJECTION", "name": "PROJECTION", "timing": 0.001, "extra_info": {}} + for _ in range(depth - 1): + root = {"type": "PROJECTION", "name": "PROJECTION", "timing": 0.001, "extra_info": {}, "children": [root]} + return {"query": {"total_time": 1.0, "cpu_time": 1.0, "sql": "deep"}, "operator": [root]} + + +def chain_profile_text(depth: int) -> str: + """The JSON text of chain_profile(depth), built without recursive encoding so any depth can be written.""" + node = '{"type": "PROJECTION", "name": "PROJECTION", "timing": 0.001, "extra_info": {}' + opening = (node + ', "children": [') * (depth - 1) + node + "}" + return '{"query": {"total_time": 1.0, "cpu_time": 1.0, "sql": "deep"}, "operator": [' + opening + "]}" * depth + + +class RenderedTree(HTMLParser): + """Rebuilds the operator tree of a page as a browser would nest it. + + Each node is a two element list [headline, children]. A browser closes an open li when the next li starts with + no ul open inside it, and a new li belongs to the li that owns the innermost open ul; a parser that only follows + li tags would nest B under A in
  • A
    • B
    • , where a browser shows B beside A. End tags follow + the browser too: a is ignored while a ul is still open inside the li (so
    • A
      • B
      • leaves + A's list open and the next li lands under A), and a
      is ignored when no ul is open. + """ + + def __init__(self) -> None: + super().__init__() + self.roots: list[list] = [] + self.stack: list[list | None] = [] # an open li as its node, an open ul as None + self.in_headline = False + + def handle_starttag(self, tag, attrs): + if tag == "ul": + self.stack.append(None) + elif tag == "li": + if self.stack and self.stack[-1] is not None: + self.stack.pop() + innermost_ul = max((i for i, entry in enumerate(self.stack) if entry is None), default=-1) + owner = next((entry for entry in reversed(self.stack[:innermost_ul]) if entry is not None), None) + node: list = ["", []] + (self.roots if owner is None else owner[1]).append(node) + self.stack.append(node) + elif tag == "b" and self.stack and self.stack[-1] is not None and not self.stack[-1][0]: + self.in_headline = True + + def handle_data(self, data): + if self.in_headline: + self.stack[-1][0] += data + + def handle_endtag(self, tag): + if tag == "b": + self.in_headline = False + elif tag == "li": + if self.stack and self.stack[-1] is not None: + self.stack.pop() + elif tag == "ul" and None in self.stack: + while self.stack.pop() is not None: + pass + + +def rendered_tree(html: str) -> list: + parser = RenderedTree() + parser.feed(html) + assert parser.stack == [] + return parser.roots + + +def expected_tree(node: dict) -> list: + """The (headline, children) shape of a profile's operator, built without recursion.""" + shapes: dict[int, list] = {} + for current, _ in reversed(walk(node)): + shapes[id(current)] = [ + current.get("type", current.get("name", "OPERATOR")).replace("_", " "), + [shapes[id(child)] for child in current.get("children", [])], + ] + return shapes[id(node)] + + +def operators(node: dict) -> list[dict]: + return [op for op, _ in walk(node)] + + +def copy_of(profile: dict) -> dict: + return json.loads(json.dumps(profile)) + + +def render(profile: dict | str | bytes, tmp_path) -> str: + """Render a profile (a dict, or the raw file content) through ProfilingInfo and return the HTML.""" + profile_file = tmp_path / "profile.json" + if isinstance(profile, bytes): + profile_file.write_bytes(profile) + else: + profile_file.write_text(profile if isinstance(profile, str) else json.dumps(profile), encoding="utf8") + out_file = tmp_path / "profile.html" + returned = ProfilingInfo(from_file=str(profile_file)).to_html(output_file=str(out_file)) + written = out_file.read_text(encoding="utf8") + assert returned == written + return written + + +def grid_value(html: str, title: str) -> str: + """The value shown in the metric box with the given title.""" + pattern = rf'
      {re.escape(title)}
      \s*
      ([^<]*)
      ' + matches = re.findall(pattern, html) + assert len(matches) == 1, f"{title}: {matches}" + return matches[0] + + +def headlines(html: str) -> list[str]: + return re.findall(r"

      ([^<]+)

      ", html) + + +def node_shades(html: str) -> list[str]: + return re.findall(r'
    • ', html) + + +def percentage_cells(html: str) -> list[str]: + return re.findall(r"]*>([^<]*%)", html) + + +def sql_block(html: str) -> str: + blocks = re.findall(r"
      (.*?)
      ", html, flags=re.DOTALL) + assert len(blocks) == 1 + return blocks[0] + + +@pytest.fixture(scope="module") +def join_profile(): + return engine_profile(JOIN_SQL) + + +class TestQueryGraphRenderer: + def test_renders_engine_profile_with_query_metrics_and_operators(self, join_profile, tmp_path): + html = render(join_profile, tmp_path) + query = join_profile["query"] + io = join_profile["io"] + + assert grid_value(html, "Execution Time (s)") == f"{query['total_time']:.4f}" + assert grid_value(html, "CPU Time (s)") == f"{query['cpu_time']:.4f}" + assert grid_value(html, "Total GB Read") == f"{io['total_bytes_read'] / 1024**3:.4f}" + assert grid_value(html, "Total GB Written") == f"{io['total_bytes_written'] / 1024**3:.4f}" + assert grid_value(html, "Peak Memory (GB)") == f"{join_profile['system']['peak_buffer_memory'] / 1024**3:.4f}" + assert grid_value(html, "Rows Scanned") == f"{query['total_rows_scanned']:,}" + assert JOIN_SQL in sql_block(html) + ops = operators(join_profile["operator"][0]) + for op in ops: + assert op["type"].replace("_", " ") in html + hash_join = next(op for op in ops if op["type"] == "HASH_JOIN") + assert f"

      time: {hash_join['timing']:.4f}s

      " in html + assert f"

      cardinality: {hash_join['intermediate_rows']}

      " in html + assert f"

      estimate: {hash_join['extra_info']['Estimated Cardinality']}

      " in html + assert f"

      result size: {hash_join['intermediate_size_bytes']} bytes

      " in html + assert f"Join Type: {hash_join['extra_info']['Join Type']}
      " in html + + def test_tree_nests_children_in_engine_order(self, join_profile, tmp_path): + html = render(join_profile, tmp_path) + ops = operators(join_profile["operator"][0]) + + assert html.count("
    • ") == len(ops) + assert headlines(html) == [op["type"].replace("_", " ") for op in ops] + assert rendered_tree(html) == [expected_tree(join_profile["operator"][0])] + # the two scans are leaves: each sits in its own nested list under the join + assert html.count("
        ") == 1 + sum(1 for op in ops if op.get("children")) + assert html.count("
      ") == html.count("
        ") + + def test_name_shown_in_its_own_line_when_it_differs_from_type(self, join_profile, tmp_path): + html = render(join_profile, tmp_path) + ops = operators(join_profile["operator"][0]) + scan = next(op for op in ops if op["type"] == "TABLE_SCAN") + hash_join = next(op for op in ops if op["type"] == "HASH_JOIN") + + assert scan["name"] == "RANGE" + assert hash_join["name"] == hash_join["type"] + assert f"

        name: {scan['name']}

        " in html + assert html.count("

        name: ") == sum(1 for op in ops if op["name"] != op["type"]) + + def test_scan_counters_are_listed_in_the_details(self, join_profile, tmp_path): + html = render(join_profile, tmp_path) + scan = next(op for op in operators(join_profile["operator"][0]) if op["type"] == "TABLE_SCAN") + + for key in ("rows_scanned", "row_groups_scanned", "total_row_groups_to_scan"): + assert f"{key}: {scan[key]}
        " in html + + def test_phase_table_sums_timing_per_operator_type(self, join_profile, tmp_path): + html = render(join_profile, tmp_path) + entries = walk(join_profile["operator"][0]) + scans = [(op, depth) for op, depth in entries if op["type"] == "TABLE_SCAN"] + total = sum(op["timing"] for op, _ in entries) + + assert len(scans) == 2 + assert "Execution Time (CPU)" in html + assert f"{round(total, 8)}" in html + assert f"{round(sum(op['timing'] for op, _ in scans), 8)}" in html + assert percentage_cells(html)[0] == "100.0000%" + assert f"Show {len(scans)} nodes" in html + per_type: dict[str, list[dict]] = {} + for op, _ in entries: + per_type.setdefault(op["type"], []).append(op) + assert html.count("↳ Depth") == sum(len(group) for group in per_type.values() if len(group) > 1) + for _, depth in scans: + assert f"↳ Depth {depth}" in html + + def test_phase_percentages_have_fixed_decimals(self, join_profile, tmp_path): + profile = copy_of(join_profile) + ops = operators(profile["operator"][0]) + for op in ops: + op["timing"] = 0.0 + next(op for op in ops if op["type"] == "HASH_JOIN")["timing"] = 0.9 + next(op for op in ops if op["type"] == "ORDER_BY")["timing"] = 0.1 + next(op for op in ops if op["type"] == "RESULT_COLLECTOR")["timing"] = 1e-9 + + html = render(profile, tmp_path) + + cells = percentage_cells(html) + assert "90.0000%" in cells + assert "10.0000%" in cells + assert "0.0000%" in cells + assert all(re.fullmatch(r"\d+\.\d{4}%", cell) for cell in cells), cells + + def test_metric_grid_reads_grouped_io_and_system_metrics(self, join_profile, tmp_path): + profile = copy_of(join_profile) + profile["io"]["total_bytes_read"] = 3 * 1024**3 + profile["io"]["total_bytes_written"] = 1024**3 // 2 + profile["system"]["peak_buffer_memory"] = 2 * 1024**3 + profile["query"]["total_rows_scanned"] = 1234567 + + html = render(profile, tmp_path) + + assert grid_value(html, "Total GB Read") == "3.0000" + assert grid_value(html, "Total GB Written") == "0.5000" + assert grid_value(html, "Peak Memory (GB)") == "2.0000" + assert grid_value(html, "Rows Scanned") == "1,234,567" + + @pytest.mark.parametrize( + ("cpu_time", "timings", "expected"), + [ + pytest.param(1.0, (0.5, 0.0), ["#dfffc3", "#f7fff0"], id="share-of-cpu-time"), + # Without a CPU time the total is the sum of the operator timings, 1.0 here, not their maximum. + pytest.param(None, (0.25, 0.75), ["#ebffd9", "#d3ffac"], id="no-cpu-time"), + pytest.param(0.0, (0.25, 0.75), ["#ebffd9", "#d3ffac"], id="zero-cpu-time"), + pytest.param(1.0, None, ["#f7fff0", "#f7fff0"], id="no-timing"), + ], + ) + def test_node_shade_follows_the_share_of_cpu_time(self, cpu_time, timings, expected, join_profile, tmp_path): + profile = copy_of(join_profile) + if cpu_time is None: + del profile["query"]["cpu_time"] + else: + profile["query"]["cpu_time"] = cpu_time + ops = operators(profile["operator"][0]) + for op in ops: + if timings is None: + del op["timing"] + else: + op["timing"] = 0.0 + if timings is not None: + ops[0]["timing"], ops[1]["timing"] = timings + + shades = node_shades(render(profile, tmp_path)) + + assert shades == expected + ["#f7fff0"] * (len(ops) - 2) + + def test_extra_info_list_values_render_each_item(self, tmp_path): + profile = engine_profile("SELECT 1 AS x, 2 AS y") + projection = next(op for op in operators(profile["operator"][0]) if op["type"] == "PROJECTION") + assert projection["extra_info"]["Projections"] == ["x", "y"], "the engine writes multi line values as lists" + + html = render(profile, tmp_path) + + assert "Projections: x, y
        " in html + assert "['x'" not in html + + def test_user_names_in_the_details_are_shown_unchanged(self, join_profile, tmp_path): + profile = copy_of(join_profile) + projection = next(op for op in operators(profile["operator"][0]) if op["type"] == "PROJECTION") + projection["extra_info"] = { + "Projections": [ + "compress_integral", + "__internal_z", + "x,y", + "__internal_compress_integral_utinyint(#0, 1)", + "__internal_decompress_integral_bigint(#0, 1)", + ] + } + + html = render(profile, tmp_path) + + shown = "compress_integral, __internal_z, x,y, __compress_utinyint(#0, 1), __decompress_bigint(#0, 1)" + assert f"Projections: {shown}
        " in html + + def test_profile_text_is_html_escaped(self, tmp_path): + profile = engine_profile("SELECT '&' AS x") + assert "&" in profile["query"]["sql"] + ops = operators(profile["operator"][0]) + ops[1]["type"] = "T_X" + ops[1]["name"] = "n" + ops[1]["extra_info"] = {"": ""} + + html = render(profile, tmp_path) + + assert "'<b>&'" in sql_block(html) + assert "'&'" not in html + assert "

        <b>T</b> X

        " in html + assert "

        name: <i>n</i>

        " in html + assert "<k>: <v>
        " in html + for raw in ("T", "n", "", ""): + assert raw not in html + + def test_sql_containing_template_markers_stays_text(self, tmp_path): + profile = engine_profile("SELECT '${TREE}' AS a, '${TIMING_TABLE}' AS b, '{metric_grid}' AS c") + + html = render(profile, tmp_path) + + block = sql_block(html) + assert "'${TREE}' AS a, '${TIMING_TABLE}' AS b, '{metric_grid}' AS c" in block + assert "
      • " not in block + assert "") == len(operators(profile["operator"][0])) + + def test_deep_operator_chain_renders_without_recursion(self): + # The dict goes straight to the renderer: Python 3.11's JSON decoder cannot read a chain this deep. + depth = 1000 + profile = chain_profile(depth) + + html = ProfilingInfo()._render_page(profile) + + assert html.count("
      • ") == depth + assert f"Show {depth} nodes" in html + assert f"↳ Depth {depth - 1}" in html + tree = rendered_tree(html) + for _ in range(depth - 1): + assert len(tree) == 1 + assert tree[0][0] == "PROJECTION" + tree = tree[0][1] + assert tree == [["PROJECTION", []]] + + def test_deep_operator_chain_file_renders(self, tmp_path): + # 300 operators nest 600 JSON levels, well within what every supported Python's JSON decoder reads. The + # tightest case is 3.11, whose limit of 1000 also counts pytest's own frames (about 944 levels remain inside + # pytest with xdist); Windows ARM64 with 3.13 has the same 1000 for the decoder alone. + depth = 300 + text = chain_profile_text(depth) + assert json.loads(text) == chain_profile(depth) + + html = render(text, tmp_path) + + assert html.count("
      • ") == depth + tree = rendered_tree(html) + for _ in range(depth - 1): + assert len(tree) == 1 + tree = tree[0][1] + assert tree == [["PROJECTION", []]] + + def test_profile_too_deep_for_the_json_decoder_raises_the_module_error(self, tmp_path, monkeypatch): + # Python 3.11's decoder raises RecursionError from about 500 operators; from 3.12 on the bound is the + # platform's C recursion limit (about 500 operators on Windows ARM64 with 3.13, about 5000 on Linux), and + # that decoder does not follow sys.setrecursionlimit, so the failure is forced here on every version. + def too_deep(text): + msg = "maximum recursion depth exceeded while decoding a JSON object" + raise RecursionError(msg) + + monkeypatch.setattr(json, "loads", too_deep) + + with pytest.raises(ValueError, match=r"profile\.json nests its operators deeper"): + render(chain_profile_text(1000), tmp_path) + + def test_profile_a_thousand_deep_never_leaks_a_recursion_error(self, tmp_path): + # How deep the JSON decoder reads differs by Python version and platform; the invariant is the outcome: + # a rendered page or the module's error, never a RecursionError. + depth = 1000 + try: + html = render(chain_profile_text(depth), tmp_path) + except ValueError as e: + assert "nests its operators deeper" in str(e) # noqa: PT017 + else: + assert html.count("
      • ") == depth + + def test_profile_without_timing_metrics_renders_tree(self, tmp_path): + profile = engine_profile(JOIN_SQL, "SET tracked_metrics = ['operator.type', 'operator.name']") + assert set(profile) == {"operator"} + + html = render(profile, tmp_path) + + assert headlines(html) == [op["type"].replace("_", " ") for op in operators(profile["operator"][0])] + assert "time:" not in html + assert "Execution Time (CPU)" not in html + assert all(grid_value(html, title) == "N/A" for title in GRID_TITLES) + + def test_only_name_tracked_heads_the_node_with_the_name_once(self, tmp_path): + profile = engine_profile(JOIN_SQL, "SET tracked_metrics = ['operator.name', 'operator.timing']") + ops = operators(profile["operator"][0]) + assert "type" not in ops[0] + + html = render(profile, tmp_path) + + assert headlines(html) == [op["name"].replace("_", " ") for op in ops] + assert "

        name: " not in html + + def test_only_timing_tracked_heads_every_node_operator(self, tmp_path): + profile = engine_profile(JOIN_SQL, "SET tracked_metrics = ['operator.timing']") + ops = operators(profile["operator"][0]) + assert set(ops[0]) == {"timing", "children"} + + html = render(profile, tmp_path) + + assert headlines(html) == ["OPERATOR"] * len(ops) + + def test_profile_without_operator_metrics_renders_query_metrics(self, tmp_path): + profile = engine_profile(JOIN_SQL, "SET tracked_metrics = ['query.*']") + assert set(profile) == {"query"} + + html = render(profile, tmp_path) + + assert grid_value(html, "Execution Time (s)") == f"{profile['query']['total_time']:.4f}" + assert JOIN_SQL in sql_block(html) + assert "

      • " not in html + assert "The profile holds no operator metrics" in html + + def test_profile_with_only_system_metrics_renders_its_boxes(self, tmp_path): + profile = engine_profile(JOIN_SQL, "SET tracked_metrics = ['system.*']") + assert set(profile) == {"system"} + + html = render(profile, tmp_path) + + assert grid_value(html, "Peak Memory (GB)") == f"{profile['system']['peak_buffer_memory'] / 1024**3:.4f}" + assert grid_value(html, "Execution Time (s)") == "N/A" + assert "
      • " not in html + assert "Execution Time (CPU)" not in html + + def test_empty_profile_object_renders_without_metrics(self, tmp_path): + html = render({}, tmp_path) + + assert all(grid_value(html, title) == "N/A" for title in GRID_TITLES) + assert "
      • " not in html + + @pytest.mark.parametrize("result", ["disabled", "empty", "error"]) + def test_profile_without_query_raises(self, result, tmp_path): + with pytest.raises(ValueError, match=result): + render({"result": result}, tmp_path) + + @pytest.mark.parametrize( + "content", + [ + pytest.param("this is not json", id="not-json"), + pytest.param("", id="empty-file"), + pytest.param("[1, 2, 3]", id="json-list"), + pytest.param('{"query": {}}'.encode("utf-16"), id="utf-16-file"), + ], + ) + def test_input_that_is_not_a_profile_raises(self, content, tmp_path): + with pytest.raises(ValueError, match=r"profile\.json"): + render(content, tmp_path) + + def test_missing_input_file_raises_file_not_found(self, tmp_path): + with pytest.raises(FileNotFoundError): + ProfilingInfo(from_file=str(tmp_path / "missing.json")).to_html(output_file=str(tmp_path / "out.html")) + + def test_profiling_info_without_connection_or_file_raises(self, tmp_path): + with pytest.raises(ValueError, match="connection or a file"): + ProfilingInfo().to_html(output_file=str(tmp_path / "out.html")) + + @pytest.mark.parametrize( + ("settings", "present", "absent"), + [ + pytest.param(("SET legacy_metrics_format = true",), ("latency", "children"), (), id="legacy-all-metrics"), + pytest.param( + ("SET legacy_metrics_format = true", "SET tracked_metrics = ['operator.*']"), + ("children",), + ("latency",), + id="legacy-operator-metrics-only", + ), + ], + ) + def test_legacy_flat_format_is_rejected_with_a_clear_message(self, settings, present, absent, tmp_path): + profile = engine_profile(JOIN_SQL, *settings) + for key in present: + assert key in profile + for key in absent: + assert key not in profile + + with pytest.raises(ValueError, match=r"flat profiling format of DuckDB 1\.x.*legacy_metrics_format"): + render(profile, tmp_path) + + def test_profile_written_by_duckdb_1x_is_rejected(self, tmp_path): + # Shortened from what the DuckDB 1.5.6 wheel wrote for SELECT 42. + profile_1x = { + "query_name": "SELECT 42", + "cpu_time": 0.000947039, + "latency": 0.005966684, + "children": [ + { + "operator_type": "PROJECTION", + "operator_name": "PROJECTION", + "operator_timing": 7.4e-06, + "operator_cardinality": 1, + "result_set_size": 4, + "cpu_time": 9.933e-06, + "extra_info": {"Projections": "42", "Estimated Cardinality": "1"}, + "children": [ + { + "operator_type": "DUMMY_SCAN", + "operator_name": "DUMMY_SCAN", + "operator_timing": 2.533e-06, + "operator_cardinality": 1, + "result_set_size": 4, + "cpu_time": 2.533e-06, + "extra_info": {}, + "children": [], + } + ], + } + ], + } + + with pytest.raises(ValueError, match=r"flat profiling format of DuckDB 1\.x"): + render(profile_1x, tmp_path) + + +class TestQueryGraphCommandLine: + @pytest.fixture + def browser_calls(self, monkeypatch): + calls = [] + monkeypatch.setattr(webbrowser, "open", lambda url, *args, **kwargs: calls.append(url)) + return calls + + @staticmethod + def run_cli(monkeypatch, *args: str) -> None: + monkeypatch.setattr(sys, "argv", ["query_graph", *args]) + query_graph_main() + + @staticmethod + def write_profile(profile: dict, path) -> str: + path.write_text(json.dumps(profile), encoding="utf8") + return str(path) + + def test_cli_renders_profile_input_to_out(self, join_profile, tmp_path, monkeypatch, browser_calls, capsys): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + out_file = tmp_path / "graph.html" + + self.run_cli(monkeypatch, "--profile_input", profile_file, "--out", str(out_file)) + + html = out_file.read_text(encoding="utf8") + assert JOIN_SQL in html + assert "HASH JOIN" in html + assert browser_calls == [out_file.resolve().as_uri()] + assert str(out_file) in capsys.readouterr().out + + def test_cli_positional_profile_path_renders(self, join_profile, tmp_path, monkeypatch, browser_calls): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + out_file = tmp_path / "graph.html" + + self.run_cli(monkeypatch, profile_file, "--out", str(out_file)) + + assert JOIN_SQL in out_file.read_text(encoding="utf8") + assert browser_calls == [out_file.resolve().as_uri()] + + def test_cli_default_output_path_replaces_json_suffix(self, join_profile, tmp_path, monkeypatch, browser_calls): + # The directory name holds .json too; only the suffix of the file changes. + directory = tmp_path / "runs.json" + directory.mkdir() + profile_file = self.write_profile(join_profile, directory / "profile.json") + + self.run_cli(monkeypatch, "--profile_input", profile_file) + + assert (directory / "profile.html").exists() + assert not (tmp_path / "runs.html").exists() + assert len(browser_calls) == 1 + + def test_cli_refuses_a_profile_without_json_suffix_when_no_output_is_named( + self, join_profile, tmp_path, monkeypatch, browser_calls, capsys + ): + profile_file = self.write_profile(join_profile, tmp_path / "profile.txt") + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--no-open") + + assert exc.value.code == 1 + assert ".json" in capsys.readouterr().err + assert list(tmp_path.glob("*.html")) == [] + assert browser_calls == [] + + def test_cli_positional_path_and_profile_input_must_agree(self, join_profile, tmp_path, monkeypatch, browser_calls): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + other_file = self.write_profile(join_profile, tmp_path / "other.json") + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--profile_input", other_file, "--no-open") + assert exc.value.code == 2 + + self.run_cli(monkeypatch, profile_file, "--profile_input", profile_file, "--no-open") + assert (tmp_path / "profile.html").exists() + assert browser_calls == [] + + def test_cli_no_open_writes_the_file_without_a_browser(self, join_profile, tmp_path, monkeypatch, browser_calls): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + + self.run_cli(monkeypatch, profile_file, "--no-open") + + assert (tmp_path / "profile.html").exists() + assert browser_calls == [] + + @pytest.mark.parametrize( + "args", + [ + pytest.param((), id="no-arguments"), + pytest.param(("--out", "graph.html"), id="only-out"), + pytest.param(("--no-open",), id="only-no-open"), + ], + ) + def test_cli_without_a_path_is_a_usage_error(self, args, tmp_path, monkeypatch, browser_calls, capsys): + monkeypatch.chdir(tmp_path) + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, *args) + + assert exc.value.code == 2 + err = capsys.readouterr().err + assert err.startswith("usage: python -m duckdb.query_graph") + assert "the path of a JSON profile is required" in err + assert list(tmp_path.iterdir()) == [] + assert browser_calls == [] + + def test_cli_rejects_non_profile_with_exit_code_1(self, tmp_path, monkeypatch, browser_calls, capsys): + profile_file = self.write_profile({"result": "empty"}, tmp_path / "profile.json") + out_file = tmp_path / "graph.html" + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--out", str(out_file)) + + assert exc.value.code == 1 + assert "empty" in capsys.readouterr().err + assert not out_file.exists() + assert browser_calls == [] + + @pytest.mark.parametrize("out_name", ["graph.txt", "graph.html.txt"]) + def test_cli_rejects_output_without_html_suffix(self, out_name, join_profile, tmp_path, monkeypatch, browser_calls): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--out", str(tmp_path / out_name)) + + assert exc.value.code == 1 + assert not (tmp_path / out_name).exists() + assert browser_calls == [] + + def test_cli_refuses_an_output_path_equal_to_the_input( + self, join_profile, tmp_path, monkeypatch, browser_calls, capsys + ): + profile_file = self.write_profile(join_profile, tmp_path / "saved.html") + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--out", profile_file) + + assert exc.value.code == 1 + assert "input" in capsys.readouterr().err + assert json.loads((tmp_path / "saved.html").read_text(encoding="utf8")) == join_profile + assert browser_calls == [] + + def test_cli_names_the_file_it_could_not_read(self, tmp_path, monkeypatch, browser_calls, capsys): + directory = tmp_path / "dir.json" + directory.mkdir() + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, str(directory), "--no-open") + + assert exc.value.code == 1 + err = capsys.readouterr().err + assert "read the profile" in err + assert str(directory) in err + + def test_cli_names_the_file_it_could_not_write(self, join_profile, tmp_path, monkeypatch, browser_calls, capsys): + # The output path is given relative and not in normal form, as a user types it. + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + monkeypatch.chdir(tmp_path) + + with pytest.raises(SystemExit) as exc: + self.run_cli(monkeypatch, profile_file, "--out", "./missing/graph.html") + + assert exc.value.code == 1 + err = capsys.readouterr().err + assert "write the output file ./missing/graph.html" in err + assert "read the profile" not in err + assert browser_calls == [] + + def test_cli_module_run_does_not_warn_about_double_import(self, join_profile, tmp_path): + profile_file = self.write_profile(join_profile, tmp_path / "profile.json") + + result = subprocess.run( + [sys.executable, "-m", "duckdb.query_graph", profile_file, "--no-open"], + capture_output=True, + text=True, + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + assert "RuntimeWarning" not in result.stderr + assert (tmp_path / "profile.html").exists() + assert str(tmp_path / "profile.html") in result.stdout