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,56 @@
1
+ """A live map of table lineage and update cost.
2
+
3
+ Example:
4
+
5
+ .. code-block:: python
6
+
7
+ from deephaven.query_graph import query_graph
8
+
9
+ graph = query_graph()
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Mapping
15
+
16
+ from deephaven.table import Table
17
+
18
+ from ._model import LineageState, NamedTable, describe
19
+ from ._widget import QueryGraph, QueryGraphType
20
+
21
+
22
+ def query_graph(
23
+ tables: Mapping[str, Table] | None = None,
24
+ scope: Mapping[str, Any] | None = None,
25
+ mode: str = "named",
26
+ refresh_interval: float = 1.0,
27
+ ) -> QueryGraph:
28
+ """Create a live map of how tables derive from each other and what each step costs.
29
+
30
+ Args:
31
+ tables: Tables to anchor the graph on, by name, in addition to those in ``scope``.
32
+ scope: Where to find named tables, such as ``globals()``. Defaults to the
33
+ console's global scope.
34
+ mode: ``"named"`` (named tables and their ancestors) or ``"all"`` (every
35
+ operation in the performance logs). Can be switched in the UI.
36
+ refresh_interval: Seconds between updates sent to the client.
37
+
38
+ Returns:
39
+ The graph widget.
40
+ """
41
+ return QueryGraph(
42
+ tables=tables,
43
+ scope=scope,
44
+ mode=mode, # type: ignore[arg-type]
45
+ refresh_interval=refresh_interval,
46
+ )
47
+
48
+
49
+ __all__ = [
50
+ "LineageState",
51
+ "NamedTable",
52
+ "QueryGraph",
53
+ "QueryGraphType",
54
+ "describe",
55
+ "query_graph",
56
+ ]
@@ -0,0 +1,181 @@
1
+ """Feeds :class:`LineageState` from the engine's performance logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ import threading
8
+ from typing import Any
9
+
10
+ import jpy
11
+ import numpy as np
12
+ from deephaven import perfmon
13
+ from deephaven.constants import NULL_LONG
14
+ from deephaven.liveness_scope import LivenessScope
15
+ from deephaven.table import Table
16
+ from deephaven.table_listener import listen
17
+
18
+ from ._model import LineageState, Mode, NamedTable
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _BaseTable = jpy.get_type("io.deephaven.engine.table.impl.BaseTable")
23
+ _Configuration = jpy.get_type("io.deephaven.configuration.Configuration")
24
+
25
+ INTERVAL_PROPERTY = "UpdatePerformanceTracker.reportIntervalMillis"
26
+ THRESHOLD_PROPERTY = "QueryPerformance.minimumUpdateLogDurationNanos"
27
+ SEED_ROWS = 20_000
28
+
29
+ _UPL_COLUMNS = [
30
+ "EntryId",
31
+ "EntryDescription",
32
+ "EntryCallerLine",
33
+ "UpdateGraph",
34
+ "UsageNanos",
35
+ "CpuNanos",
36
+ "RowsAdded",
37
+ "RowsRemoved",
38
+ "RowsModified",
39
+ "InvocationCount",
40
+ "IntervalEndNanos = epochNanos(IntervalEndTime)",
41
+ "IntervalNanos = epochNanos(IntervalEndTime) - epochNanos(IntervalStartTime)",
42
+ ]
43
+ _UPL_NAMES = [c.split("=")[0].strip() for c in _UPL_COLUMNS]
44
+
45
+
46
+ def _py(value: Any) -> Any:
47
+ if isinstance(value, np.generic):
48
+ value = value.item()
49
+ if value == NULL_LONG:
50
+ return None
51
+ return value
52
+
53
+
54
+ _ancestors_lock = threading.Lock()
55
+ _ancestors_scope: LivenessScope | None = None
56
+ _ancestors_log: Table | None = None
57
+
58
+
59
+ def ensure_ancestors_log() -> Table:
60
+ """Start recording ancestry, and return the ancestors log.
61
+
62
+ The log is an append-only view of a blink table, so it only holds entries published
63
+ while it is alive. Keep it alive for the life of the process, from plugin startup.
64
+ """
65
+ global _ancestors_scope, _ancestors_log
66
+ with _ancestors_lock:
67
+ if _ancestors_log is None:
68
+ scope = LivenessScope()
69
+ with scope.open():
70
+ _ancestors_log = perfmon.update_performance_ancestors_log()
71
+ _ancestors_scope = scope
72
+ return _ancestors_log
73
+
74
+
75
+ def performance_config() -> dict[str, int | None]:
76
+ """The performance-log settings that affect how complete and live the graph is."""
77
+ config = _Configuration.getInstance()
78
+ interval = config.getLongWithDefault(INTERVAL_PROPERTY, -1)
79
+ threshold = config.getLongWithDefault(THRESHOLD_PROPERTY, -1)
80
+ return {
81
+ "reportIntervalMillis": None if interval < 0 else interval,
82
+ "minimumUpdateLogDurationNanos": None if threshold < 0 else threshold,
83
+ }
84
+
85
+
86
+ def table_entry_ids(table: Table) -> tuple[int, ...] | None:
87
+ """The performance entries that produce ``table``, or None if it isn't a BaseTable."""
88
+ j_table = getattr(table, "j_table", None)
89
+ if j_table is None or not _BaseTable.jclass.isInstance(j_table):
90
+ return None
91
+ return tuple(
92
+ int(i)
93
+ for i in jpy.cast(j_table, _BaseTable).parentPerformanceEntryIds().toArray()
94
+ )
95
+
96
+
97
+ def last_notification_step(table: Table) -> int:
98
+ """The update graph step the table last changed on."""
99
+ return int(jpy.cast(table.j_table, _BaseTable).getLastNotificationStep())
100
+
101
+
102
+ class LineageCollector:
103
+ """Listens to the update performance logs and maintains a :class:`LineageState`."""
104
+
105
+ def __init__(self, history_size: int = 60):
106
+ self._lock = threading.Lock()
107
+ self.state = LineageState(history_size)
108
+ self._scope = LivenessScope()
109
+ with self._scope.open():
110
+ ancestors = ensure_ancestors_log().view(
111
+ [
112
+ "EntryId",
113
+ "EntryDescription",
114
+ "UpdateGraph",
115
+ "AncestorText = Ancestors == null ? `` : Ancestors.toString()",
116
+ ]
117
+ )
118
+ upl = perfmon.update_performance_log().view(_UPL_COLUMNS)
119
+ self._ingest_intervals(self._columns(upl.tail(SEED_ROWS).snapshot()))
120
+ self._handles = [
121
+ listen(ancestors, self._on_ancestors, do_replay=True),
122
+ listen(upl, self._on_upl),
123
+ ]
124
+
125
+ @staticmethod
126
+ def _columns(table: Table) -> dict[str, list[Any]]:
127
+ columns: dict[str, list[Any]] = {name: [] for name in table.column_names}
128
+ for chunk in table.iter_chunk_dict():
129
+ for name, values in chunk.items():
130
+ columns[name].extend(values)
131
+ return columns
132
+
133
+ def _on_ancestors(self, update: Any, is_replay: bool) -> None:
134
+ added = update.added()
135
+ rows = [
136
+ (
137
+ int(_py(entry_id)),
138
+ None if description is None else str(description),
139
+ [int(a) for a in re.findall(r"-?\d+", str(text or ""))],
140
+ None if graph is None else str(graph),
141
+ )
142
+ for entry_id, description, text, graph in zip(
143
+ added["EntryId"],
144
+ added["EntryDescription"],
145
+ added["AncestorText"],
146
+ added["UpdateGraph"],
147
+ )
148
+ ]
149
+ with self._lock:
150
+ self.state.record_ancestors(rows)
151
+
152
+ def _on_upl(self, update: Any, is_replay: bool) -> None:
153
+ self._ingest_intervals(update.added())
154
+
155
+ def _ingest_intervals(self, columns: dict[str, Any]) -> None:
156
+ count = len(columns.get("EntryId", ()))
157
+ intervals: dict[int, list[dict[str, Any]]] = {}
158
+ for i in range(count):
159
+ row = {name: _py(columns[name][i]) for name in _UPL_NAMES}
160
+ intervals.setdefault(row["IntervalEndNanos"], []).append(row)
161
+ with self._lock:
162
+ for end in sorted(intervals):
163
+ self.state.record_interval(end, intervals[end])
164
+
165
+ def build_graph(self, named: list[NamedTable], mode: Mode) -> dict[str, Any]:
166
+ """Render the current graph."""
167
+ with self._lock:
168
+ return self.state.build_graph(named, mode)
169
+
170
+
171
+ _collector: LineageCollector | None = None
172
+ _collector_lock = threading.Lock()
173
+
174
+
175
+ def collector() -> LineageCollector:
176
+ """The process-wide collector, created on first use."""
177
+ global _collector
178
+ with _collector_lock:
179
+ if _collector is None:
180
+ _collector = LineageCollector()
181
+ return _collector