model-debugger 0.4.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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/repl/remote.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""A client of a live ``mdb serve`` session: gdb's ``target remote`` for models.
|
|
2
|
+
|
|
3
|
+
The model and the debugger live in the server process (``mdb serve --project DIR --model PATH``
|
|
4
|
+
on the machine with the weights); this module drives them over the server's HTTP API and needs
|
|
5
|
+
only the standard library, so the machine that types the commands needs no model framework.
|
|
6
|
+
|
|
7
|
+
remote = Remote("http://127.0.0.1:8765")
|
|
8
|
+
remote.console("until t3.L1.p") # the text the REPL prints
|
|
9
|
+
remote.op("print", address="p", top=3) # the JSON `python -m mdb.repl --json` prints
|
|
10
|
+
RemoteShell(remote).loop() # the same REPL prompt, served remotely
|
|
11
|
+
|
|
12
|
+
mdb engine --connect http://127.0.0.1:8765 [--script FILE]
|
|
13
|
+
|
|
14
|
+
Every command runs through the server's op registry, so a remote command and a local one are
|
|
15
|
+
the same operation. Three things differ from the local REPL and are handled here:
|
|
16
|
+
``quit`` ends the client and leaves the server session as it is; ``source FILE`` reads the
|
|
17
|
+
file on the client and sends its lines; Ctrl-C asks the server to interrupt the running op and
|
|
18
|
+
then keeps waiting for that op's own answer. ``record`` is refused by the server. An empty line
|
|
19
|
+
repeats nothing (the local REPL repeats the last motion).
|
|
20
|
+
|
|
21
|
+
The server has no authentication: it accepts loopback by default, so reach a remote machine
|
|
22
|
+
through a tunnel (``ssh -L 8765:127.0.0.1:8765 host``) rather than by binding it to a network.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import sys
|
|
29
|
+
import urllib.error
|
|
30
|
+
import urllib.parse
|
|
31
|
+
import urllib.request
|
|
32
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
33
|
+
from concurrent.futures import TimeoutError as FutureTimeout
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any, Callable, TextIO
|
|
36
|
+
|
|
37
|
+
Transport = Callable[[str, str, "dict[str, Any] | None"], "tuple[int, Any]"]
|
|
38
|
+
QUIT = ("quit", "q", "exit")
|
|
39
|
+
MAX_SOURCE_DEPTH = 16
|
|
40
|
+
API = "/api/v1"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RemoteError(Exception):
|
|
44
|
+
"""The server refused a request before any op ran (``busy``, ``unknown-op``, ``not_live``,
|
|
45
|
+
``host_not_allowed``, ...) or could not be reached (``unreachable``, ``bad-response``)."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, kind: str, message: str, status: int | None = None):
|
|
48
|
+
super().__init__(f"{kind}: {message}")
|
|
49
|
+
self.kind, self.message, self.status = kind, message, status
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def http_transport(base: str, timeout: float) -> Transport:
|
|
53
|
+
"""``send(method, path, body) -> (status, json)`` over urllib; no proxy, no redirect."""
|
|
54
|
+
|
|
55
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
56
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
|
|
60
|
+
|
|
61
|
+
def send(method: str, path: str, body: dict[str, Any] | None) -> tuple[int, Any]:
|
|
62
|
+
data = None if body is None else json.dumps(body).encode()
|
|
63
|
+
headers = {"Accept": "application/json"}
|
|
64
|
+
if data is not None:
|
|
65
|
+
headers["Content-Type"] = "application/json"
|
|
66
|
+
request = urllib.request.Request(base + path, data=data, method=method, headers=headers)
|
|
67
|
+
try:
|
|
68
|
+
with opener.open(request, timeout=timeout) as response:
|
|
69
|
+
status, raw = response.status, response.read()
|
|
70
|
+
except urllib.error.HTTPError as error:
|
|
71
|
+
status, raw = error.code, error.read()
|
|
72
|
+
except (urllib.error.URLError, OSError) as error:
|
|
73
|
+
reason = getattr(error, "reason", error)
|
|
74
|
+
raise RemoteError("unreachable", f"cannot reach {base}: {reason}") from error
|
|
75
|
+
try:
|
|
76
|
+
return status, json.loads(raw)
|
|
77
|
+
except ValueError as error:
|
|
78
|
+
raise RemoteError("bad-response", f"{base}{path} answered {status} with a body "
|
|
79
|
+
"that is not JSON (is this an mdb serve address?)",
|
|
80
|
+
status) from error
|
|
81
|
+
|
|
82
|
+
return send
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _base(url: str) -> str:
|
|
86
|
+
parts = urllib.parse.urlsplit(url if "://" in url else f"http://{url}")
|
|
87
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
88
|
+
raise RemoteError("bad-url", f"{url!r} is not an http(s) address of an mdb serve")
|
|
89
|
+
if parts.path not in ("", "/") or parts.query or parts.fragment:
|
|
90
|
+
raise RemoteError("bad-url", f"{url!r}: give the server address only, as "
|
|
91
|
+
f"{parts.scheme}://{parts.netloc}")
|
|
92
|
+
return f"{parts.scheme}://{parts.netloc}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Remote:
|
|
96
|
+
"""One live session of an ``mdb serve``. ``where`` and ``seq`` follow the last answer."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, url: str, *, timeout: float = 3600.0,
|
|
99
|
+
transport: Transport | None = None):
|
|
100
|
+
self.url = _base(url)
|
|
101
|
+
self._send = transport or http_transport(self.url, timeout)
|
|
102
|
+
self._requests = 0
|
|
103
|
+
hello = self._data("GET", "/hello")
|
|
104
|
+
if not isinstance(hello, dict) or "version" not in hello:
|
|
105
|
+
raise RemoteError("bad-response", f"{self.url} is not an mdb serve")
|
|
106
|
+
self.version: str = str(hello["version"])
|
|
107
|
+
self.sid = hello.get("live")
|
|
108
|
+
if not self.sid:
|
|
109
|
+
raise RemoteError("not_live", f"{self.url} holds no live session (it was started "
|
|
110
|
+
"without --tiny or --model); there is nothing to step")
|
|
111
|
+
self.where: str | None = None
|
|
112
|
+
self.seq = 0
|
|
113
|
+
|
|
114
|
+
# ------------------------------------------------------------------ wire
|
|
115
|
+
|
|
116
|
+
def _data(self, method: str, path: str, body: dict[str, Any] | None = None) -> Any:
|
|
117
|
+
status, answer = self._send(method, API + path, body)
|
|
118
|
+
if isinstance(answer, dict) and "data" in answer:
|
|
119
|
+
return answer["data"]
|
|
120
|
+
if isinstance(answer, dict) and "refused" in answer:
|
|
121
|
+
raise RemoteError(str(answer["refused"]), str(answer.get("detail") or ""), status)
|
|
122
|
+
raise RemoteError("bad-response", f"{method} {path} answered {status} without data",
|
|
123
|
+
status)
|
|
124
|
+
|
|
125
|
+
def _session(self, method: str, path: str, body: dict[str, Any] | None = None) -> Any:
|
|
126
|
+
data = self._data(method, f"/s/{self.sid}{path}", body)
|
|
127
|
+
if isinstance(data, dict):
|
|
128
|
+
if "where" in data:
|
|
129
|
+
self.where = data["where"]
|
|
130
|
+
if isinstance(data.get("seq"), int):
|
|
131
|
+
self.seq = data["seq"]
|
|
132
|
+
return data
|
|
133
|
+
|
|
134
|
+
# ------------------------------------------------------------------ commands
|
|
135
|
+
|
|
136
|
+
def op(self, name: str, args: dict[str, Any] | None = None, **more: Any) -> dict[str, Any]:
|
|
137
|
+
"""One registered op. The value is the op's own JSON, exactly what ``python -m mdb.repl
|
|
138
|
+
--json`` prints for the command: a result, ``{error, state, reason}`` when the op
|
|
139
|
+
refused, or ``{interrupted, state, reason}``. ``RemoteError`` is raised only when the
|
|
140
|
+
server refused the request itself."""
|
|
141
|
+
self._requests += 1
|
|
142
|
+
body = {"op": name, "args": {**(args or {}), **more}, "request_id": f"c{self._requests}"}
|
|
143
|
+
return self._session("POST", "/op", body)["result"]
|
|
144
|
+
|
|
145
|
+
def console(self, line: str) -> str:
|
|
146
|
+
"""One command line through the server's REPL parser; the text the REPL prints."""
|
|
147
|
+
return self._session("POST", "/console", {"line": line})["text"]
|
|
148
|
+
|
|
149
|
+
def interrupt(self) -> dict[str, Any]:
|
|
150
|
+
"""Ctrl-C for the op the server is running; says whether one was running."""
|
|
151
|
+
return self._session("POST", "/interrupt")
|
|
152
|
+
|
|
153
|
+
def frame(self) -> dict[str, Any]:
|
|
154
|
+
"""The live frame: cursor, the current layer's ports, edits, breakpoints, checkpoints."""
|
|
155
|
+
return self._session("GET", "/live")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class RemoteShell:
|
|
159
|
+
"""The REPL prompt over a ``Remote``: same lines in, same text out."""
|
|
160
|
+
|
|
161
|
+
def __init__(self, remote: Remote, *, out: TextIO | None = None, prompt: str = "(mdb) ",
|
|
162
|
+
poll: float = 0.1):
|
|
163
|
+
self.remote = remote
|
|
164
|
+
self.out = out if out is not None else sys.stdout
|
|
165
|
+
self.prompt = prompt
|
|
166
|
+
self.poll = poll
|
|
167
|
+
self.errors = 0
|
|
168
|
+
self.depth = 0
|
|
169
|
+
self._failed = False
|
|
170
|
+
self._interrupted = False
|
|
171
|
+
self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="mdb-remote")
|
|
172
|
+
|
|
173
|
+
def write(self, text: str) -> None:
|
|
174
|
+
self.out.write(text + "\n")
|
|
175
|
+
|
|
176
|
+
def close(self) -> None:
|
|
177
|
+
self._pool.shutdown(wait=False, cancel_futures=True)
|
|
178
|
+
|
|
179
|
+
def _console(self, line: str) -> str:
|
|
180
|
+
"""Send one line; Ctrl-C while it runs interrupts the server's op, and the wait goes on
|
|
181
|
+
until that op answers (``interrupted at WHERE``). A second Ctrl-C asks again."""
|
|
182
|
+
future = self._pool.submit(self.remote.console, line)
|
|
183
|
+
while True:
|
|
184
|
+
try:
|
|
185
|
+
return future.result(timeout=self.poll)
|
|
186
|
+
except FutureTimeout:
|
|
187
|
+
continue
|
|
188
|
+
except KeyboardInterrupt:
|
|
189
|
+
self._interrupted = True
|
|
190
|
+
try:
|
|
191
|
+
self.remote.interrupt()
|
|
192
|
+
except RemoteError as error:
|
|
193
|
+
self.write(f"error ({error.kind}): interrupt was not delivered: "
|
|
194
|
+
f"{error.message}")
|
|
195
|
+
|
|
196
|
+
def execute(self, line: str) -> bool:
|
|
197
|
+
"""Run one command line; False means quit. Server refusals are printed, not raised."""
|
|
198
|
+
text = line.strip()
|
|
199
|
+
if self.depth == 0:
|
|
200
|
+
self._interrupted = False
|
|
201
|
+
if not text or text.startswith("#"):
|
|
202
|
+
return True
|
|
203
|
+
verb, _, rest = text.partition(" ")
|
|
204
|
+
if verb in QUIT:
|
|
205
|
+
return False
|
|
206
|
+
self._failed = False
|
|
207
|
+
if verb == "source":
|
|
208
|
+
self._source_line(rest.strip())
|
|
209
|
+
return True
|
|
210
|
+
try:
|
|
211
|
+
out = self._console(text)
|
|
212
|
+
except RemoteError as error:
|
|
213
|
+
out = f"error ({error.kind}): {error.message}"
|
|
214
|
+
if out.startswith("error") or out.startswith("interrupted at "):
|
|
215
|
+
self.errors += 1
|
|
216
|
+
self._failed = True
|
|
217
|
+
if out:
|
|
218
|
+
self.write(out)
|
|
219
|
+
return True
|
|
220
|
+
|
|
221
|
+
def _source_line(self, rest: str) -> None:
|
|
222
|
+
words = rest.split()
|
|
223
|
+
keep_going = bool(words) and words[0] == "-k"
|
|
224
|
+
names = words[1:] if keep_going else words
|
|
225
|
+
if len(names) != 1:
|
|
226
|
+
self.errors += 1
|
|
227
|
+
self._failed = True
|
|
228
|
+
self.write("error (bad-args): usage: source [-k] FILE")
|
|
229
|
+
return
|
|
230
|
+
try:
|
|
231
|
+
self.source(names[0], keep_going=keep_going)
|
|
232
|
+
except OSError as error:
|
|
233
|
+
self.errors += 1
|
|
234
|
+
self._failed = True
|
|
235
|
+
self.write(f"error (bad-args): cannot read {names[0]}: {error.strerror or error}")
|
|
236
|
+
|
|
237
|
+
def source(self, path: str, *, echo: bool = True, keep_going: bool = False) -> int:
|
|
238
|
+
"""Send a local command file line by line. It stops at the first error unless
|
|
239
|
+
``keep_going`` (``source -k``). Returns the number of errors."""
|
|
240
|
+
if self.depth >= MAX_SOURCE_DEPTH:
|
|
241
|
+
self.errors += 1
|
|
242
|
+
self._failed = True
|
|
243
|
+
self.write(f"error (bad-args): source nests more than {MAX_SOURCE_DEPTH} deep: {path}")
|
|
244
|
+
return 1
|
|
245
|
+
before = self.errors
|
|
246
|
+
lines = Path(path).expanduser().read_text().splitlines()
|
|
247
|
+
self.depth += 1
|
|
248
|
+
try:
|
|
249
|
+
for number, raw in enumerate(lines, 1):
|
|
250
|
+
line = raw.strip()
|
|
251
|
+
if not line or line.startswith("#"):
|
|
252
|
+
continue
|
|
253
|
+
if echo:
|
|
254
|
+
self.write(f"{self.prompt}{line}")
|
|
255
|
+
self._failed = False
|
|
256
|
+
if not self.execute(line) or self._interrupted:
|
|
257
|
+
break
|
|
258
|
+
if self._failed and not keep_going:
|
|
259
|
+
if self.depth == 1:
|
|
260
|
+
self.write(f"error: stopped sourcing {path} at line {number} "
|
|
261
|
+
"(use `source -k FILE` to keep going)")
|
|
262
|
+
break
|
|
263
|
+
finally:
|
|
264
|
+
self.depth -= 1
|
|
265
|
+
if keep_going:
|
|
266
|
+
self._failed = False
|
|
267
|
+
return self.errors - before
|
|
268
|
+
|
|
269
|
+
def loop(self, stream: TextIO | None = None) -> int:
|
|
270
|
+
stream = stream if stream is not None else sys.stdin
|
|
271
|
+
interactive = stream is sys.stdin and stream.isatty()
|
|
272
|
+
if interactive:
|
|
273
|
+
try:
|
|
274
|
+
import readline # noqa: F401 - line editing and history for input()
|
|
275
|
+
except ImportError:
|
|
276
|
+
pass
|
|
277
|
+
try:
|
|
278
|
+
while True:
|
|
279
|
+
try:
|
|
280
|
+
if interactive:
|
|
281
|
+
line = input(self.prompt)
|
|
282
|
+
else:
|
|
283
|
+
line = stream.readline()
|
|
284
|
+
if not line:
|
|
285
|
+
break
|
|
286
|
+
line = line.rstrip("\n")
|
|
287
|
+
if line.strip() and not line.strip().startswith("#"):
|
|
288
|
+
self.write(f"{self.prompt}{line.strip()}")
|
|
289
|
+
except EOFError:
|
|
290
|
+
break
|
|
291
|
+
except KeyboardInterrupt:
|
|
292
|
+
self.write("")
|
|
293
|
+
continue
|
|
294
|
+
if not self.execute(line):
|
|
295
|
+
break
|
|
296
|
+
finally:
|
|
297
|
+
self.close()
|
|
298
|
+
return 0 if self.errors == 0 else 1
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def main(url: str, *, start: str | None = None, script: str | None = None,
|
|
302
|
+
out: TextIO | None = None) -> int:
|
|
303
|
+
"""``mdb engine --connect URL``: attach to the server's live session and run the prompt."""
|
|
304
|
+
try:
|
|
305
|
+
remote = Remote(url)
|
|
306
|
+
except RemoteError as error:
|
|
307
|
+
print(f"mdb engine: {error.message} ({error.kind})", file=sys.stderr)
|
|
308
|
+
return 2
|
|
309
|
+
shell = RemoteShell(remote, out=out)
|
|
310
|
+
try:
|
|
311
|
+
if start is not None:
|
|
312
|
+
shell.write(f"{shell.prompt}{start}")
|
|
313
|
+
shell.execute(start)
|
|
314
|
+
if script:
|
|
315
|
+
try:
|
|
316
|
+
shell.source(script)
|
|
317
|
+
except OSError as error:
|
|
318
|
+
print(f"mdb engine: cannot read {script}: {error.strerror or error}",
|
|
319
|
+
file=sys.stderr)
|
|
320
|
+
return 2
|
|
321
|
+
return 0 if shell.errors == 0 else 1
|
|
322
|
+
return shell.loop()
|
|
323
|
+
finally:
|
|
324
|
+
shell.close()
|