Repository navigation
Expand file tree
/
Copy pathml_proxy.py
More file actions
executable file
·2256 lines (2020 loc) · 97.8 KB
/
Copy pathml_proxy.py
File metadata and controls
executable file
·2256 lines (2020 loc) · 97.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Isabelle Remote ML Prover Proxy
===============================
Runs the Isabelle ML prover (Poly/ML) and associated servers on a remote machine
while keeping jEdit + Scala/PIDE local. No Isabelle source changes required.
Normal Isabelle Architecture
----------------------------
In a standard local session, Isabelle has three communicating processes:
jEdit/Scala (GUI + PIDE) Poly/ML (prover)
┌─────────────────────┐ ┌─────────────────────┐
│ │ │ │
│ Document model │ PIDE │ Theory processing │
│ Rendering │◄════════► │ Proof checking │
│ Session management │ TCP │ Code generation │
│ │ │ │
│ Bash.Server ◄──────┼───────────┼── bash_process() │
│ (localhost:P2) │ TCP │ (sledgehammer etc) │
│ │ │ │
└─────────────────────┘ └─────────────────────┘
Startup sequence:
1. jEdit/Scala creates a System_Channel (TCP server on localhost:P1)
and writes its address + password to ISABELLE_PROCESS_OPTIONS file.
2. Scala starts a Bash.Server on localhost:P2 (random port + password).
3. Scala spawns the poly process wrapped in a configurable `process_policy`,
passing the full poly command line. The poly process inherits
ISABELLE_PROCESS_OPTIONS.
4. Poly/ML reads ISABELLE_PROCESS_OPTIONS, connects back to localhost:P1,
sends the password. The PIDE channel is established.
5. Scala sends `Prover.options` over PIDE, which includes
bash_process_address=127.0.0.1:P2 and bash_process_password=UUID.
6. When ML needs external tools (e.g. sledgehammer), it connects to
the Bash.Server at 127.0.0.1:P2 to run shell commands.
7. For heap builds, Scala sends `build_session` over PIDE, which includes
session_directories (filesystem paths) and options (including
bash_process_address/password). ML reads theory files from disk.
8. For interactive builds, Poly/ML receives file contents via PIDE;
it does not read the file system.
Proxied Architecture
--------------------
This script interposes between Scala and a remote Poly/ML:
LOCAL MACHINE REMOTE MACHINE
┌──────────────────┐ ┌──────────────────┐
│ jEdit/Scala │ │ Poly/ML │
│ │ │ │
│ System_Channel │ ┌───────────────┐ SSH │ │
│ (localhost:P1) ◄─┼─┤ PIDE proxy ├───-R────►│ connects to │
│ │ │ (localhost:P3)│ tunnel │ localhost:P3 │
│ Bash.Server │ │ │ │ │
│ (localhost:P2) │ │ Intercepts: │ │ bash_process()───┼─┐
│ (unused) │ │ • Prover. │ │ │ │
│ │ │ options │ └──────────────────┘ │
│ │ │ • build_ │ │
│ │ │ session │ ┌──────────────────┐ │
│ │ │ • ML→Scala │ │ Remote │ │
│ │ │ errors │ │ Bash.Server │◄┘
│ │ │ • ML stats │ │ (localhost:P4) │
│ │ │ • loading_ │ └──────────────────┘
│ │ │ theory │
│ │ └──────┬────────┘ ┌──────────────────┐
│ │ │ SSH │ Stats monitor │
│ │ └──────────────────►│ (poly process) │
│ │ proxy_ml_stats ◄───│ ML_Statistics. │
│ │ │ monitor PID │
└──────────────────┘ └──────────────────┘
Startup sequence:
1. The proxy + configuration is passed to Isabelle as a `process_policy`;
whenever Isabelle invokes Poly/ML, the invocation will thus be wrapped
by the proxy.
2. Proxy rewrites paths in the command line: ISABELLE_HOME, POLYML_HOME,
ML_PLATFORM, HOME (for heap paths in ~/.isabelle/).
3. Proxy matches local Isabelle components to remote components by basename,
building a path rewrite table for components outside ISABELLE_HOME/HOME.
4. Proxy extracts the PIDE channel port (P1) from ISABELLE_PROCESS_OPTIONS.
5. Proxy creates a PIDE proxy server on localhost:P3 (random port).
6. Proxy starts a Bash.Server on the remote (localhost:P4), capturing its
address and password.
7. Proxy rewrites ISABELLE_PROCESS_OPTIONS: P1 → P3 (so ML connects to
the proxy, not directly to Scala). Copies it to the remote.
8. Proxy rewrites ISABELLE_INIT_SESSION: replaces local paths with remote
paths (components, ISABELLE_HOME, HOME). Copies it to the remote.
9. Proxy queries remote Isabelle env vars and builds the remote command.
10. For heap builds of local sessions (cwd outside ISABELLE_HOME), proxy
rsyncs the session source directory to a temp dir on the remote.
11. Proxy starts the PIDE proxy thread (bidirectional message forwarding).
12. Proxy launches poly on the remote via SSH with a reverse tunnel
(remote:P3 → local:P3) so ML can reach the PIDE proxy.
PIDE proxy interceptions (Scala→ML):
• Prover.options: rewrites bash_process_address/password to point to the
remote Bash.Server (P4) instead of the local one (P2).
• build_session: rewrites session_directories paths (local → remote) and
bash_process_address/password (same as Prover.options).
PIDE proxy interceptions (ML→Scala):
• "error" with "No such file": downgraded to "warning" (remote ML cannot
verify local file existence for \\<^file> annotations).
• "status" with "failed" on text commands: dropped (cosmetic failure from
\\<^file> checks; the subsequent "finished" status completes the command).
• "protocol" with "function=ML_statistics": suppressed. Instead, the proxy
starts a separate remote poly process that runs ML_Statistics.monitor to
poll the remote POLYSTATSDIR, and injects the results back to Scala as
proxy_ml_stats messages. This is necessary because Scala normally reads
stats files from POLYSTATSDIR on the local filesystem, which doesn't
exist when the prover runs remotely.
• "protocol" with "function=loading_theory": reverse-rewrites remote paths
back to local paths, so that Scala's Sources lookup (which is keyed by
local paths) can find the correct session source entries.
Post-build:
• If ML_Heap.save_child is in the command (heap build), the built heap is
rsynced back from remote to the local heap directory, reversing the
platform/HOME/ISABELLE_HOME path rewrites. This way, an 'inventory' of
remote heaps can be retained on the localhost.
• Temp files on the remote are cleaned up.
Usage
-----
To use the proxy directly, pass it as a Poly/ML wrapper via the existing
`process_policy` option, e.g.:
isabelle jedit -l HOL -o 'process_policy=/path/to/ml_proxy.py \\
-v --log /tmp/ml_proxy.log \\
--host user@remote \\
--target-isabelle-home /path/to/isabelle/on/remote \\
--target-ml-platform arm64-linux --'
To make this more convenient, however, the `configure-remote.py` script
should be used to generate the required Isabelle flags. See the documentation
of `configure-remote.py` for more information.
"""
import argparse
import atexit
from collections import deque
import os
import re
import shlex
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
import logging
logger = logging.getLogger("ml_proxy")
class MgmtLogHandler(logging.Handler):
"""Logging handler that forwards messages to a management console.
Maps logger levels to mgmt verbosity:
WARNING/ERROR → level 0 (always shown)
INFO → level 0 (always shown)
DEBUG → level 1 (shown at /verbosity >= 1)
"""
def __init__(self, mgmt):
super().__init__()
self.mgmt = mgmt
def emit(self, record):
try:
msg = f"{DIM}[{record.levelname[0]}] {record.getMessage()}{RST}"
level = 0 if record.levelno >= logging.INFO else 1
self.mgmt.event(msg, level=level)
except Exception:
pass
def setup_logging(verbose, log_file=None):
"""Configure the logger. DEBUG for verbose, WARNING otherwise.
Always logs to stderr. If log_file is set, also logs to that file.
"""
level = logging.DEBUG if verbose else logging.WARNING
fmt = logging.Formatter("[ml_proxy] %(asctime)s.%(msecs)03d %(levelname)s %(message)s",
datefmt="%H:%M:%S")
logger.setLevel(level)
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setFormatter(fmt)
logger.addHandler(stderr_handler)
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(fmt)
logger.addHandler(file_handler)
# ---------------------------------------------------------------------------
# Process registry: track all spawned subprocesses for cleanup
# ---------------------------------------------------------------------------
_spawned_processes = [] # list of subprocess.Popen objects
_remote_pids = [] # list of (host, pid_str) for remote processes
_spawned_lock = threading.Lock()
_cleanup_done = False
def register_process(proc):
"""Register a subprocess for cleanup on exit."""
with _spawned_lock:
_spawned_processes.append(proc)
def register_remote_pid(host, pid):
"""Register a remote PID for cleanup on exit."""
with _spawned_lock:
_remote_pids.append((host, str(pid)))
logger.debug(f"Registered remote PID {pid} on {host}")
def setsid_wrap(cmd):
"""Wrap a shell command with setsid --wait so the inner process
becomes a session leader (PID == PGID), enabling process-group kill."""
return f"setsid --wait bash -c {shlex.quote(cmd)}"
def cleanup_all():
"""Kill all remote processes and terminate all local subprocesses.
Remote processes are killed first (via SSH) because terminating the local
SSH client does NOT reliably kill the remote side. Safe to call multiple
times.
"""
global _cleanup_done
with _spawned_lock:
if _cleanup_done:
return
_cleanup_done = True
remote = list(_remote_pids)
procs = list(_spawned_processes)
# Kill remote processes first — group them by host for efficiency.
# Each remote command runs under setsid, so its PID == PGID.
# kill -9 -{pid} kills the entire process group, including all
# descendants (grandchildren etc.) regardless of depth.
hosts = {}
for host, pid in remote:
hosts.setdefault(host, []).append(pid)
for host, pids in hosts.items():
try:
kill_cmd = "kill -9 -- " + " ".join(f"-{p}" for p in pids) + " 2>/dev/null"
subprocess.run(
["ssh"] + ssh_control_flags() + [host, kill_cmd],
capture_output=True, timeout=5)
except Exception:
pass
# Then terminate local SSH processes, with SIGKILL escalation
for proc in procs:
try:
if proc.poll() is None:
proc.terminate()
except OSError:
pass
# Give local processes a moment to exit, then SIGKILL any survivors
time.sleep(0.5)
for proc in procs:
try:
if proc.poll() is None:
proc.kill()
except OSError:
pass
ssh_control_cleanup()
# ---------------------------------------------------------------------------
# Remote command helpers
# ---------------------------------------------------------------------------
# SSH multiplexing: first call establishes a master, subsequent calls reuse it.
_ssh_control_path = None
def ssh_control_flags():
"""Return SSH flags for connection multiplexing."""
global _ssh_control_path
if _ssh_control_path is None:
_ssh_control_path = f"/tmp/ml_proxy_ssh_{os.getpid()}_%h"
return ["-o", "ControlMaster=auto",
"-o", f"ControlPath={_ssh_control_path}",
"-o", "ControlPersist=yes"]
def ssh_control_cleanup():
"""Stop the SSH master connection."""
if _ssh_control_path:
import glob
for sock in glob.glob(_ssh_control_path.replace("%h", "*")):
subprocess.run(["ssh", "-o", f"ControlPath={sock}", "-O", "exit", "dummy"],
capture_output=True)
def ssh_forward_local(host, local_port, remote_port):
"""Dynamically add an SSH local forward via the control socket.
Maps local_port on the local machine to remote_port on the remote.
Requires an active SSH ControlMaster connection.
"""
cmd = ["ssh"] + ssh_control_flags() + [
"-O", "forward",
"-L", f"127.0.0.1:{local_port}:127.0.0.1:{remote_port}",
host,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.warning(f"SSH local forward failed (rc={result.returncode}): {result.stderr.strip()}")
return False
logger.debug(f"SSH local forward: local:{local_port} -> remote:{remote_port}")
return True
def ssh_run(host, *cmd_args, capture=True, ssh_flags=None, **kwargs):
"""Run a command on the remote host via SSH. Returns CompletedProcess or Popen.
All remote command execution goes through this function.
"""
ssh_cmd = ["ssh"] + ssh_control_flags() + (ssh_flags or []) + [host] + [" ".join(shlex.quote(str(a)) for a in cmd_args)]
if capture:
return subprocess.run(ssh_cmd, capture_output=True, text=True, **kwargs)
return subprocess.Popen(ssh_cmd, **kwargs)
def ssh_run_stdout(host, *cmd_args):
"""Run a command on the remote host, return stdout stripped."""
return ssh_run(host, *cmd_args).stdout.strip()
def query_getenv(host, isabelle_home, var):
"""Query an Isabelle environment variable on the remote via `isabelle getenv`."""
val = ssh_run_stdout(host, isabelle_home + "/bin/isabelle", "getenv", "-b", var)
logger.debug(f"getenv {var} = {val}")
return val
# ---------------------------------------------------------------------------
# YXML helpers
# ---------------------------------------------------------------------------
def yxml_text_leaves(data):
"""Extract leaf text nodes from YXML-encoded data.
YXML uses \\x05 (X) and \\x06 (Y) as delimiters instead of < and >.
Text between markup tags appears as plain bytes between X/Y sequences.
Returns a list of decoded text strings (skipping empty ones).
"""
# Split on markup: \x05\x06...\x05 is an open/close tag pair
texts = re.split(rb'\x05[\x05\x06][^\x05]*\x05', data)
return [t.decode(errors="replace") for t in texts if t.strip()]
# ---------------------------------------------------------------------------
# PIDE protocol helpers
# ---------------------------------------------------------------------------
def read_pide_message(sock):
"""Read one PIDE message: header line + chunks. Returns (header, chunks) or None.
Wire format:
"len1,len2,...\\n" <- ASCII header
<chunk1><chunk2>... <- raw bytes
"""
header = b""
while True:
b = sock.recv(1)
if not b:
return None
header += b
if b == b"\n":
break
header_line = header.rstrip(b"\n")
try:
sizes = [int(s) for s in header_line.decode().split(",")]
except (ValueError, UnicodeDecodeError):
return None
chunks = []
for size in sizes:
data = b""
while len(data) < size:
part = sock.recv(size - len(data))
if not part:
return None
data += part
chunks.append(data)
return (header_line, chunks)
def write_pide_message(sock, chunks):
"""Write a PIDE message with recomputed header."""
header = ",".join(str(len(c)) for c in chunks) + "\n"
sock.sendall(header.encode())
for chunk in chunks:
sock.sendall(chunk)
def inject_proxy_message(sock, function, props=None, body=b""):
"""Inject a synthetic PIDE protocol message into the ML→Scala stream.
Args:
sock: The Scala-side socket.
function: Protocol function name (e.g. "proxy_log", "proxy_status").
props: Optional dict of additional properties (beyond "function").
body: Optional body bytes.
"""
prop_chunks = [f"function={function}".encode()]
for k, v in (props or {}).items():
prop_chunks.append(f"{k}={v}".encode())
chunks = [b"protocol", str(len(prop_chunks)).encode()] + prop_chunks
if body:
chunks.append(body if isinstance(body, bytes) else body.encode())
write_pide_message(sock, chunks)
def rewrite_bash_process_in_chunk(chunk, remote_bash_addr, remote_bash_pw):
"""Rewrite bash_process_address and password in a YXML chunk.
Matches the YXML-encoded option fields by regex and replaces the values.
Returns (new_chunk, was_modified).
"""
modified = False
if remote_bash_addr:
m = re.search(
rb"bash_process_address([\x05\x06:]+)string([\x05\x06:]+)(127\.0\.0\.1:\d+)",
chunk)
if m:
old_addr = m.group(3)
new_addr = remote_bash_addr.encode()
chunk = chunk.replace(old_addr, new_addr)
logger.debug(f"Rewrote bash_process_address: {old_addr.decode()} -> {remote_bash_addr}")
modified = True
if remote_bash_pw:
m = re.search(
rb"(bash_process_password[\x05\x06:]+string[\x05\x06:]+)"
rb"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",
chunk)
if m:
chunk = chunk.replace(m.group(2), remote_bash_pw.encode())
modified = True
return chunk, modified
def rewrite_bash_process_options(chunks, remote_bash_addr, remote_bash_pw):
"""Rewrite bash_process fields in a Prover.options message.
Returns (new_chunks, was_modified).
"""
if not chunks or chunks[0] != b"Prover.options":
return chunks, False
modified = False
new_chunks = [chunks[0]]
for chunk in chunks[1:]:
chunk, m = rewrite_bash_process_in_chunk(chunk, remote_bash_addr, remote_bash_pw)
modified = modified or m
new_chunks.append(chunk)
return new_chunks, modified
# ---------------------------------------------------------------------------
# PIDE proxy: sits between Scala and ML, intercepts Prover.options
# ---------------------------------------------------------------------------
def rewrite_build_session_paths(chunks, path_rewrites,
remote_bash_addr, remote_bash_pw):
"""Rewrite local paths and bash_process options in a build_session command.
chunks: [b"build_session", resources_yxml, args_yxml].
- resources_yxml: session_directories with local paths → rewritten via path_rewrites.
- args_yxml: options including bash_process_address/password → rewritten to remote.
Returns (new_chunks, was_modified).
"""
if not chunks or chunks[0] != b"build_session":
return chunks, False
modified = False
new_chunks = [chunks[0]]
for i, chunk in enumerate(chunks[1:], 1):
new_chunk = forward_rewrite(chunk, path_rewrites, label=f"build_session[{i}]")
if new_chunk != chunk:
modified = True
chunk = new_chunk
# Rewrite bash_process fields
chunk, m = rewrite_bash_process_in_chunk(chunk, remote_bash_addr, remote_bash_pw)
modified = modified or m
new_chunks.append(chunk)
if modified:
logger.debug("Rewrote build_session protocol command")
return new_chunks, modified
def _start_remote_stats_monitor(host, pid, stats_dir, target_isabelle_home,
target_ml_home, scala_sock, scala_write_lock):
"""Start a remote poly process to monitor ML stats, inject as proxy_ml_stats."""
def monitor_thread():
try:
inner_cmd = (
f"echo $$; exec env "
f"POLYSTATSDIR={shlex.quote(stats_dir)} "
f"{shlex.quote(target_ml_home + '/poly')} -q "
f"--use {shlex.quote(target_isabelle_home + '/src/Pure/ML/ml_statistics.ML')} "
f"--eval 'ML_Statistics.monitor {pid} 0.5'"
)
cmd = setsid_wrap(inner_cmd)
logger.debug(f"Stats monitor wrapped cmd: {cmd[:300]}")
proc = subprocess.Popen(
["ssh"] + ssh_control_flags() + [host, cmd],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
stdin=subprocess.DEVNULL)
register_process(proc)
# First line is the session leader PID (= PGID)
first_line = proc.stdout.readline().decode().strip()
if first_line.isdigit():
register_remote_pid(host, first_line)
while True:
line = proc.stdout.readline()
if not line:
break
line = line.strip()
if line:
try:
with scala_write_lock:
inject_proxy_message(scala_sock, "proxy_ml_stats",
body=line)
except (ConnectionError, OSError):
break
except Exception as e:
logger.debug(f"Remote stats monitor error: {e}")
t = threading.Thread(target=monitor_thread, daemon=True)
t.start()
def pide_proxy(server_sock, scala_port, scala_password,
remote_bash_addr, remote_bash_pw, local_isabelle_home,
path_rewrites=None, remote_host=None,
stats_rewrite=None, target_isabelle_home=None,
target_ml_home=None, mgmt=None):
"""PIDE protocol proxy.
ML (remote, via SSH tunnel)
│
▼
proxy_port (this proxy listens here)
│ intercepts Prover.options
▼
scala_port (Scala's System_Channel)
"""
# Reverse rewrites: remote→local (for ML→Scala path translation).
# Built from the same rewrite table used Scala→ML, just swapped.
path_rewrites = path_rewrites or []
# Accept ML's connection
logger.debug(f"PIDE proxy listening on {server_sock.getsockname()}")
ml_sock, ml_addr = server_sock.accept()
server_sock.close()
logger.debug(f"ML connected from {ml_addr}")
if mgmt:
mgmt.event(f"{GREEN}ML connected{RST} from {ml_addr}", 1)
# Read ML's password line
ml_pw = b""
while True:
b = ml_sock.recv(1)
if not b or b == b"\n":
break
ml_pw += b
# Connect to Scala's System_Channel, forward the password
scala_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scala_sock.connect(("127.0.0.1", scala_port))
scala_sock.sendall(ml_pw + b"\n")
logger.debug(f"Connected to Scala on 127.0.0.1:{scala_port}")
# --- Bidirectional forwarding ---
# Lock for writes to scala_sock (shared by ML forwarder and heartbeat)
scala_write_lock = threading.Lock()
def forward_scala_to_ml():
"""Parse Scala→ML messages, intercept Prover.options and build_session."""
try:
while True:
msg = read_pide_message(scala_sock)
if msg is None:
logger.debug("Scala disconnected")
try: ml_sock.shutdown(socket.SHUT_WR)
except OSError: pass
break
header_line, chunks = msg
cmd = chunks[0] if chunks else b""
# Intercept Prover.options: rewrite bash_process_address/password
if cmd == b"Prover.options":
new_chunks, modified = rewrite_bash_process_options(
chunks, remote_bash_addr, remote_bash_pw)
if modified:
if mgmt:
mgmt.event(f"{YELLOW}→ML{RST} Prover.options: rewrote bash_process", 1)
write_pide_message(ml_sock, new_chunks)
continue
# Intercept build_session: rewrite session_directories paths
# and bash_process_address/password
if cmd == b"build_session" and path_rewrites:
new_chunks, modified = rewrite_build_session_paths(
chunks, path_rewrites,
remote_bash_addr, remote_bash_pw)
if modified:
if mgmt:
mgmt.event(f"{YELLOW}→ML{RST} build_session: rewrote paths", 1)
write_pide_message(ml_sock, new_chunks)
continue
# Forward unmodified (preserve original header for efficiency)
n = len(header_line) + 1 + sum(len(c) for c in chunks)
ml_sock.sendall(header_line + b"\n")
for chunk in chunks:
ml_sock.sendall(chunk)
count_bytes(n)
if mgmt:
mgmt.event(f"{CYAN}→ML{RST} {cmd.decode(errors='replace')} ({n}B)", 2)
except (ConnectionError, OSError) as e:
logger.debug(f"Scala->ML error: {e}")
def forward_ml_to_scala():
"""Forward ML→Scala messages, downgrading file-not-found errors to warnings.
ML→Scala message format:
chunk[0] = kind ("error", "writeln", "status", ...)
chunk[1] = props_length (number of property chunks)
chunk[2..2+N-1] = property chunks
chunk[2+N..] = body chunks (YXML-encoded text)
When kind is "error" and the body contains "No such file" with a path
under the local ISABELLE_HOME, we change kind to "warning". This
suppresses red error markup for remote file-not-found errors (e.g.
\\<^file> annotations) while preserving the message as a warning.
"""
local_home_bytes = local_isabelle_home.encode() if local_isabelle_home else b""
rewrite_counts = {} # label -> count, for summarizing at exit
try:
while True:
msg = read_pide_message(ml_sock)
if msg is None:
logger.debug("ML disconnected")
try: scala_sock.shutdown(socket.SHUT_WR)
except OSError: pass
break
header_line, chunks = msg
kind = chunks[0] if chunks else b""
# Downgrade file-not-found errors to warnings with clearer message
if (kind == b"error" and
any(b"No such file" in c for c in chunks[2:])):
error_text = b" ".join(chunks[2:])
file_match = (re.search(rb'No such file: "([^"]*)"', error_text) or
re.search(rb'No such file:\s*(.+)', error_text))
if file_match:
raw = file_match.group(1)
# Strip YXML markup
missing = re.sub(rb'[\x05\x06][^\x05\x06]*', b'', raw).decode(errors="replace").strip()
else:
missing = "?"
logger.debug("File-not-found error chunks:\n" + "\n".join(
f" chunk[{i}]: {c[:300]!r}" for i, c in enumerate(chunks)))
new_prefix = b"Prover cannot verify existence of file: "
for j in range(2, len(chunks)):
chunks[j] = chunks[j].replace(b"No such file: ", new_prefix)
chunks[0] = b"warning"
logger.info(f"Prover cannot verify existence of file: {missing}")
if mgmt:
mgmt.event(f"{YELLOW}←Scala{RST} error→warning: {missing}", 1)
with scala_write_lock:
write_pide_message(scala_sock, chunks)
continue
# Drop "failed" status on text commands
if (kind == b"status" and
any(b"label=command.text" == c for c in chunks) and
any(b"failed" in c for c in chunks)):
logger.debug("Dropped text command failed status")
if mgmt:
mgmt.event(f"{YELLOW}←Scala{RST} dropped text failed status", 1)
continue
# Suppress ML_statistics and start remote stats monitoring instead
if (kind == b"protocol" and stats_rewrite and
any(b"function=ML_statistics" == c for c in chunks)):
stats_pid = None
for c in chunks:
if c.startswith(b"pid="):
stats_pid = c[4:].decode()
remote_stats_dir, local_stats_dir = stats_rewrite
if stats_pid:
logger.debug(f"Suppressed ML_statistics, starting remote monitor "
f"(pid={stats_pid}, dir={remote_stats_dir})")
if mgmt:
mgmt.event(f"{YELLOW}←Scala{RST} ML_statistics: started remote monitor (pid={stats_pid})", 1)
_start_remote_stats_monitor(
remote_host, stats_pid, remote_stats_dir,
target_isabelle_home, target_ml_home,
scala_sock, scala_write_lock)
continue
# Intercept IR_Repl.port: set up SSH local forward so I/R
# is reachable locally, then rewrite the port in the message.
if (kind == b"protocol" and len(chunks) > 3 and
chunks[2] == b"function=IR_Repl.port"):
m = re.match(rb"port=(\d+)$", chunks[3])
if m:
remote_port = int(m.group(1))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 0))
local_port = s.getsockname()[1]
if ssh_forward_local(remote_host, local_port, remote_port):
logger.info(f"I/R tunnel (PIDE): local:{local_port} -> remote:{remote_port}")
if mgmt:
mgmt.tunnels["I/R"] = f"local:{local_port} → remote:{remote_port}"
mgmt.event(f"{GREEN}I/R tunnel{RST}: local:{local_port} → remote:{remote_port}", 0)
chunks[3] = f"port={local_port}".encode()
else:
logger.warning("I/R tunnel (PIDE) failed")
if mgmt:
mgmt.event(f"{RED}I/R tunnel failed{RST}", 0)
with scala_write_lock:
write_pide_message(scala_sock, chunks)
continue
# Reverse-rewrite loading_theory paths (remote→local)
if (kind == b"protocol" and path_rewrites and
any(b"function=loading_theory" in c for c in chunks)):
chunks = [backward_rewrite(c, path_rewrites, label="loading_theory",
quiet=True)
for c in chunks]
rewrite_counts["loading_theory"] = rewrite_counts.get("loading_theory", 0) + 1
if mgmt:
theory = "?"
for c in chunks:
if c.startswith(b"name="):
theory = c[5:].decode(errors="replace")
break
mgmt.event(f"{YELLOW}←Scala{RST} loading_theory: {theory}", 1)
with scala_write_lock:
write_pide_message(scala_sock, chunks)
count_bytes(sum(len(c) for c in chunks))
continue
# Reverse-rewrite command_timing paths (remote→local)
if (kind == b"protocol" and path_rewrites and
any(c == b"function=command_timing" for c in chunks)):
chunks = [backward_rewrite(c, path_rewrites, label="command_timing",
quiet=True)
for c in chunks]
rewrite_counts["command_timing"] = rewrite_counts.get("command_timing", 0) + 1
with scala_write_lock:
write_pide_message(scala_sock, chunks)
count_bytes(sum(len(c) for c in chunks))
continue
# Forward unmodified
n = len(header_line) + 1 + sum(len(c) for c in chunks)
with scala_write_lock:
scala_sock.sendall(header_line + b"\n")
for chunk in chunks:
scala_sock.sendall(chunk)
count_bytes(n)
if mgmt:
mgmt.event(f"{GREEN}←Scala{RST} {kind.decode(errors='replace')} ({n}B)", 2)
except (ConnectionError, OSError) as e:
logger.debug(f"ML->Scala error: {e}")
finally:
for label, count in rewrite_counts.items():
logger.debug(f"Rewrote {count} {label} messages")
# Byte counter for throughput reporting (updated by both forwarding threads)
byte_counter = [0] # mutable via list; protected by GIL for atomic reads
byte_counter_lock = threading.Lock()
def count_bytes(n):
with byte_counter_lock:
byte_counter[0] += n
if mgmt:
mgmt.bytes_transferred[0] += n
def proxy_heartbeat():
"""Write periodic proxy stats to ISABELLE_TMP_PREFIX/proxy-stats-{host}."""
host_label = remote_host or "unknown"
interval = 0.5
# Use ISABELLE_TMP_PREFIX (parent of ISABELLE_TMP), accessible from jEdit
stats_dir = os.environ.get("ISABELLE_TMP_PREFIX", "")
if not stats_dir:
# Fallback: derive from ISABELLE_TMP (its parent)
isabelle_tmp = os.environ.get("ISABELLE_TMP", "")
if isabelle_tmp:
stats_dir = os.path.dirname(isabelle_tmp)
if not stats_dir:
logger.warning("No ISABELLE_TMP_PREFIX or ISABELLE_TMP, proxy stats disabled")
return
# Use hostname/IP only (strip user@ prefix)
bare_host = host_label.split("@")[-1] if "@" in host_label else host_label
stats_path = os.path.join(stats_dir, f"proxy-stats-{bare_host}")
tmp_path = stats_path + ".tmp"
try:
with scala_write_lock:
inject_proxy_message(scala_sock, "proxy_log",
body=f"Proxy connected to {host_label}")
with open(tmp_path, "w") as f:
f.write(f"host={host_label}\nmbps=0.0\n")
os.replace(tmp_path, stats_path)
while True:
time.sleep(interval)
with byte_counter_lock:
b = byte_counter[0]
byte_counter[0] = 0
mbps = b / interval / (1024 * 1024)
with open(tmp_path, "w") as f:
f.write(f"host={host_label}\nmbps={mbps:.1f}\n")
os.replace(tmp_path, stats_path)
except (ConnectionError, OSError):
pass
finally:
for p in (stats_path, tmp_path):
try:
os.unlink(p)
except OSError:
pass
t1 = threading.Thread(target=forward_scala_to_ml, daemon=True)
t2 = threading.Thread(target=forward_ml_to_scala, daemon=True)
t3 = threading.Thread(target=proxy_heartbeat, daemon=True)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
ml_sock.close()
scala_sock.close()
logger.debug("PIDE proxy stopped")
# ---------------------------------------------------------------------------
# Path rewriting
# ---------------------------------------------------------------------------
def forward_rewrite(data, rewrites, label="", quiet=False):
"""Apply rewrites (old→new) to str or bytes, logging changes."""
result = data
for old, new in rewrites:
result = result.replace(old, new)
if result != data and not quiet and logger.isEnabledFor(logging.DEBUG):
if isinstance(data, bytes):
logger.debug(f" forward_rewrite [{label}]: (modified, {len(data)} -> {len(result)} bytes)")
else:
logger.debug(f" forward_rewrite [{label}]: {data[:200]} -> {result[:200]}")
return result
def backward_rewrite(data, rewrites, label="", quiet=False):
"""Apply rewrites in reverse (new→old) to str or bytes, logging changes."""
result = data
for old, new in rewrites:
result = result.replace(new, old)
if result != data and not quiet and logger.isEnabledFor(logging.DEBUG):
if isinstance(data, bytes):
logger.debug(f" backward_rewrite [{label}]: (modified, {len(data)} -> {len(result)} bytes)")
else:
logger.debug(f" backward_rewrite [{label}]: {data[:200]} -> {result[:200]}")
return result
def rewrite_argv(poly_argv, rewrites):
"""Rewrite paths in the poly command line using a list of (old, new) pairs."""
return [forward_rewrite(arg, rewrites, label=f"arg[{i}]")
for i, arg in enumerate(poly_argv)]
# ---------------------------------------------------------------------------
# ROOT file helpers
# ---------------------------------------------------------------------------
def parse_root_sessions(root_path):
"""Extract imported session names from the 'sessions' block of a ROOT file."""
sessions = []
try:
text = open(root_path).read()
except OSError:
return sessions
# Find the 'sessions' keyword and collect names until the next keyword
in_sessions = False
for line in text.splitlines():
stripped = line.strip()
# ROOT keywords that end a sessions block
if stripped and stripped.split()[0] in (
"theories", "directories", "document_theories",
"document_files", "export_files", "export_classpath",
):
in_sessions = False
if in_sessions and stripped:
# Session name: bare or quoted
name = stripped.strip('"')
if name:
sessions.append(name)
if stripped.startswith("sessions"):
in_sessions = True
# Handle inline: "sessions Foo Bar"
rest = stripped[len("sessions"):].strip()
for tok in rest.split():
sessions.append(tok.strip('"'))
return sessions
def find_session_dir(session_name, search_root):
"""Find the source directory of a session by searching for ROOT files
under search_root that declare 'session <name>'."""
for dirpath, _dirnames, filenames in os.walk(search_root):
if "ROOT" in filenames:
root_path = os.path.join(dirpath, "ROOT")
try:
text = open(root_path).read()
except OSError:
continue
for line in text.splitlines():
# Match: session Name = ... or session "Name" = ...
line = line.strip()
if line.startswith("session"):
parts = line.split()
if len(parts) >= 2:
declared = parts[1].strip('"')
if declared == session_name:
return dirpath
return None
# ---------------------------------------------------------------------------
# Options file helpers
# ---------------------------------------------------------------------------
def extract_bash_port(opts_data):
"""Extract the bash_process_address port from options data."""
match = re.search(
rb"bash_process_address[\x05\x06:]+string[\x05\x06:]+127\.0\.0\.1:(\d+)", opts_data)
return int(match.group(1)) if match else None
def extract_channel_port(opts_file):
"""Extract the system_channel_address port from the ISABELLE_PROCESS_OPTIONS file."""
data = open(opts_file, "rb").read()
match = re.search(rb"system_channel_address[\x05\x06:]+string[\x05\x06:]+(127\.0\.0\.1:(\d+))", data)
return int(match.group(2)) if match else None
def make_proxy_server():
"""Create a TCP server socket on a free port for the PIDE proxy."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 0))
server.listen(1)
return server
# ---------------------------------------------------------------------------
# Remote Bash.Server
# ---------------------------------------------------------------------------
def start_remote_bash_server(host, target_isabelle_home):
"""Start a Bash.Server on the remote via `isabelle scala -e`.
A dummy `tput` is placed in PATH to work around Scala 3's `tput cols`
crash in non-interactive SSH. Slow on first invocation (~15-30s).
Returns (address, password, Popen).
"""
ssh_run(host, "sh", "-c",
"mkdir -p /tmp/isabelle-proxy-bin && "
"printf '#!/bin/sh\\necho 80\\n' > /tmp/isabelle-proxy-bin/tput && "
"chmod +x /tmp/isabelle-proxy-bin/tput")
logger.debug("Starting remote Bash.Server...")
bash_server_inner = (
f"echo $$; exec env PATH=/tmp/isabelle-proxy-bin:$PATH "
f"{shlex.quote(target_isabelle_home + '/bin/isabelle')} scala -e "
f"'{{ val server = isabelle.Bash.Server.start(debugging = true); "
f"println(\"BASH_SERVER_ADDRESS=\" + server.address); "
f"println(\"BASH_SERVER_PASSWORD=\" + server.password); "
f"Thread.sleep(Long.MaxValue) }}'"
)
bash_server_cmd = setsid_wrap(bash_server_inner)
logger.debug(f"Bash.Server wrapped cmd: {bash_server_cmd[:300]}")
proc = subprocess.Popen(
["ssh"] + ssh_control_flags() + [host, bash_server_cmd],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
register_process(proc)
addr = None
pw = None
remote_pid = None
deadline = time.time() + 60
while time.time() < deadline:
line = proc.stdout.readline().decode().strip()
if remote_pid is None and line.isdigit():
remote_pid = line