deephaven-plugin-query-graph 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@deephaven/js-plugin-query-graph",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Deephaven Query Graph plugin - a live map of table lineage and update cost",
6
+ "keywords": [
7
+ "Deephaven",
8
+ "plugin",
9
+ "deephaven-js-plugin",
10
+ "performance",
11
+ "lineage"
12
+ ],
13
+ "author": "Mike Bender",
14
+ "license": "Apache-2.0",
15
+ "main": "dist/index.js",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/mofojed/deephaven-live-plugins",
19
+ "directory": "plugins/query-graph/src/js"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/mofojed/deephaven-live-plugins/issues"
23
+ },
24
+ "homepage": "https://github.com/mofojed/deephaven-live-plugins/tree/main/plugins/query-graph",
25
+ "scripts": {
26
+ "start": "vite build --watch",
27
+ "build": "vite build"
28
+ },
29
+ "devDependencies": {
30
+ "@types/react": "^18.0.0",
31
+ "@types/react-dom": "^18.0.0",
32
+ "react": "^18.0.0",
33
+ "react-dom": "^18.0.0"
34
+ },
35
+ "peerDependencies": {
36
+ "react": "^18.0.0 || ^19.0.0",
37
+ "react-dom": "^18.0.0 || ^19.0.0"
38
+ },
39
+ "dependencies": {
40
+ "@deephaven/dashboard": "^1.30.0",
41
+ "@deephaven/icons": "^1.2.0",
42
+ "@deephaven/jsapi-bootstrap": "^1.30.0",
43
+ "@deephaven/jsapi-types": "^1.0.0-dev0.39.6",
44
+ "@deephaven/log": "^1.8.0",
45
+ "@deephaven/plugin": "^1.30.0"
46
+ },
47
+ "files": [
48
+ "dist/index.js"
49
+ ]
50
+ }
@@ -0,0 +1,289 @@
1
+ """Pure (engine-free) lineage graph state, built from performance log rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import deque
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Iterable, Literal
9
+
10
+ Mode = Literal["named", "all"]
11
+ MODES: tuple[str, ...] = ("named", "all")
12
+ SMALL_UPDATES = "Aggregated Small Updates"
13
+ _OP_PATTERN = re.compile(
14
+ r"^\s*(?:(?:left|right)Table:\s*)?([A-Za-z_][\w.]*)\s*\((.*)\)\s*$", re.S
15
+ )
16
+ _MAX_SUBTITLE = 48
17
+
18
+
19
+ @dataclass
20
+ class EntryStats:
21
+ """Cost of one performance entry during one interval."""
22
+
23
+ usage_nanos: int = 0
24
+ cpu_nanos: int = 0
25
+ rows_added: int = 0
26
+ rows_removed: int = 0
27
+ rows_modified: int = 0
28
+ invocations: int = 0
29
+ interval_nanos: int = 0
30
+
31
+ @property
32
+ def usage(self) -> float:
33
+ """Fraction of the interval's wall time spent in this entry."""
34
+ return (
35
+ self.usage_nanos / self.interval_nanos if self.interval_nanos > 0 else 0.0
36
+ )
37
+
38
+ def rows_per_second(self) -> float:
39
+ """Rows added, removed or modified per second."""
40
+ if self.interval_nanos <= 0:
41
+ return 0.0
42
+ rows = self.rows_added + self.rows_removed + self.rows_modified
43
+ return rows * 1e9 / self.interval_nanos
44
+
45
+
46
+ @dataclass
47
+ class EntryInfo:
48
+ """What is known about a performance entry."""
49
+
50
+ entry_id: int
51
+ description: str = ""
52
+ caller_line: str | None = None
53
+ update_graph: str | None = None
54
+ ancestors: tuple[int, ...] = ()
55
+ has_ancestry: bool = False
56
+
57
+
58
+ @dataclass
59
+ class NamedTable:
60
+ """A named table and the performance entries that produce it."""
61
+
62
+ name: str
63
+ entry_ids: tuple[int, ...]
64
+ size: int
65
+ refreshing: bool
66
+ ticked: bool = False
67
+
68
+
69
+ def describe(description: str) -> tuple[str, str]:
70
+ """Split an entry description into a short operation label and a subtitle.
71
+
72
+ ``"where([X % 2 == 0])"`` becomes ``("where", "X % 2 == 0")``, and aggregations
73
+ become ``("aggBy", "by Sym")``.
74
+ """
75
+ match = _OP_PATTERN.match(description or "")
76
+ if not match:
77
+ text = " ".join((description or "").split())
78
+ return (text[:_MAX_SUBTITLE] or "?", "")
79
+ op, args = match.group(1), " ".join(match.group(2).split())
80
+ if op == "by":
81
+ keys = re.search(r"\[([^\[\]]*)\]\s*$", args)
82
+ return ("aggBy", f"by {keys.group(1)}" if keys and keys.group(1) else "")
83
+ if args.startswith("[") and args.endswith("]") and args.count("[") == 1:
84
+ args = args[1:-1]
85
+ if len(args) > _MAX_SUBTITLE:
86
+ args = args[: _MAX_SUBTITLE - 1] + "…"
87
+ return (op, args)
88
+
89
+
90
+ def _kind(info: EntryInfo) -> str:
91
+ # Sources (time tables, publishers, ...) never appear in the ancestors log.
92
+ if info.ancestors:
93
+ return "op"
94
+ return "source" if info.has_ancestry or info.description else "unknown"
95
+
96
+
97
+ class LineageState:
98
+ """Accumulates entries, ancestry and per-interval cost, and renders the graph."""
99
+
100
+ def __init__(self, history_size: int = 60):
101
+ self.history_size = history_size
102
+ self.entries: dict[int, EntryInfo] = {}
103
+ self.latest: dict[int, EntryStats] = {}
104
+ self.small_updates = EntryStats()
105
+ self.history: dict[int, deque] = {}
106
+ self.interval_end: int | None = None
107
+ self.interval_nanos: int = 0
108
+
109
+ def _entry(self, entry_id: int) -> EntryInfo:
110
+ info = self.entries.get(entry_id)
111
+ if info is None:
112
+ info = self.entries[entry_id] = EntryInfo(entry_id)
113
+ return info
114
+
115
+ def record_ancestors(
116
+ self, rows: Iterable[tuple[int, str | None, Iterable[int], str | None]]
117
+ ) -> None:
118
+ """Record ``(entry_id, description, ancestor_ids, update_graph)`` rows."""
119
+ for entry_id, description, ancestors, update_graph in rows:
120
+ info = self._entry(int(entry_id))
121
+ if description:
122
+ info.description = description
123
+ if update_graph:
124
+ info.update_graph = update_graph
125
+ info.ancestors = tuple(int(a) for a in ancestors)
126
+ info.has_ancestry = True
127
+
128
+ def record_interval(self, end_nanos: int, rows: Iterable[dict[str, Any]]) -> None:
129
+ """Record every update-performance row of one interval.
130
+
131
+ Rows have ``EntryId`` (None for the aggregated small updates), ``EntryDescription``,
132
+ ``EntryCallerLine``, ``UpdateGraph``, ``UsageNanos``, ``CpuNanos``, ``RowsAdded``,
133
+ ``RowsRemoved``, ``RowsModified``, ``InvocationCount`` and ``IntervalNanos``.
134
+ Re-recording the latest interval merges into it instead of adding history.
135
+ """
136
+ is_new = self.interval_end is None or end_nanos > self.interval_end
137
+ if self.interval_end is not None and end_nanos < self.interval_end:
138
+ return
139
+ if is_new:
140
+ self.latest = {}
141
+ self.small_updates = EntryStats()
142
+ self.interval_end = end_nanos
143
+ for row in rows:
144
+ stats = EntryStats(
145
+ usage_nanos=int(row.get("UsageNanos") or 0),
146
+ cpu_nanos=int(row.get("CpuNanos") or 0),
147
+ rows_added=int(row.get("RowsAdded") or 0),
148
+ rows_removed=int(row.get("RowsRemoved") or 0),
149
+ rows_modified=int(row.get("RowsModified") or 0),
150
+ invocations=int(row.get("InvocationCount") or 0),
151
+ interval_nanos=int(row.get("IntervalNanos") or 0),
152
+ )
153
+ self.interval_nanos = max(self.interval_nanos, stats.interval_nanos)
154
+ entry_id = row.get("EntryId")
155
+ if entry_id is None:
156
+ if row.get("EntryDescription") == SMALL_UPDATES:
157
+ self.small_updates = stats
158
+ continue
159
+ info = self._entry(int(entry_id))
160
+ info.description = info.description or row.get("EntryDescription") or ""
161
+ info.caller_line = row.get("EntryCallerLine") or info.caller_line
162
+ info.update_graph = info.update_graph or row.get("UpdateGraph")
163
+ self.latest[int(entry_id)] = stats
164
+ if is_new:
165
+ for entry_id in self.entries:
166
+ history = self.history.get(entry_id)
167
+ if history is None:
168
+ history = self.history[entry_id] = deque(maxlen=self.history_size)
169
+ stats = self.latest.get(entry_id)
170
+ history.append(round(stats.usage, 6) if stats else 0.0)
171
+
172
+ def _closure(self, anchors: Iterable[int]) -> set[int]:
173
+ seen: set[int] = set()
174
+ stack = list(anchors)
175
+ while stack:
176
+ entry_id = stack.pop()
177
+ if entry_id in seen:
178
+ continue
179
+ seen.add(entry_id)
180
+ info = self.entries.get(entry_id)
181
+ if info is not None:
182
+ stack.extend(info.ancestors)
183
+ return seen
184
+
185
+ def build_graph(
186
+ self, named: Iterable[NamedTable], mode: Mode = "named"
187
+ ) -> dict[str, Any]:
188
+ """Render the graph as a JSON-friendly dictionary of nodes and edges."""
189
+ if mode not in MODES:
190
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}")
191
+ named = list(named)
192
+ names_by_entry: dict[int, list[NamedTable]] = {}
193
+ for table in named:
194
+ for entry_id in table.entry_ids:
195
+ names_by_entry.setdefault(entry_id, []).append(table)
196
+
197
+ if mode == "all":
198
+ ids = set(self.entries) | set(names_by_entry)
199
+ for info in list(self.entries.values()):
200
+ ids.update(info.ancestors)
201
+ else:
202
+ ids = self._closure(names_by_entry)
203
+
204
+ nodes = []
205
+ for entry_id in sorted(ids):
206
+ info = self.entries.get(entry_id) or EntryInfo(entry_id)
207
+ stats = self.latest.get(entry_id)
208
+ tables = names_by_entry.get(entry_id, [])
209
+ label, subtitle = describe(info.description)
210
+ if not info.description and tables:
211
+ label, subtitle = tables[0].name, ""
212
+ nodes.append(
213
+ {
214
+ "id": str(entry_id),
215
+ "entryId": entry_id,
216
+ "label": label,
217
+ "subtitle": subtitle,
218
+ "description": info.description,
219
+ "callerLine": info.caller_line,
220
+ "updateGraph": info.update_graph,
221
+ "kind": _kind(info),
222
+ "names": [t.name for t in tables],
223
+ "size": tables[0].size if tables else None,
224
+ "ticked": any(t.ticked for t in tables),
225
+ "idle": stats is None,
226
+ "usage": stats.usage if stats else 0.0,
227
+ "cpuNanos": stats.cpu_nanos if stats else 0,
228
+ "usageNanos": stats.usage_nanos if stats else 0,
229
+ "rowsAdded": stats.rows_added if stats else 0,
230
+ "rowsRemoved": stats.rows_removed if stats else 0,
231
+ "rowsModified": stats.rows_modified if stats else 0,
232
+ "rowsPerSecond": stats.rows_per_second() if stats else 0.0,
233
+ "invocations": stats.invocations if stats else 0,
234
+ "history": list(self.history.get(entry_id, ())),
235
+ }
236
+ )
237
+
238
+ for table in named:
239
+ if not table.entry_ids:
240
+ nodes.append(
241
+ {
242
+ "id": f"table:{table.name}",
243
+ "entryId": None,
244
+ "label": table.name,
245
+ "subtitle": "ticking table"
246
+ if table.refreshing
247
+ else "static table",
248
+ "description": "",
249
+ "callerLine": None,
250
+ "updateGraph": None,
251
+ "kind": "table",
252
+ "names": [table.name],
253
+ "size": table.size,
254
+ "ticked": table.ticked,
255
+ "idle": True,
256
+ "usage": 0.0,
257
+ "cpuNanos": 0,
258
+ "usageNanos": 0,
259
+ "rowsAdded": 0,
260
+ "rowsRemoved": 0,
261
+ "rowsModified": 0,
262
+ "rowsPerSecond": 0.0,
263
+ "invocations": 0,
264
+ "history": [],
265
+ }
266
+ )
267
+
268
+ edges = [
269
+ {"source": str(a), "target": str(entry_id)}
270
+ for entry_id in sorted(ids)
271
+ for a in (self.entries.get(entry_id) or EntryInfo(entry_id)).ancestors
272
+ if a in ids
273
+ ]
274
+ total = (
275
+ sum(s.usage_nanos for s in self.latest.values())
276
+ + self.small_updates.usage_nanos
277
+ )
278
+ return {
279
+ "mode": mode,
280
+ "nodes": nodes,
281
+ "edges": edges,
282
+ "intervalNanos": self.interval_nanos,
283
+ "intervalEnd": self.interval_end,
284
+ "totalUsage": total / self.interval_nanos if self.interval_nanos else 0.0,
285
+ "smallUpdatesUsage": self.small_updates.usage,
286
+ "missingLineage": sorted(
287
+ {t.name for t in named for e in t.entry_ids if e not in self.entries}
288
+ ),
289
+ }
@@ -0,0 +1,31 @@
1
+ """Plugin registration for the query graph."""
2
+
3
+ import logging
4
+
5
+ from deephaven.plugin import Callback, Registration
6
+ from deephaven.plugin.utilities import DheSafeCallbackWrapper, create_js_plugin
7
+
8
+ PACKAGE_NAMESPACE = "deephaven.query_graph"
9
+ JS_NAME = "_js"
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class QueryGraphRegistration(Registration):
15
+ """Register the QueryGraph object type and its JS plugin."""
16
+
17
+ @classmethod
18
+ def register_into(cls, callback: Callback) -> None:
19
+ from ._widget import QueryGraphType
20
+ from ._collector import ensure_ancestors_log
21
+
22
+ # The ancestors log only records entries published after it is created, so
23
+ # create it at startup, before any user tables exist.
24
+ try:
25
+ ensure_ancestors_log()
26
+ except Exception: # noqa: BLE001 - lineage is best effort
27
+ logger.exception("Could not start the update performance ancestors log")
28
+
29
+ callback = DheSafeCallbackWrapper(callback)
30
+ callback.register(QueryGraphType)
31
+ callback.register(create_js_plugin(PACKAGE_NAMESPACE, JS_NAME))
@@ -0,0 +1,218 @@
1
+ """The QueryGraph widget and its client connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import sys
8
+ import threading
9
+ from typing import Any, Mapping, cast
10
+
11
+ from deephaven.execution_context import get_exec_ctx
12
+ from deephaven.plugin.object_type import BidirectionalObjectType, MessageStream
13
+ from deephaven.table import Table
14
+
15
+ from ._collector import (
16
+ collector,
17
+ last_notification_step,
18
+ performance_config,
19
+ table_entry_ids,
20
+ )
21
+ from ._model import MODES, Mode, NamedTable
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ NAME = "deephaven.query_graph.QueryGraph"
26
+ LIVE_INTERVAL_MILLIS = 5_000
27
+
28
+
29
+ class QueryGraph:
30
+ """A live map of how tables derive from each other, and what each step costs.
31
+
32
+ Display it in the IDE (assign it to a variable) to see the update graph lineage of
33
+ your named tables, with each operation's share of update time, rows/second and a
34
+ cost sparkline. Click an operation to see details, or open the table it produces.
35
+
36
+ Args:
37
+ tables: Tables to anchor the graph on, by name. Added to the tables found in
38
+ ``scope``.
39
+ scope: A namespace to find named tables in, such as ``globals()``. Defaults to
40
+ the console's global scope. Names starting with ``_`` are ignored.
41
+ mode: ``"named"`` shows named tables and everything they derive from.
42
+ ``"all"`` shows every operation the performance logs know about.
43
+ refresh_interval: Seconds between updates sent to the client.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ tables: Mapping[str, Table] | None = None,
49
+ scope: Mapping[str, Any] | None = None,
50
+ mode: Mode = "named",
51
+ refresh_interval: float = 1.0,
52
+ ):
53
+ if mode not in MODES:
54
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}")
55
+ if refresh_interval <= 0:
56
+ raise ValueError("refresh_interval must be positive")
57
+ self.tables = dict(tables or {})
58
+ self.scope = scope
59
+ self.mode: Mode = mode
60
+ self.refresh_interval = refresh_interval
61
+ # Start collecting as soon as a graph exists, not when it is first opened.
62
+ collector()
63
+
64
+ def named_tables(self) -> dict[str, Table]:
65
+ """The tables the graph is anchored on, by name."""
66
+ scope = self.scope
67
+ if scope is None:
68
+ main = sys.modules.get("__main__")
69
+ scope = vars(main) if main is not None else {}
70
+ found = {
71
+ name: value
72
+ for name, value in list(scope.items())
73
+ if isinstance(value, Table) and not name.startswith("_")
74
+ }
75
+ found.update(self.tables)
76
+ return found
77
+
78
+ def snapshot(
79
+ self, mode: Mode | None = None, steps: dict[str, int] | None = None
80
+ ) -> dict[str, Any]:
81
+ """Render the graph as a JSON-friendly dictionary.
82
+
83
+ Args:
84
+ mode: Overrides the graph's mode.
85
+ steps: Last seen update step per table name. Updated in place and used to
86
+ flag tables that ticked since the previous snapshot.
87
+ """
88
+ named = []
89
+ for name, table in self.named_tables().items():
90
+ entry_ids = table_entry_ids(table)
91
+ if entry_ids is None:
92
+ continue
93
+ ticked = False
94
+ if steps is not None and table.is_refreshing:
95
+ step = last_notification_step(table)
96
+ ticked = name in steps and steps[name] != step
97
+ steps[name] = step
98
+ named.append(
99
+ NamedTable(
100
+ name=name,
101
+ entry_ids=entry_ids,
102
+ size=table.size,
103
+ refreshing=table.is_refreshing,
104
+ ticked=ticked,
105
+ )
106
+ )
107
+ graph = collector().build_graph(named, mode or self.mode)
108
+ config = performance_config()
109
+ warnings = []
110
+ interval = config["reportIntervalMillis"]
111
+ if interval is None or interval > LIVE_INTERVAL_MILLIS:
112
+ warnings.append(
113
+ f"Cost statistics refresh every {(interval or 60_000) / 1000:g}s. Start the "
114
+ "server with -DUpdatePerformanceTracker.reportIntervalMillis=1000 for live "
115
+ "statistics."
116
+ )
117
+ if config["minimumUpdateLogDurationNanos"] != 0:
118
+ warnings.append(
119
+ "Cheap operations are folded into 'Aggregated Small Updates' and may be "
120
+ "missing. Start the server with "
121
+ "-DQueryPerformance.minimumUpdateLogDurationNanos=0 for a complete graph."
122
+ )
123
+ if graph["missingLineage"]:
124
+ warnings.append(
125
+ "No lineage recorded yet for: "
126
+ + ", ".join(graph["missingLineage"])
127
+ + ". Lineage appears once an operation has ticked, and is only recorded "
128
+ "for operations created after the plugin was loaded."
129
+ )
130
+ graph["config"] = config
131
+ graph["warnings"] = warnings
132
+ return graph
133
+
134
+
135
+ class QueryGraphType(BidirectionalObjectType):
136
+ """Object type for :class:`QueryGraph`."""
137
+
138
+ @property
139
+ def name(self) -> str:
140
+ return NAME
141
+
142
+ def is_type(self, obj: Any) -> bool:
143
+ return isinstance(obj, QueryGraph)
144
+
145
+ def create_client_connection(
146
+ self, obj: QueryGraph, connection: MessageStream
147
+ ) -> MessageStream:
148
+ return QueryGraphConnection(obj, connection)
149
+
150
+
151
+ class QueryGraphConnection(MessageStream):
152
+ """Pushes graph snapshots to one client and answers its requests.
153
+
154
+ Client messages are JSON objects:
155
+
156
+ - ``{"type": "MODE", "mode": "named" | "all"}`` switches the graph mode.
157
+ - ``{"type": "OPEN", "name": <table name>}`` replies with ``{"type": "TABLE"}``
158
+ and the table as an exported reference.
159
+ """
160
+
161
+ def __init__(self, graph: QueryGraph, client: MessageStream):
162
+ super().__init__()
163
+ self._graph = graph
164
+ self._client = client
165
+ self._mode: Mode = graph.mode
166
+ self._steps: dict[str, int] = {}
167
+ self._exec_ctx = get_exec_ctx()
168
+ self._lock = threading.Lock()
169
+ self._closed = threading.Event()
170
+ self._push()
171
+ self._thread = threading.Thread(
172
+ target=self._run, name="deephaven-query-graph", daemon=True
173
+ )
174
+ self._thread.start()
175
+
176
+ def _run(self) -> None:
177
+ while not self._closed.wait(self._graph.refresh_interval):
178
+ self._push()
179
+
180
+ def _send(
181
+ self, message: dict[str, Any], references: list[Any] | None = None
182
+ ) -> None:
183
+ self._client.on_data(
184
+ json.dumps(message, default=str).encode(), references or []
185
+ )
186
+
187
+ def _push(self) -> None:
188
+ with self._lock:
189
+ if self._closed.is_set():
190
+ return
191
+ try:
192
+ with self._exec_ctx:
193
+ graph = self._graph.snapshot(self._mode, self._steps)
194
+ self._send({"type": "GRAPH", **graph})
195
+ except Exception: # noqa: BLE001 - keep the connection alive
196
+ logger.exception("Failed to send query graph")
197
+
198
+ def on_data(self, payload: bytes, references: list[Any]) -> None:
199
+ try:
200
+ message = json.loads(bytes(payload).decode("utf-8") or "{}")
201
+ except (UnicodeDecodeError, json.JSONDecodeError):
202
+ logger.warning("Ignoring malformed query graph message")
203
+ return
204
+ kind = message.get("type")
205
+ if kind == "MODE" and message.get("mode") in MODES:
206
+ self._mode = cast(Mode, message["mode"])
207
+ self._push()
208
+ elif kind == "OPEN":
209
+ name = message.get("name")
210
+ table = self._graph.named_tables().get(name)
211
+ with self._lock:
212
+ if table is None:
213
+ self._send({"type": "ERROR", "message": f"No table named {name!r}"})
214
+ else:
215
+ self._send({"type": "TABLE", "name": name}, [table])
216
+
217
+ def on_close(self) -> None:
218
+ self._closed.set()