Repository navigation
Expand file tree
/
Copy pathtest_venv_worker.py
More file actions
2780 lines (2450 loc) · 127 KB
/
Copy pathtest_venv_worker.py
File metadata and controls
2780 lines (2450 loc) · 127 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
"""Tests for venv_worker (paths, warm worker, run_code) via PythonWorkerManager + worker_harness."""
from __future__ import annotations
import io
import os
import pickle
import shlex
import stat
import struct
import subprocess
import sys
import signal
import threading
import time
from collections.abc import Generator
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from plugin.framework.constants import WORKER_POOL_DEFAULT, WORKER_POOL_EMBEDDINGS
from plugin.framework.send_cancellation import SendCancellation
from plugin.scripting.config_limits import WARM_WORKER_TIMEOUT_SEC
from plugin.framework.ipc import DEFAULT_MAX_PAYLOAD_BYTES, FRAME_HEARTBEAT, FRAME_RESULT, IpcFrameError, IpcPartialFrameTimeout, pack_pickle_frame, read_pickle_frame
import plugin.scripting.venv_worker as venv_worker_module
from plugin.framework.subprocess_env import scrub_subprocess_env
from plugin.scripting.venv_worker import (
ExecRequest,
FailedAfterStart,
NotStarted,
PythonWorkerManager,
RetryWithNewLease,
Terminal,
_TurnState,
_classify_read_failure,
_resolve_worker_python,
_worker_error_message,
get_worker_manager,
parse_worker_stdout_frame,
reset_python_session,
run_code_in_user_venv,
shutdown_venv_workers_for_tests,
warm_venv_worker,
)
from plugin.framework.child_runtime import Deadline
from plugin.framework.warm_child import supervisor
from tests.scripting.sandbox_support import sandbox_run
from plugin.tests.testing_utils import cancelled_scope, pid_is_alive
def _mgr_proc(mgr: PythonWorkerManager) -> Any:
"""Test helper: Popen for the live warm child, if any."""
warm = mgr._warm
if warm is None:
return None
child = warm.child
if child is None:
return None
return child.managed.popen
def _mock_mgr(*, stdout_bytes: bytes = b"") -> tuple[PythonWorkerManager, MagicMock]:
"""Create a PythonWorkerManager wired to a live mock Popen with BytesIO streams."""
mgr = PythonWorkerManager(sys.executable, {})
proc = MagicMock()
proc.poll.return_value = None
proc.stdin = io.BytesIO()
proc.stdout = io.BytesIO(stdout_bytes)
_install_mock_proc(mgr, proc)
return mgr, proc
def _install_mock_proc(mgr: PythonWorkerManager, proc: Any) -> None:
"""Attach a mock Popen to *mgr* for unit tests that stub IPC."""
from plugin.framework.warm_child import ChildSpec, WarmChild
env = {k: v for k, v in os.environ.items() if isinstance(v, str)}
env.setdefault("PATH", "/usr/bin")
spec = ChildSpec(
name="test-venv",
argv=[sys.executable, "-c", "pass"],
env=env,
log_start_failure=False,
)
warm = WarmChild(spec)
managed = MagicMock()
managed.popen = proc
child = MagicMock()
child.managed = managed
child.was_signaled.return_value = False
io_owner_holder: list[int | None] = [None]
def begin_io() -> None:
io_owner_holder[0] = threading.get_ident()
def end_io() -> bool:
io_owner_holder[0] = None
return False
child.begin_io = begin_io
child.end_io = end_io
warm.child = child
warm._generation = 0
warm._fake_io_owner: int | None = None
def ensure_live(_deadline: object) -> None:
return None
warm._ensure_live = ensure_live # type: ignore[method-assign]
poll_fn = getattr(proc, "poll", None)
warm.is_alive = lambda: poll_fn() is None if callable(poll_fn) else True
warm.io_owner = lambda: warm._fake_io_owner if warm._fake_io_owner is not None else io_owner_holder[0]
warm.diagnostic_tail = lambda: ""
mgr._warm = warm
mgr._primed = True
mgr._primed_generation = 0
def _hold_pipe_in_thread(mgr: PythonWorkerManager) -> tuple[threading.Thread, threading.Event]:
warm = mgr._warm
assert warm is not None
held = threading.Event()
release = threading.Event()
def _run() -> None:
with warm.lease(Deadline(30), wait=0) as leased:
assert not isinstance(leased, dict)
held.set()
assert release.wait(timeout=5)
thread = threading.Thread(target=_run)
thread.start()
assert held.wait(timeout=2)
return thread, release
def _session_ok(mgr: PythonWorkerManager) -> bool:
from plugin.framework.warm_child import Lease
with mgr._io_session() as session:
return isinstance(session, Lease)
def _lease_from_proc(mgr: PythonWorkerManager, proc: Any, *, generation: int=0) -> Any:
from plugin.framework.warm_child import Lease
warm = mgr._warm if mgr._warm is not None else MagicMock()
return Lease(stdin=proc.stdin, stdout=proc.stdout, pid=int(getattr(proc, 'pid', 1) or 1), generation=generation, warm=warm)
def _mgr_stderr_tail(mgr: PythonWorkerManager) -> Any:
warm = mgr._warm
if warm is None:
return None
child = warm.child
if child is None:
return None
return child.managed.stderr_tail
def _run_ipc_with_mock(mgr: PythonWorkerManager, req: ExecRequest, proc: Any) -> dict[str, Any]:
import contextlib
counter = {'n': 0}
@contextlib.contextmanager
def fake_io(*args: object, **kwargs: object):
del args, kwargs
counter['n'] += 1
yield _lease_from_proc(mgr, proc, generation=counter['n'] - 1)
with patch.object(mgr, '_io_session', fake_io):
return mgr._run_in_session(lambda leased: mgr._execute_ipc_unlocked(req, leased=leased), timeout_sec=req.timeout_sec or 1)
def _guard_ipc_while_lock_wait(req: ExecRequest, *, leased: Any) -> dict[str, Any]:
if req.code == 'result = None' and not req.action:
return {'status': 'ok', 'result': None}
raise AssertionError('IPC must not run while waiting on pipe lock')
@pytest.fixture(scope='module', autouse=True)
def _shutdown_workers_after_module():
"""Ensure no leftover worker processes after this file finishes."""
yield
shutdown_venv_workers_for_tests()
def _skip_harness_ready_frame(stdout: io.BytesIO) -> None:
"""Consume the warm-child ready frame worker_harness.main emits before the request loop."""
stdout.seek(0)
ready = read_pickle_frame(stdout, require_dict=True)
assert isinstance(ready, dict)
assert ready.get('status') == 'ready'
assert 'pid' in ready
_STUB_WORKER_EMIT_READY = '\ndef _emit_ready():\n import os as _os\n import pickle as _pickle\n import struct as _struct\n _frame = _pickle.dumps({"status": "ready", "pid": _os.getpid()}, protocol=5)\n sys.stdout.buffer.write(_struct.pack("!I", len(_frame)) + _frame)\n sys.stdout.buffer.flush()\n\n_emit_ready()\n'
@pytest.fixture(autouse=True)
def _protect_worker_harness_os_exit(monkeypatch: pytest.MonkeyPatch) -> Any:
import plugin.scripting.venv.worker_harness as harness
monkeypatch.setattr(harness.os, '_exit', lambda code: pytest.fail(f'Unexpected os._exit({code}) in harness test'))
try:
import plugin.contrib.smolagents.local_python_executor as lpe
lpe.discard_thread_pool_timeout()
except ImportError:
pass
try:
yield
finally:
try:
import plugin.contrib.smolagents.local_python_executor as lpe
lpe.discard_thread_pool_timeout()
except ImportError:
pass
def test_worker_error_message_strips_command_path():
long_cmd = ['/very/long/path/to/python', '/very/long/path/to/worker_harness.py']
exc = subprocess.TimeoutExpired(cmd=long_cmd, timeout=3)
msg = _worker_error_message(exc)
assert msg == 'Python worker failed: timed out after 3 seconds'
assert 'Command' not in msg
assert '/very/long' not in msg
def test_run_code_in_user_venv_passes_cancel():
"""run_code_in_user_venv must pass cancel to the manager's execute method."""
scope = SendCancellation()
with patch('plugin.scripting.venv_worker.get_worker_manager') as mock_mgr_ctx, patch(
'plugin.scripting.venv_worker.get_config', return_value=''
):
mock_mgr = MagicMock()
mock_mgr.execute.return_value = {'status': 'ok'}
mock_mgr_ctx.return_value = (mock_mgr, None)
run_code_in_user_venv(code='result = 1', cancel=scope)
mock_mgr.execute.assert_called_once()
assert mock_mgr.execute.call_args.args[0].cancel is scope
def test_sentence_transformers_import_not_deep_wrapped():
"""Heavy embedder packages must bypass get_safe_module scanning (hangs on dir()/getattr)."""
st = pytest.importorskip('sentence_transformers')
from plugin.contrib.smolagents.local_python_executor import get_safe_module
assert get_safe_module(st, []) is st
r = sandbox_run('from sentence_transformers import SentenceTransformer\nresult = str(SentenceTransformer)', None)
assert r['status'] == 'ok'
assert 'SentenceTransformer' in r['result']
def test_duckdb_import_not_deep_wrapped():
"""DuckDB (C-backed analytics lib) must bypass get_safe_module like other heavy packages."""
duck = pytest.importorskip('duckdb')
from plugin.contrib.smolagents.local_python_executor import get_safe_module
assert get_safe_module(duck, []) is duck
r = sandbox_run("import duckdb\ncon = duckdb.connect()\nresult = con.execute('SELECT 42 AS x').df().to_dict()", None)
assert r['status'] == 'ok'
assert r['result'] == {'x': {'0': 42}}
def test_harness_main_loop_integration():
"""Harness reads and writes Pickle (subprocess smoke)."""
harness = __import__('plugin.scripting.venv.worker_harness', fromlist=['main'])
proc_pickle = subprocess.Popen([sys.executable, harness.__file__], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=False, bufsize=0)
req_dict = {'id': 't2', 'code': 'result = 2 ** 10', 'timeout_sec': 10}
proc_pickle.stdin.write(pack_pickle_frame(req_dict))
proc_pickle.stdin.flush()
ready = read_pickle_frame(proc_pickle.stdout, require_dict=True)
assert ready is not None and ready.get('status') == 'ready'
started = read_pickle_frame(proc_pickle.stdout, require_dict=True)
assert started is not None
assert started['type'] == 'exec_started'
assert started['id'] == 't2'
resp_dict = read_pickle_frame(proc_pickle.stdout, require_dict=True)
assert resp_dict is not None
assert resp_dict['id'] == 't2'
assert resp_dict['status'] == 'ok'
assert resp_dict['result'] == 1024
proc_pickle.stdin.close()
proc_pickle.wait(timeout=5)
def test_manager_real_spawn_drains_stderr_flood(tmp_path, monkeypatch):
"""The manager's actual Popen path must drain stderr before waiting for a response."""
child = tmp_path / 'stderr_flood_worker.py'
child.write_text(('\nimport pickle\nimport struct\nimport sys\n\nsys.stderr.buffer.write(b"x" * (128 * 1024))\nsys.stderr.buffer.flush()\n\n' + _STUB_WORKER_EMIT_READY + '\nwhile True:\n header = sys.stdin.buffer.read(4)\n if len(header) < 4:\n break\n size = struct.unpack("!I", header)[0]\n payload = sys.stdin.buffer.read(size)\n if len(payload) < size:\n break\n request = pickle.loads(payload)\n response = {"id": request.get("id"), "status": "ok", "result": 42, "stdout": ""}\n encoded = pickle.dumps(response, protocol=5)\n sys.stdout.buffer.write(struct.pack("!I", len(encoded)) + encoded)\n sys.stdout.buffer.flush()\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
drain = None
try:
result = mgr.execute(ExecRequest(code='result = 42', timeout_sec=5))
drain = _mgr_stderr_tail(mgr)
assert result['status'] == 'ok'
assert result['result'] == 42
assert drain is not None
deadline = time.monotonic() + 2.0
captured = ''
while time.monotonic() < deadline:
captured = drain.text()
if 'x' * 1024 in captured:
break
time.sleep(0.01)
assert 'x' * 1024 in captured
finally:
mgr._terminate_worker()
assert drain is not None
assert not drain.is_alive
def test_worker_crash_mid_request_retries_and_recovers(tmp_path, monkeypatch):
"""A child that dies once mid-IPC must be recycled; the retried turn should succeed."""
crash_once = tmp_path / 'crash_once'
crash_once.write_text('1', encoding='utf-8')
child = tmp_path / 'crash_once_worker.py'
child.write_text((f'\nimport os\nimport pickle\nimport struct\nimport sys\n\nflag = {str(crash_once)!r}\n\n' + _STUB_WORKER_EMIT_READY + '\nwhile True:\n header = sys.stdin.buffer.read(4)\n if len(header) < 4:\n break\n size = struct.unpack("!I", header)[0]\n payload = sys.stdin.buffer.read(size)\n if len(payload) < size:\n break\n if os.path.exists(flag):\n os.remove(flag)\n os._exit(1)\n request = pickle.loads(payload)\n response = {"id": request.get("id"), "status": "ok", "result": 42, "stdout": ""}\n encoded = pickle.dumps(response, protocol=5)\n sys.stdout.buffer.write(struct.pack("!I", len(encoded)) + encoded)\n sys.stdout.buffer.flush()\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
mgr._ensure_warmed_unlocked = lambda leased: None
try:
result = mgr.execute(ExecRequest(code='result = 42', timeout_sec=5))
assert result['status'] == 'ok'
assert result['result'] == 42
assert _mgr_proc(mgr) is not None and _mgr_proc(mgr).poll() is None
finally:
mgr._terminate_worker()
@pytest.mark.skipif(sys.platform != "linux", reason="SIGKILL idle-death check is Linux-only")
def test_idle_worker_sigkill_recovers_on_next_execute(monkeypatch):
"""Killing an idle real worker with SIGKILL respawns a fresh worker on the next execute."""
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
try:
first = mgr.execute(ExecRequest(code='result = 0', timeout_sec=10))
assert first['status'] == 'ok'
assert first['result'] == 0
proc = _mgr_proc(mgr)
assert proc is not None
old_pid = proc.pid
os.kill(old_pid, signal.SIGKILL)
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and mgr._is_worker_alive():
time.sleep(0.05)
assert not mgr._is_worker_alive()
second = mgr.execute(ExecRequest(code='result = 1', timeout_sec=10))
assert second['status'] == 'ok'
assert second['result'] == 1
new_proc = _mgr_proc(mgr)
assert new_proc is not None
assert new_proc.pid != old_pid
finally:
mgr._terminate_worker()
def test_worker_child_dies_without_response_fails_promptly(tmp_path: Any, monkeypatch: pytest.MonkeyPatch) -> None:
"""A child that dies without writing a response returns promptly with an error and retries once."""
shutdown_venv_workers_for_tests()
counter_file = tmp_path / 'counter.txt'
child = tmp_path / 'die_worker.py'
child.write_text(('\nimport os\nimport struct\nimport sys\n\n' + _STUB_WORKER_EMIT_READY + f'\nwith open({str(counter_file)!r}, "a") as f:\n f.write("start\\n")\n f.flush()\n\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\nos._exit(0)\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
monkeypatch.setattr(venv_worker_module, 'WARM_WORKER_TIMEOUT_SEC', 8.0)
monkeypatch.setattr(venv_worker_module, 'HOST_IPC_READ_GRACE_SEC', 8.0)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
mgr._ensure_warmed_unlocked = lambda *args, **kwargs: None
t0 = time.monotonic()
try:
res = mgr.execute(ExecRequest(code='result = 1', timeout_sec=8))
elapsed = time.monotonic() - t0
assert elapsed < 4.0
assert res.get('status') == 'error'
assert res.get('code') == 'WORKER_IPC_ERROR'
assert 'without a response' in res.get('message', '')
assert counter_file.read_text(encoding='utf-8').splitlines() == ['start', 'start']
assert _mgr_proc(mgr) is None or _mgr_proc(mgr).poll() is not None
finally:
mgr._terminate_worker()
def test_worker_child_hung_zero_bytes_times_out_without_replay(tmp_path: Any, monkeypatch: pytest.MonkeyPatch) -> None:
"""A live child that hangs without writing times out within window and does not replay."""
counter_file = tmp_path / 'counter.txt'
child = tmp_path / 'hung_zero_worker.py'
child.write_text(('\nimport os\nimport struct\nimport sys\nimport time\n\n' + _STUB_WORKER_EMIT_READY + f'\nwith open({str(counter_file)!r}, "a") as f:\n f.write("start\\n")\n f.flush()\n\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\ntime.sleep(120)\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
monkeypatch.setattr(venv_worker_module, 'WARM_WORKER_TIMEOUT_SEC', 1.0)
monkeypatch.setattr(venv_worker_module, 'HOST_IPC_READ_GRACE_SEC', 0.5)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
t0 = time.monotonic()
try:
res = mgr.execute(ExecRequest(code='result = 1', timeout_sec=1))
elapsed = time.monotonic() - t0
assert 1.0 <= elapsed < 4.0
assert res.get('status') == 'error'
assert res.get('code') == 'VENV_TIMEOUT'
assert 'timed out after 1.5 seconds' in res.get('message', '')
assert counter_file.read_text(encoding='utf-8').splitlines() == ['start']
finally:
mgr._terminate_worker()
def test_worker_child_hung_partial_frame_times_out_without_replay(tmp_path: Any, monkeypatch: pytest.MonkeyPatch) -> None:
"""A live child that writes a partial frame and hangs times out without replay."""
counter_file = tmp_path / 'counter.txt'
child = tmp_path / 'hung_partial_worker.py'
child.write_text(('\nimport os\nimport struct\nimport sys\nimport time\n\n' + _STUB_WORKER_EMIT_READY + f'\nwith open({str(counter_file)!r}, "a") as f:\n f.write("start\\n")\n f.flush()\n\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\nheader = sys.stdin.buffer.read(4)\nif len(header) == 4:\n size = struct.unpack("!I", header)[0]\n sys.stdin.buffer.read(size)\nsys.stdout.buffer.write(b"\\x00\\x00")\nsys.stdout.buffer.flush()\ntime.sleep(120)\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
monkeypatch.setattr(venv_worker_module, 'WARM_WORKER_TIMEOUT_SEC', 1.0)
monkeypatch.setattr(venv_worker_module, 'HOST_IPC_READ_GRACE_SEC', 0.5)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
t0 = time.monotonic()
try:
res = mgr.execute(ExecRequest(code='result = 1', timeout_sec=1))
elapsed = time.monotonic() - t0
assert 1.0 <= elapsed < 4.0
assert res.get('status') == 'error'
assert res.get('code') == 'VENV_TIMEOUT'
assert 'mid-frame' in res.get('message', '') or 'timed out' in res.get('message', '')
assert counter_file.read_text(encoding='utf-8').splitlines() == ['start']
finally:
mgr._terminate_worker()
def test_terminate_worker_kills_grandchild(tmp_path, monkeypatch):
"""Timeout/crash cleanup must kill descendants (joblib/loky, DataLoader), not only the worker."""
child = tmp_path / 'tree_worker.py'
child.write_text(('\nimport os\nimport subprocess\nimport sys\nimport time\n\n' + _STUB_WORKER_EMIT_READY + '\ngrandchild = subprocess.Popen(\n [sys.executable, "-c", "import time; time.sleep(120)"],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n)\nsys.stderr.write(f"GRANDCHILD {grandchild.pid}\\n")\nsys.stderr.flush()\ntime.sleep(120)\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, '_HARNESS_PATH', str(child))
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
mgr = PythonWorkerManager(sys.executable, {'PATH': os.environ.get('PATH', '')})
monkeypatch.setattr(mgr, '_ensure_warmed_unlocked', lambda leased: None)
gpid = None
try:
_session_ok(mgr)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
drain = _mgr_stderr_tail(mgr)
text = drain.text() if drain is not None else ''
for line in text.splitlines():
if line.startswith('GRANDCHILD '):
gpid = int(line.split()[1])
break
if gpid is not None:
break
time.sleep(0.05)
assert gpid is not None, 'worker did not report grandchild pid'
assert pid_is_alive(gpid)
mgr._terminate_worker()
dead_deadline = time.monotonic() + 5
while time.monotonic() < dead_deadline and pid_is_alive(gpid):
time.sleep(0.05)
assert not pid_is_alive(gpid), f'grandchild pid {gpid} survived worker termination'
finally:
mgr._terminate_worker()
if gpid is not None and pid_is_alive(gpid):
try:
os.kill(gpid, 9)
except OSError:
pass
def test_blocked_stdin_write_times_out_and_releases_lock(tmp_path, monkeypatch):
"""A child that never reads stdin must not hold the warm-child pipe lock forever."""
from plugin.framework.warm_child import ChildSpec, WarmChild
child = tmp_path / 'blocked_stdin_worker.py'
child.write_text(('import sys\n' + _STUB_WORKER_EMIT_READY + 'import time\ntime.sleep(60)\n').lstrip(), encoding='utf-8')
monkeypatch.setattr(venv_worker_module, 'wrap_command_for_sandbox', lambda cmd, **_kwargs: cmd)
env = {k: v for k, v in os.environ.items() if isinstance(v, str)}
env['WRITERAGENT_IS_WORKER'] = '1'
spec = ChildSpec(
name='blocked-stdin-test',
argv=[sys.executable, str(child)],
env=env,
command_wrapper=venv_worker_module.wrap_command_for_sandbox,
)
warm = WarmChild(spec)
mgr = PythonWorkerManager.__new__(PythonWorkerManager)
mgr.exe = sys.executable
mgr._warm = warm
try:
with warm.lease(Deadline(30)) as leased:
assert not isinstance(leased, dict)
started = time.monotonic()
with pytest.raises(subprocess.TimeoutExpired):
mgr._write_packed_frame_with_timeout(leased.stdin, b'x' * (8 * 1024 * 1024), timeout_sec=0.2, label='test request')
# Callers own the kill.
mgr._terminate_worker()
assert time.monotonic() - started < 5
for t in threading.enumerate():
if t.name == 'ipc-stdin-write':
t.join(timeout=5)
assert not t.is_alive()
with warm.lease(Deadline(1), wait=0) as leased:
assert not isinstance(leased, dict)
finally:
warm.retire()
def test_execute_refuses_reentry_while_this_thread_owns_the_pipe():
mgr = PythonWorkerManager(sys.executable, {})
_install_mock_proc(mgr, MagicMock(poll=MagicMock(return_value=None), stdin=io.BytesIO(), stdout=io.BytesIO()))
assert mgr._warm is not None
mgr._warm._fake_io_owner = threading.get_ident()
result = mgr.execute(ExecRequest(code='result = 1', timeout_sec=1))
assert result['status'] == 'error'
assert result['code'] == 'WORKER_REENTRY'
assert 'called back' in result['message']
assert mgr._warm is not None
with mgr._warm.lease(Deadline(1), wait=0) as leased:
assert not isinstance(leased, dict)
def test_large_stdin_write_completes_intact():
mgr = PythonWorkerManager(sys.executable, {})
stream = io.BytesIO()
payload = b'large-payload-' * (256 * 1024)
mgr._write_packed_frame_with_timeout(stream, payload, timeout_sec=2, label='test request')
assert stream.getvalue() == payload
def test_initial_write_timeout_retries_once(monkeypatch):
mgr, proc = _mock_mgr()
monkeypatch.setattr(
"plugin.scripting.venv_worker.write_packed_frame_with_timeout",
MagicMock(side_effect=subprocess.TimeoutExpired(cmd=sys.executable, timeout=1)),
)
mgr._write_frame_with_timeout = MagicMock(wraps=mgr._write_frame_with_timeout)
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'VENV_TIMEOUT'
assert 'timed out after 1.0 seconds' in result['message']
assert mgr._write_frame_with_timeout.call_count == 2
assert mgr._terminate_worker.call_count == 2
first = mgr._write_frame_with_timeout.call_args_list[0].args[1]
second = mgr._write_frame_with_timeout.call_args_list[1].args[1]
assert first['id'] == second['id']
def test_ppt_master_write_timeout_does_not_replay(monkeypatch):
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
monkeypatch.setattr(
"plugin.scripting.venv_worker.write_packed_frame_with_timeout",
MagicMock(side_effect=subprocess.TimeoutExpired(cmd=sys.executable, timeout=1)),
)
response_payload = pickle.dumps({'type': 'llm_request', 'status': 'host_request'}, protocol=5)
mgr._read_response_bytes = MagicMock(return_value=response_payload)
mgr._terminate_worker = MagicMock()
dispatch_calls = []
def dispatch(response, *, stdin_write, on_worker_event=None, cancel=None):
del response, on_worker_event, cancel
dispatch_calls.append(True)
stdin_write(b'host response')
return True
monkeypatch.setattr('plugin.ppt_master.venv.host_rpc.dispatch_worker_response', dispatch)
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1, caller='ppt_master_venv'), proc)
assert result['status'] == 'error'
assert 'host RPC response timed out' in result['message']
assert len(dispatch_calls) == 1
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._read_response_bytes.call_count == 1
assert mgr._terminate_worker.call_count == 1
def test_tool_call_then_broken_stdout_does_not_replay(monkeypatch):
"""An intermediate frame (llm_request) that already ran must not be followed by a second copy of the script."""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
response_payload = pickle.dumps({'type': 'llm_request', 'status': 'host_request'}, protocol=5)
mgr._read_response_bytes = MagicMock(side_effect=[response_payload, RuntimeError('Worker closed stdout')])
mgr._terminate_worker = MagicMock()
def dispatch(response, *, stdin_write, on_worker_event=None, cancel=None):
del response, stdin_write, on_worker_event, cancel
return True
monkeypatch.setattr('plugin.ppt_master.venv.host_rpc.dispatch_worker_response', dispatch)
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1, caller='ppt_master_venv'), proc)
assert result['status'] == 'error'
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._terminate_worker.call_count == 1
@pytest.mark.parametrize('frame_type', ['tool_call', 'llm_request', 'worker_event'])
def test_tool_call_raise_without_exec_started_does_not_replay(monkeypatch, frame_type):
"""An intermediate frame that raises mid-dispatch must not be sent again.
may_have_run must be set before dispatch; otherwise a RuntimeError from
the handler causes the attempt loop to resend to a new child.
"""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(return_value=pickle.dumps({'type': frame_type, 'id': 't1', 'tool': 'apply_content', 'args': {}}, protocol=5))
mgr._terminate_worker = MagicMock()
def dispatch(*args, **kwargs):
del args, kwargs
raise RuntimeError('tool mutated then failed')
monkeypatch.setattr(venv_worker_module, '_maybe_dispatch_intermediate_response', dispatch)
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'WORKER_IPC_ERROR'
assert 'tool mutated then failed' in result['message']
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._terminate_worker.call_count == 1
def test_stdout_close_before_start_retries_once():
"""A death before exec_started has not run the request; recycle the child."""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(return_value=b'')
mgr._drain_stderr = MagicMock(return_value='')
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert 'without a response' in result['message']
assert mgr._write_frame_with_timeout.call_count == 2
assert mgr._terminate_worker.call_count == 2
def test_truncated_header_before_exec_started_fails_without_replay():
"""A truncated frame is stream desynchronization; do not replay."""
mgr, proc = _mock_mgr(stdout_bytes=b'\x00\x00')
mgr._write_frame_with_timeout = MagicMock()
mgr._drain_stderr = MagicMock(return_value='')
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] in ('WORKER_IPC_ERROR', 'VENV_TIMEOUT')
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._terminate_worker.call_count == 1
def test_runtime_error_before_exec_started_retries_once():
"""A RuntimeError before the child has started the script is still a failed start."""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(side_effect=RuntimeError('pipe died'))
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert 'pipe died' in result['message']
assert mgr._write_frame_with_timeout.call_count == 2
assert mgr._terminate_worker.call_count == 2
def test_runtime_error_after_exec_started_does_not_replay():
"""A RuntimeError after exec_started must not resend the script on a new child."""
mgr, proc = _mock_mgr()
captured: dict[str, dict] = {}
def _write_frame(stdin, request, **kwargs):
captured['request'] = request
mgr._write_frame_with_timeout = _write_frame
reads = {'n': 0}
def _read(stdout, timeout_sec, cancel=None):
reads['n'] += 1
request = captured['request']
if reads['n'] == 1:
return pickle.dumps({'type': 'exec_started', 'id': request['id']}, protocol=5)
raise RuntimeError('worker frame was not a dict')
mgr._read_response_bytes = _read
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'WORKER_IPC_ERROR'
assert 'not a dict' in result['message']
assert reads['n'] == 2
assert mgr._terminate_worker.call_count == 1
def test_stdout_close_after_exec_started_does_not_replay():
"""In-process side effects after exec_started must not run under the same id again."""
mgr, proc = _mock_mgr()
captured: dict[str, dict] = {}
def _write_frame(stdin, request, **kwargs):
captured['request'] = request
mgr._write_frame_with_timeout = _write_frame
reads = {'n': 0}
def _read(stdout, timeout_sec, cancel=None):
reads['n'] += 1
request = captured['request']
if reads['n'] == 1:
return pickle.dumps({'type': 'exec_started', 'id': request['id']}, protocol=5)
return b''
mgr._read_response_bytes = _read
mgr._drain_stderr = MagicMock(return_value='')
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'WORKER_IPC_ERROR'
assert 'without a response' in result['message']
assert 'request' in captured
assert reads['n'] == 2
assert mgr._terminate_worker.call_count == 1
def test_exec_started_wrong_id_is_refused_without_replay():
"""An exec_started for another request is an id mismatch: kill, no resend."""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(return_value=pickle.dumps({'type': 'exec_started', 'id': 'someone-else'}, protocol=5))
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['code'] == 'WORKER_IPC_ERROR'
assert 'id mismatch' in result['message']
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._terminate_worker.call_count == 1
def test_host_read_timeout_does_not_retry():
"""Hung user code must not be replayed; that would double the configured timeout."""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(side_effect=subprocess.TimeoutExpired(cmd=sys.executable, timeout=1))
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert 'timed out after 1 seconds' in result['message']
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._read_response_bytes.call_count == 1
assert mgr._terminate_worker.call_count == 1
def test_partial_frame_timeout_does_not_replay():
"""Windows mid-frame stall must not resend the script.
IpcPartialFrameTimeout is an OSError. Before it was mapped with the
read timeout, a partial exec_started left may_have_run false and the
outer handler ran the request again.
"""
mgr, proc = _mock_mgr()
mgr._write_frame_with_timeout = MagicMock()
mgr._read_response_bytes = MagicMock(side_effect=IpcPartialFrameTimeout('python stream desynchronized: timeout mid-frame'))
mgr._terminate_worker = MagicMock()
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'VENV_TIMEOUT'
assert 'mid-frame' in result['message']
assert mgr._write_frame_with_timeout.call_count == 1
assert mgr._read_response_bytes.call_count == 1
mgr._terminate_worker.assert_called_once()
def test_win32_partial_frame_timeout_with_stop_is_cancelled(monkeypatch: pytest.MonkeyPatch):
"""Stop during a Windows mid-frame stall is CANCELLED, not a replayed timeout."""
monkeypatch.setattr(sys, 'platform', 'win32')
mgr = PythonWorkerManager.__new__(PythonWorkerManager)
mgr.exe = 'python'
_install_mock_proc(mgr, MagicMock(poll=MagicMock(return_value=None)))
class _Stdout(io.BytesIO):
def fileno(self) -> int:
return 3
def _boom(*args: object, **kwargs: object) -> bytes:
del args, kwargs
raise IpcPartialFrameTimeout('timeout mid-frame')
from plugin.scripting import venv_worker as venv_worker_mod
ipc_module = sys.modules[venv_worker_mod.read_frame_payload.__module__]
monkeypatch.setattr(ipc_module, '_poll_pipe', _boom)
res = mgr._read_frame_bytes(_Stdout(), 1.0, cancel=cancelled_scope())
assert isinstance(res, FailedAfterStart)
assert res.kind == 'cancel'
with pytest.raises(IpcPartialFrameTimeout):
mgr._read_frame_bytes(_Stdout(), 1.0, cancel=None)
def test_manager_separate_pools_same_exe():
shutdown_venv_workers_for_tests()
env = {'PATH': '/usr/bin:/bin'}
default_mgr = PythonWorkerManager.get(sys.executable, env, pool=WORKER_POOL_DEFAULT)
embed_mgr = PythonWorkerManager.get(sys.executable, env, pool=WORKER_POOL_EMBEDDINGS)
assert default_mgr is not embed_mgr
assert default_mgr is PythonWorkerManager.get(sys.executable, env, pool=WORKER_POOL_DEFAULT)
shutdown_venv_workers_for_tests()
def test_split_grid_data_round_trip_execute_request():
"""Ingress split_grid: child receives CalcRange backed by numeric values."""
pytest.importorskip('numpy')
from plugin.calc.calc_addin_data import pack_calc_data_for_wire
from plugin.scripting.payload_codec import BINARY_MIN_CELLS, is_split_grid
from plugin.scripting.calc_range import is_calc_range_payload
from tests.scripting.payload_codec_test_support import NUMERIC_AT_THRESHOLD, sequential_grid_sum
grid = NUMERIC_AT_THRESHOLD
wire = pack_calc_data_for_wire(grid)
assert is_calc_range_payload(wire)
assert is_split_grid(wire['data'])
r = sandbox_run('result = float(np.sum(data))', wire)
assert r['status'] == 'ok'
assert r['result'] == pytest.approx(sequential_grid_sum(BINARY_MIN_CELLS))
def test_normalize_response_unpacks_split_grid():
from plugin.scripting.payload_codec import host_pack_split_grid, is_split_grid
grid = [[float(r * 10 + c) for c in range(5)] for r in range(5)]
wire = host_pack_split_grid(grid)
assert is_split_grid(wire)
mgr = PythonWorkerManager(sys.executable, {'PATH': '/usr/bin:/bin'})
out = mgr._normalize_response({'status': 'ok', 'result': wire, 'stdout': ''})
assert out['status'] == 'ok'
assert not is_split_grid(out['result'])
assert len(out['result']) == 5
assert out['result'][0][0] == pytest.approx(0.0)
assert out['result'][4][4] == pytest.approx(44.0)
def test_build_request_sets_heartbeat_on_trusted_action():
req = ExecRequest(action='run_trusted_action', allow_heartbeat=True, data={'domain': 'embeddings_index'}, timeout_sec=1)
request = req.wire()
assert request == req.wire()
assert request['id'] == req.request_id
assert request['allow_heartbeat'] is True
assert request['action'] == 'run_trusted_action'
assert request['data'] is req.data
assert 'code' not in request
assert request['timeout_sec'] == 1
assert 'cancel' not in request
assert 'script_session_id' not in request
empty = ExecRequest(allow_heartbeat=False, timeout_sec=1).wire()
assert empty['code'] == ''
assert 'session_id' not in empty
assert 'allow_heartbeat' not in empty
assert 'bindings' not in empty
def test_exec_request_wire_sandbox_policy():
policy = {'network': True, 'files': True, 'os': False, 'extra_modules': 'requests'}
code_req = ExecRequest(code='x = 1', sandbox_policy=policy, timeout_sec=1)
code_wire = code_req.wire()
assert code_wire['sandbox_policy'] == policy
assert code_wire['code'] == 'x = 1'
reset_req = ExecRequest(action='reset_session', sandbox_policy=policy, timeout_sec=1)
reset_wire = reset_req.wire()
assert 'sandbox_policy' not in reset_wire
assert reset_wire['action'] == 'reset_session'
trusted_req = ExecRequest(action='run_trusted_action', data={'domain': 'analysis'}, sandbox_policy=policy, timeout_sec=1)
trusted_wire = trusted_req.wire()
assert 'sandbox_policy' not in trusted_wire
assert trusted_wire['action'] == 'run_trusted_action'
def test_run_code_in_user_venv_reads_sandbox_policy_flags():
with patch('plugin.framework.config.get_config', return_value=10), patch('plugin.scripting.venv_worker.configured_venv_path', return_value=''), patch('plugin.scripting.venv_worker.resolve_libreoffice_python', return_value=sys.executable), patch('plugin.scripting.venv_worker.PythonWorkerManager.execute') as mock_execute:
mock_execute.return_value = {'status': 'ok', 'result': 1}
def fake_get_config(key: str):
if key == 'scripting.python_allow_os':
return True
if key in ('scripting.python_allow_network', 'scripting.python_allow_files'):
return False
if key == 'scripting.python_extra_modules':
return 'custom_mod'
return ''
with patch('plugin.scripting.venv_worker.get_config', side_effect=fake_get_config):
run_code_in_user_venv('result = 1')
assert mock_execute.call_args.args[0].sandbox_policy == {'network': False, 'files': False, 'os': True, 'extra_modules': 'custom_mod'}
mock_execute.reset_mock()
def fake_get_config_net_files(key: str):
if key in ('scripting.python_allow_network', 'scripting.python_allow_files'):
return True
if key == 'scripting.python_extra_modules':
return ''
return False
with patch('plugin.scripting.venv_worker.get_config', side_effect=fake_get_config_net_files):
run_code_in_user_venv('result = 1')
assert mock_execute.call_args.args[0].sandbox_policy == {'network': True, 'files': True, 'os': False, 'extra_modules': ''}
@pytest.mark.parametrize('exc_type', [ValueError, OverflowError, TypeError])
def test_bad_result_after_tool_call_does_not_replay(monkeypatch, exc_type):
"""Unpack failures (ValueError, OverflowError, TypeError) after a finished tool call do not resend the script."""
mgr, proc = _mock_mgr()
captured: dict[str, dict] = {}
def _write_frame(stdin, request, **kwargs):
captured['request'] = request
mgr._write_frame_with_timeout = _write_frame
reads = {'n': 0}
def _read(stdout, timeout_sec, cancel=None):
reads['n'] += 1
if reads['n'] == 1:
return pickle.dumps({'status': 'host_request'}, protocol=5)
request = captured['request']
return pickle.dumps({'status': 'ok', 'id': request['id'], 'result': {'split_grid': 'bad'}}, protocol=5)
mgr._read_response_bytes = _read
mgr._terminate_worker = MagicMock()
def _normalize(response):
raise exc_type('inconsistent split_grid')
mgr._normalize_response = _normalize
dispatched = {'n': 0}
def dispatch(response, *, stdin_write, on_worker_event=None, cancel=None, **kwargs):
del response, stdin_write, on_worker_event, cancel, kwargs
dispatched['n'] += 1
return dispatched['n'] == 1
monkeypatch.setattr(venv_worker_module, '_maybe_dispatch_intermediate_response', dispatch)
result = _run_ipc_with_mock(mgr, ExecRequest(code='result = 1', timeout_sec=1), proc)
assert result['status'] == 'error'
assert result['code'] == 'WORKER_IPC_ERROR'
assert 'inconsistent split_grid' in result['message']
assert 'request' in captured
assert reads['n'] == 2
assert mgr._terminate_worker.call_count == 1
def test_get_replaces_previous_interpreter_in_the_same_pool():
from plugin.scripting import venv_worker
shutdown_venv_workers_for_tests()
first = PythonWorkerManager.get('/tmp/python-a', {'PATH': '/usr/bin'})
second = PythonWorkerManager.get('/tmp/python-b', {'PATH': '/usr/bin'}, pool=WORKER_POOL_DEFAULT)
try:
assert first is not second
assert PythonWorkerManager.get('/tmp/python-b', {'PATH': '/usr/bin'}) is second
assert all((not key.endswith('python-a') for key in venv_worker._instances))
finally:
shutdown_venv_workers_for_tests()
def test_get_refreshes_env_for_the_next_spawn():
shutdown_venv_workers_for_tests()
try:
first = PythonWorkerManager.get('/tmp/python-env', {'PATH': '/usr/bin', 'A': '1'})
assert first.env['WRITERAGENT_IS_WORKER'] == '1'
second = PythonWorkerManager.get('/tmp/python-env', {'PATH': '/usr/bin', 'A': '1', 'B': '2'})
assert first is second
assert second.env['B'] == '2'
assert second.env['WRITERAGENT_IS_WORKER'] == '1'
finally:
shutdown_venv_workers_for_tests()
def test_retired_worker_does_not_respawn():
shutdown_venv_workers_for_tests()
try:
first = PythonWorkerManager.get('/tmp/python-old-path', {'PATH': '/usr/bin'}, pool=WORKER_POOL_DEFAULT)
seen: list[bool] = []
mock_warm = MagicMock()
mock_warm.is_alive.return_value = True
mock_warm.retire = MagicMock(side_effect=lambda: seen.append(first._retired))
first._warm = mock_warm
PythonWorkerManager.get('/tmp/python-new-path', {'PATH': '/usr/bin'}, pool=WORKER_POOL_DEFAULT)
assert seen == [True]
assert first._retired is True
mock_warm.retire.assert_called_once()
assert not _session_ok(first)
assert _mgr_proc(first) is None
finally:
shutdown_venv_workers_for_tests()
@patch('plugin.scripting.venv_worker.configured_venv_path', new=lambda: '')
@patch('plugin.framework.config.get_config', return_value=10)
@patch('plugin.scripting.venv_worker.get_config', return_value='')
@patch('plugin.scripting.venv_worker.resolve_libreoffice_python', return_value=sys.executable)
@patch('plugin.scripting.venv_worker.PythonWorkerManager.execute')
def test_run_venv_code_timeout_capped(mock_execute, mock_lo_python, mock_cfg, mock_configured_timeout):
for timeout_in, expected_timeout in [(None, 10), (100, 100), (1000, 600), (0, 1)]:
if timeout_in is None:
run_code_in_user_venv('result = 1')
else:
run_code_in_user_venv('result = 1', timeout_sec=timeout_in)
mock_execute.assert_called_once()
req = mock_execute.call_args.args[0]
assert req.timeout_sec == expected_timeout
mock_execute.reset_mock()
def test_run_code_forwards_script_session_pin_apart_from_kernel_session():
with patch('plugin.framework.config.get_config', return_value=10), patch('plugin.scripting.venv_worker.configured_venv_path', return_value=''), patch('plugin.scripting.venv_worker.resolve_libreoffice_python', return_value=sys.executable), patch('plugin.scripting.venv_worker.PythonWorkerManager.execute') as mock_execute:
mock_execute.return_value = {'status': 'ok', 'result': 1}
run_code_in_user_venv('result = 1', script_session_id='doc:pin')
req = mock_execute.call_args.args[0]
assert req.pin == 'doc:pin'
assert req.session_id is None
assert 'session_id' not in req.wire()
assert 'script_session_id' not in req.wire()
def _ipc_one_tool_call(*, session_id, script_session_id):
"""Drive one tool_call frame through the host without a real worker."""
mgr, proc = _mock_mgr()
captured: dict[str, dict] = {}
def _write_frame(stdin, request, **kwargs):
del stdin, kwargs
captured['request'] = request
mgr._write_frame_with_timeout = _write_frame
reads = {'n': 0}
def _read(stdout, timeout_sec, cancel=None):
del stdout, timeout_sec
reads['n'] += 1
request = captured['request']
if reads['n'] == 1:
return pickle.dumps({'type': 'tool_call', 'id': 'c1', 'tool': 'shape_upsert', 'args': {'action': 'create'}}, protocol=5)
return pickle.dumps({'status': 'ok', 'id': request['id'], 'result': 1}, protocol=5)
mgr._read_response_bytes = _read
with patch('plugin.scripting.host_rpc.execute_tool', return_value={'status': 'ok'}) as mock_tool:
result = _run_ipc_with_mock(
mgr,
ExecRequest(code='result = 1', timeout_sec=1, session_id=session_id, pin=script_session_id),
proc,
)
return (captured['request'], mock_tool.call_args, result)
def test_pinned_script_session_reaches_tool_rpc_without_kernel_session():
request, call, result = _ipc_one_tool_call(session_id=None, script_session_id='doc:pinned-deck')
assert result['status'] == 'ok'
assert 'session_id' not in request
assert call.kwargs['script_session_id'] == 'doc:pinned-deck'
def test_request_session_id_still_reaches_tool_rpc_without_pin():
request, call, result = _ipc_one_tool_call(session_id='rps:file:///deck.odg', script_session_id=None)
assert result['status'] == 'ok'
assert request['session_id'] == 'rps:file:///deck.odg'
assert call.kwargs['script_session_id'] == 'rps:file:///deck.odg'
def test_warm_prime_failure_does_not_raise() -> None:
import contextlib
mgr = PythonWorkerManager('/tmp/python-warm-fail', {'PATH': '/usr/bin'})
@contextlib.contextmanager
def fake_session(*args: object, **kwargs: object):
del args, kwargs
yield {'status': 'error', 'message': 'prime failed'}
with patch.object(mgr, '_io_session', fake_session):
mgr.warm()
def test_retired_execute_does_not_terminate_worker(monkeypatch: pytest.MonkeyPatch) -> None:
"""A replaced manager must not kill a worker on execute."""
mgr = PythonWorkerManager('/tmp/python-retired', {'PATH': '/usr/bin'})
mgr._retired = True