This repository was archived by the owner on Oct 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathfunction_manager.py
More file actions
10093 lines (9071 loc) · 390 KB
/
Copy pathfunction_manager.py
File metadata and controls
10093 lines (9071 loc) · 390 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
import ast
import asyncio
import builtins
import concurrent.futures
import dataclasses
import hashlib
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
import inspect
import functools
import json
import keyword
import os
import re
import signal
import socket
import sys
import tempfile
import logging
import threading
from pathlib import Path
from weakref import WeakSet
from unify.logger import LOGGER
from unify.common.hierarchical_logger import ICONS
from secrets import token_hex
from typing import (
Any,
Callable,
Dict,
FrozenSet,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Union,
TYPE_CHECKING,
)
import unisdk
from .shell_pool import ShellPool
from unisdk.utils.http import RequestError as _UnifyRequestError
from ..common.authorship import strip_authoring_assistant_id
from ..common.log_utils import create_logs as unity_create_logs
from ..common.embed_utils import ensure_vector_column, list_private_fields
from ..common.custom_sync import (
MANAGED_BY_DEPLOYMENT,
CustomSyncAdapter,
CustomSyncPartialFailure,
managed_rows_filter,
run_custom_sync,
stored_hash_field,
)
from ..common.sync_lease import exclusive_sync_lease
from ..common.federated_search import (
SCORE_FIELD,
FederatedSearchContext,
federated_filter,
federated_ranked_search,
)
from .activation import (
ActivationSettings,
activation,
in_scope,
merged_usage,
rank_score,
similarity_from_distance,
)
from ..common.builtins import builtins_project
from .builtins_catalog import BUILTINS_PRIMITIVES_CONTEXT
from ..common.tool_outcome import ToolErrorException
from .execution_env import ENVIRONMENT_MODULES, create_base_globals
from .steering import (
DEFAULT_TOOL_NAMESPACES,
ControlledInterruption,
ExecutionStopped,
MemoisedDispatch,
active_session,
bind_session,
dispatch_with_steering,
instrument,
interrupt_directive,
is_stopped_outcome,
restore_session,
run_with_steering,
)
from .dependency_analysis import (
collect_dependencies_from_function_node,
detect_third_party_imports,
)
from .types.function import Function
from .types.meta import FunctionsMeta
from .types.venv import VirtualEnv
from .types.verification import (
Fixture,
FunctionContract,
SideEffectClass,
StaticReviewRecord,
VerdictKind,
VerificationPolicy,
VerificationRow,
VerificationSummary,
)
from .verification.classify import (
Classification,
classify_source,
effective_class,
)
from .verification.contracts import contract_from_callable, merge_contract
from .verification.fixtures import (
FixtureRegressionError,
coerce_fixtures,
replay_fixtures,
)
from .verification.ledger import (
fold_rows,
function_trust_hash as _function_trust_hash,
)
from .verification.policy import derive_verify
from .verification.source_labels import compile_function_source
from .verification.tier0 import Tier0Checker, signature_from_source, tier0_boundary
from .settings import VerificationSettings
from .base import BaseFunctionManager
from .hash_utils import stable_hash_for_rows
from ..common.model_to_fields import model_to_fields, with_ui_editable_forced_false
from ..file_manager.managers.local import LocalFileManager
from ..image_manager.image_manager import ImageHandle
from ..manager_registry import ManagerRegistry
from ..common.filter_utils import normalize_filter_expr
from ..common.context_registry import ContextRegistry, TableContext
from ..common.stale_reason import (
StaleReason,
coerce_stale_reasons,
merge_stale_reasons,
)
from unify.function_manager.primitives.scope import (
PrimitiveScope,
default_runtime_scope,
)
from unify.function_manager.primitives.registry import get_registry
from unify.common.diagnostic_logging import (
log_staging_diagnostic,
)
from unify.integrations.function_metadata import (
function_metadata,
integration_app_slug,
integration_backend_id,
integration_metadata,
is_provider_backed_function,
provider_function_metadata,
)
from unify.integrations.builtins_catalog import list_catalog_tools
from unify.integrations.embedding_text import normalize_embedding_text
from .custom_functions import (
CustomFunctionSyncPartialFailure,
compute_custom_functions_hash,
compute_custom_venvs_hash,
)
logger = logging.getLogger(__name__)
FUNCTIONS_VENVS_TABLE = "Functions/VirtualEnvs"
FUNCTIONS_COMPOSITIONAL_TABLE = "Functions/Compositional"
FUNCTIONS_PRIMITIVES_TABLE = "Functions/Primitives"
FUNCTIONS_META_TABLE = "Functions/Meta"
FUNCTIONS_VERIFICATIONS_TABLE = "Functions/Verifications"
# Ledger state the runtime maintains; hidden from catalogue reads that do not
# hand back callables (fixtures alone can run to tens of kilobytes).
_LEDGER_INTERNAL_FIELDS = ("fixtures", "ledger", "static_review", "verified_hash")
#: What a reader of the catalogue never acts on, minus the history a repairer
#: cannot work without. A repair is asked to fix a function against a verdict;
#: without the prior verdicts on the same function it cannot tell a fresh
#: objection from one it has already answered, and cannot see that its last
#: attempt is what produced the current complaint.
_REPAIR_HIDDEN_FIELDS = ("fixtures", "verified_hash")
def strip_ledger_internals(
rows: List[Dict[str, Any]],
*,
keep_verdict_history: bool = False,
) -> List[Dict[str, Any]]:
"""Return ``rows`` without the ledger state a reader of the catalogue never acts on.
``keep_verdict_history`` retains ``ledger`` and ``static_review`` for a
caller that is reasoning about the verdicts themselves.
"""
hidden = set(
_REPAIR_HIDDEN_FIELDS if keep_verdict_history else _LEDGER_INTERNAL_FIELDS,
)
return [
(
{k: v for k, v in row.items() if k not in hidden}
if isinstance(row, dict)
else row
)
for row in rows
]
# Sentinel: omit ``destination`` to federate; pass ``None``/``"personal"``/``"team:<id>"`` to scope.
_DESTINATION_UNSET = object()
FUNCTIONS_COMPOSITIONAL_DESTINATION_GUIDANCE = """destination : str | None, default None
Where this composed function (or set of functions) lives. Pass
``"personal"`` (the default) for one-off helper scripts and private
automations. Pass ``"team:<id>"`` for team automation every member of the
team members should be able to invoke. See the *Accessible shared teams* block in
your system prompt for available teams and descriptions. Pick personal
when in doubt; call ``request_clarification`` when the right audience is
unclear."""
FUNCTIONS_VENV_DESTINATION_GUIDANCE = """destination : str | None, default None
Where the virtual env definition lives. Pass ``"personal"`` (the default)
for envs only your private functions need. Pass ``"team:<id>"`` to share
the env with team-level functions in that team. See the Accessible shared teams
block in your system prompt; pick personal when in doubt."""
if TYPE_CHECKING: # pragma: no cover
from unify.actor.execution.targets.assistant_desktop import (
AssistantDesktopTarget,
)
def _compositional_contexts() -> list[str]:
"""Every compositional functions context readable from here."""
from unify.common.context_registry import ContextRegistry
return [
f"{root.strip('/')}/{FUNCTIONS_COMPOSITIONAL_TABLE}"
for root in ContextRegistry.read_roots(
FunctionManager,
FUNCTIONS_COMPOSITIONAL_TABLE,
)
]
def function_id_resolves(function_id: int) -> bool:
"""Whether a stored id still points at a compositional function.
For callers holding an id and asking only about referential integrity --
a task's stored ``entrypoint``, say. An id rather than a manager handle
because the question is asked from stores that keep one and have no
reason to hold a FunctionManager.
Asked per id rather than by listing every function and testing
membership: ``get_logs`` pages at a thousand rows, so an enumeration
would report perfectly good ids as missing on any deployment past that,
and callers reading this as "gone" would act on it.
"""
for context in _compositional_contexts():
if unisdk.get_logs(
context=context,
filter=f"function_id == {int(function_id)}",
limit=1,
):
return True
return False
def function_managed_by(function_id: int) -> str | None:
"""Which reconcile source owns this function row, if any.
``None`` for a function no source authored -- one a user wrote, or one a
run distilled from its own trajectory. Callers use it to tell "this row
belongs to a bundle and its surface will prune it" from "this row belongs
to nobody and would otherwise be left behind".
"""
for context in _compositional_contexts():
logs = unisdk.get_logs(
context=context,
filter=f"function_id == {int(function_id)}",
limit=1,
)
if logs:
return (logs[0].entries or {}).get("managed_by") or None
return None
def delete_functions(function_ids: "set[int] | list[int]") -> list[int]:
"""Delete compositional functions by id, returning the ids actually removed.
For a caller that has already decided which functions should go and needs
them gone -- an uninstall clearing what its workflow's runs distilled.
Deciding *which* is the caller's problem; this only carries it out.
"""
if not function_ids:
return []
deleted: list[int] = []
for context in _compositional_contexts():
for function_id in function_ids:
logs = unisdk.get_logs(
context=context,
filter=f"function_id == {int(function_id)}",
limit=1,
)
if not logs:
continue
unisdk.delete_logs(context=context, logs=[logs[0].id])
deleted.append(int(function_id))
return deleted
class _LineageTrackedFunction:
"""Boundary wrapper for FunctionManager callables injected into CodeActActor sandboxes.
This wrapper preserves hierarchical lineage across mixed execution, e.g.:
CodeActActor.act -> execute_code -> <function> -> primitives.contacts.ask -> ...
It is injected into the Python namespace **in place of** the raw callable so that
inter-function calls (function A calling function B) still pass through a boundary that:
- updates `TOOL_LOOP_LINEAGE` (ContextVar)
- emits a concise boundary log line for terminal debugging
Note: async functions can be awaited in a different task context than the call-site.
ContextVar tokens are only valid in the context they were created, so this wrapper sets
lineage around coroutine construction (call-site) and again inside the awaited coroutine
(execution-site).
"""
def __init__(
self,
wrapped_callable: Callable[..., Any],
function_name: str,
on_call: Optional[Callable[[], None]] = None,
):
self._wrapped = wrapped_callable
self._function_name = function_name
# Usage-trace hook: this class is the one layer every boundary call
# already passes through, and its __getattr__ delegation keeps proxy
# identity intact — an OUTER wrapper broke remote-routing and venv
# cleanup introspection, which is why the trace records here.
self._on_call = on_call
# Preserve introspection attributes.
self.__name__ = function_name
self.__doc__ = getattr(wrapped_callable, "__doc__", None)
self.__wrapped__ = wrapped_callable
def __getattr__(self, name: str) -> Any:
# Preserve wrapped callable API (e.g. venv proxy state helpers).
return getattr(self._wrapped, name)
def __call__(self, *args: Any, **kwargs: Any) -> Any:
if self._on_call is not None:
try:
self._on_call()
except Exception: # noqa: BLE001 - metering must never break a call
pass
# Local imports to avoid import-time cycles.
from unify.common._async_tool.loop_config import TOOL_LOOP_LINEAGE
from unify.common.hierarchical_logger import log_boundary_event
suffix = token_hex(2)
parent = TOOL_LOOP_LINEAGE.get([])
parent_lineage = list(parent) if isinstance(parent, list) else []
hierarchy = [*parent_lineage, f"{self._function_name}({suffix})"]
try:
log_boundary_event("->".join(hierarchy), "Executing function...", icon="🛠️")
except Exception:
pass
# Ensure synchronous work at call-time (if any) happens under the lineage frame.
token_call = TOOL_LOOP_LINEAGE.set(hierarchy)
try:
result = self._wrapped(*args, **kwargs)
except Exception:
TOOL_LOOP_LINEAGE.reset(token_call)
raise
finally:
# For async results we only needed the lineage during coroutine construction.
# The actual awaited execution will run under a new token created in the
# awaiting task context below.
try:
TOOL_LOOP_LINEAGE.reset(token_call)
except Exception:
pass
if inspect.isawaitable(result):
async def _await_and_finalize():
token_run = TOOL_LOOP_LINEAGE.set(hierarchy)
try:
return await result
finally:
TOOL_LOOP_LINEAGE.reset(token_run)
return _await_and_finalize()
return result
class _DependencyVisitor(ast.NodeVisitor):
"""
Statefully analyzes function AST to find direct calls and indirect calls
via variables assigned function names, specifically looking for names
known to the FunctionManager.
"""
def __init__(self, known_function_names: Set[str]):
self.known_function_names = known_function_names
self.dependencies: Set[str] = set()
self._assignment_map: Dict[str, str] = {}
def visit_Assign(self, node: ast.Assign):
# Only track simple assignments: target_var = potential_func_name
if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
target_var = node.targets[0].id
if isinstance(node.value, ast.Name):
assigned_name = node.value.id
# Check if the assigned name is one of the functions we manage
if assigned_name in self.known_function_names:
# Record the mapping for the current scope
self._assignment_map[target_var] = assigned_name
# If variable is assigned something else, remove mapping
elif target_var in self._assignment_map:
del self._assignment_map[target_var]
# If variable is assigned non-Name, remove mapping
elif target_var in self._assignment_map:
del self._assignment_map[target_var]
self.generic_visit(node)
def visit_Call(self, node: ast.Call):
func_node = node.func
called_name: Optional[str] = None
# Case 1: Direct call -> func_name()
if isinstance(func_node, ast.Name):
func_name = func_node.id
# Check if it's a direct call to a known library function
if func_name in self.known_function_names:
called_name = func_name
# Check if it's an indirect call via a mapped variable -> var()
elif func_name in self._assignment_map:
called_name = self._assignment_map[func_name]
# Case 2: Method call -> obj.method() - generally ignore for dependency injection
# (We assume obj like computer_primitives is globally available)
if called_name:
self.dependencies.add(called_name)
self.generic_visit(node) # Continue traversal
def visit_Return(self, node: ast.Return):
# Case 3: Return statement -> return func_name or return var
if isinstance(node.value, ast.Name):
returned_name = node.value.id
# Check if returning a known function name directly
if returned_name in self.known_function_names:
self.dependencies.add(returned_name)
# Also check if returning a variable that was assigned a function
elif returned_name in self._assignment_map:
self.dependencies.add(self._assignment_map[returned_name])
self.generic_visit(node)
def _strip_custom_function_decorators(source: str) -> str:
"""
Remove @custom_function decorators from a function source string.
The @custom_function decorator is used for sync metadata only (it is effectively
a no-op at runtime), but the symbol is not guaranteed to exist inside execution
environments (e.g., Actor sandboxes or venv runner subprocesses).
Handles both single-line and multi-line decorator syntax:
@custom_function(venv_name="foo") # single-line
@custom_function( # multi-line
venv_name="foo",
verify=True,
)
"""
try:
lines = source.splitlines(keepends=True)
except Exception:
return source
out: List[str] = []
seen_def = False
in_custom_decorator = False
paren_depth = 0
for line in lines:
stripped = line.lstrip()
# Once we've seen the function definition, keep all lines
if seen_def:
out.append(line)
continue
if stripped.startswith("def ") or stripped.startswith("async def "):
seen_def = True
out.append(line)
continue
# Check if this line starts a @custom_function decorator
if stripped.startswith("@custom_function"):
in_custom_decorator = True
# Count parentheses to handle multi-line decorators
paren_depth += stripped.count("(") - stripped.count(")")
# If parens are balanced on this line, decorator is complete
if paren_depth <= 0:
in_custom_decorator = False
paren_depth = 0
continue
# If we're inside a multi-line @custom_function decorator, skip lines
if in_custom_decorator:
paren_depth += stripped.count("(") - stripped.count(")")
if paren_depth <= 0:
in_custom_decorator = False
paren_depth = 0
continue
# Keep other decorators and lines before the function def
out.append(line)
return "".join(out)
# Pattern for shell script metadata comments
_SHELL_NAME_PATTERN = re.compile(r"^#\s*@name:\s*(.+?)\s*$", re.MULTILINE)
_SHELL_ARGS_PATTERN = re.compile(r"^#\s*@args:\s*(.+?)\s*$", re.MULTILINE)
_SHELL_DESC_PATTERN = re.compile(r"^#\s*@description:\s*(.+?)\s*$", re.MULTILINE)
def _parse_shell_script_metadata(source: str) -> Dict[str, Optional[str]]:
"""
Parse metadata from shell script comments.
Expected format at the top of the script::
#!/bin/sh
# @name: my_function
# @args: (input_file output_file --verbose)
# @description: Brief description of what the function does
Returns:
Dict with keys: name, argspec, docstring (any may be None if not found)
"""
name_match = _SHELL_NAME_PATTERN.search(source)
args_match = _SHELL_ARGS_PATTERN.search(source)
desc_match = _SHELL_DESC_PATTERN.search(source)
return {
"name": name_match.group(1).strip() if name_match else None,
"argspec": args_match.group(1).strip() if args_match else "()",
"docstring": desc_match.group(1).strip() if desc_match else "",
}
def _instrument_for_child(source: str) -> str:
"""Ship steering probes with source bound for a venv subprocess.
The child runs the probes against shims ``venv_runner`` installs, which
read the control channel — so a loop that makes no primitive call is
still interruptible between dispatches. Source that does not parse ships
unchanged, so the child reports the SyntaxError exactly as an unsteered
run would.
"""
try:
tree = ast.parse(source)
except SyntaxError:
return source
return ast.unparse(instrument(tree, tool_namespaces=set(DEFAULT_TOOL_NAMESPACES)))
class _VenvConnection:
"""
Manages a persistent connection to a venv subprocess in server mode.
The subprocess maintains state across calls, enabling variables to persist
between function executions within the same venv.
"""
def __init__(
self,
process: asyncio.subprocess.Process,
venv_id: int,
function_manager: "FunctionManager",
):
self._process = process
self._venv_id = venv_id
self._function_manager = function_manager
self._lock = asyncio.Lock() # Serialize calls to same venv
self._closed = False
self._tainted = False # Set to True after timeout or other corruption
@classmethod
async def create(
cls,
venv_id: int,
function_manager: "FunctionManager",
timeout: float = 30.0,
) -> "_VenvConnection":
"""
Create a new persistent venv connection.
Args:
venv_id: The virtual environment to connect to.
function_manager: The FunctionManager instance for venv preparation.
timeout: Timeout for subprocess startup.
Returns:
A new _VenvConnection instance.
Raises:
RuntimeError: If the subprocess fails to start or send ready signal.
"""
python_path = await function_manager.prepare_venv(venv_id=venv_id)
runner_path = function_manager._get_venv_runner_path(venv_id)
from unify.provider_proxy.session import build_sandbox_env
use_process_group = sys.platform != "win32"
process = await asyncio.create_subprocess_exec(
str(python_path),
str(runner_path),
"--server",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
start_new_session=use_process_group,
env=build_sandbox_env(),
)
conn = cls(process, venv_id, function_manager)
# Wait for ready signal from subprocess
try:
ready_msg = await asyncio.wait_for(
conn._read_message(),
timeout=timeout,
)
if ready_msg.get("type") != "ready":
raise RuntimeError(
f"Venv {venv_id} subprocess sent unexpected message: {ready_msg}",
)
except asyncio.TimeoutError:
await conn.shutdown()
raise RuntimeError(
f"Venv {venv_id} subprocess did not send ready signal within {timeout}s",
)
except Exception as e:
await conn.shutdown()
raise RuntimeError(
f"Venv {venv_id} subprocess failed to start: {e}",
) from e
return conn
async def _read_message(self) -> dict:
"""Read a JSON message from the subprocess stdout."""
if self._process.stdout is None:
raise RuntimeError("Subprocess stdout is None")
line = await self._process.stdout.readline()
if not line:
raise EOFError("Subprocess stdout closed")
return json.loads(line.decode().strip())
async def _write_message(self, msg: dict) -> None:
"""Write a JSON message to the subprocess stdin."""
if self._process.stdin is None:
raise RuntimeError("Subprocess stdin is None")
data = json.dumps(msg) + "\n"
self._process.stdin.write(data.encode())
await self._process.stdin.drain()
def is_alive(self) -> bool:
"""Check if the subprocess is still running and usable."""
return (
not self._closed and not self._tainted and self._process.returncode is None
)
async def execute(
self,
implementation: str,
call_kwargs: dict,
is_async: bool,
primitives: Optional[Any] = None,
computer_primitives: Optional[Any] = None,
timeout: Optional[float] = None,
env_overlay: Optional[Dict[str, str]] = None,
) -> dict:
"""
Execute a function in the persistent venv subprocess.
While a steering session is in flight, each RPC reply doubles as a
checkpoint and a correction re-sends the (patched) source over the
same connection, replaying already-completed dispatches from the
parent's cache. The session arrives by contextvar so it follows the
call rather than this long-lived connection.
Args:
implementation: The function source code.
call_kwargs: Keyword arguments to pass to the function.
is_async: Whether the function is async.
primitives: The Primitives instance for RPC access.
computer_primitives: The ComputerPrimitives instance for RPC access.
timeout: Execution timeout in seconds (None for no timeout).
Returns:
Dict with keys: result, error, stdout, stderr
Raises:
RuntimeError: If the subprocess has died or execution fails.
asyncio.TimeoutError: If execution exceeds timeout.
"""
async with self._lock:
if not self.is_alive():
raise RuntimeError(
f"Venv {self._venv_id} subprocess has died (returncode={self._process.returncode})",
)
steering = active_session()
async def _attempt(source: str) -> dict:
"""Send one execute request for *source* and relay its RPC."""
await self._write_message(
{
"type": "execute",
"implementation": (
_instrument_for_child(source)
if steering is not None
else source
),
"call_kwargs": call_kwargs,
"is_async": is_async,
"env_overlay": env_overlay or {},
},
)
# Set when a correction interrupted this attempt; the child's
# completion is then an unwind to discard, not a result.
interrupted: Optional[ControlledInterruption] = None
# Corrections that land between dispatches reach the child
# through the control channel, not through an RPC reply.
watcher = (
asyncio.create_task(
steering.relay_corrections(
source,
lambda request: self._write_message(
interrupt_directive(request),
),
),
)
if steering is not None
else None
)
pause_watcher = (
asyncio.create_task(
steering.relay_pause(
lambda paused: self._function_manager._set_process_paused(
self._process,
use_process_group=sys.platform != "win32",
paused=paused,
),
),
)
if steering is not None
else None
)
try:
while True:
msg = await self._read_message()
msg_type = msg.get("type")
if msg_type == "complete":
if interrupted is not None:
raise interrupted
child_interrupted = msg.get("interrupted")
if child_interrupted:
# The child unwound at an instrumented
# checkpoint; discard the attempt and retry.
raise ControlledInterruption(child_interrupted)
return msg
if msg_type == "rpc_call":
# Handle RPC call from subprocess
try:
reply = await self._handle_rpc_call(
msg,
primitives=primitives,
computer_primitives=computer_primitives,
)
except ControlledInterruption as interruption:
# The child is blocked on this reply, so
# telling it to unwind here is the interrupt
# probe realised without instrumentation.
interrupted = interruption
reply = {
"type": "rpc_interrupt",
"id": msg.get("id"),
"reason": str(interruption),
}
await self._write_message(reply)
else:
logger.warning(
f"Venv {self._venv_id}: unexpected message type '{msg_type}'",
)
finally:
for task in (watcher, pause_watcher):
if task is None:
continue
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
except Exception:
# A watcher can lose the race with the run ending;
# the attempt's own outcome stands.
logger.debug(
"steering: subprocess watcher failed",
exc_info=True,
)
if pause_watcher is not None:
await self._function_manager._set_process_paused(
self._process,
use_process_group=sys.platform != "win32",
paused=False,
)
async def _run(source: str) -> dict:
if timeout is None:
return await _attempt(source)
try:
return await asyncio.wait_for(_attempt(source), timeout=timeout)
except asyncio.TimeoutError:
# After a timeout, the subprocess is in an unknown state.
# Mark it as tainted so the pool recreates it on next use.
self._tainted = True
raise
if steering is None:
return await _run(implementation)
try:
return await run_with_steering(
implementation,
_run,
session=steering,
)
except ExecutionStopped as stopped:
return {
"result": stopped.outcome,
"error": None,
"stdout": "",
"stderr": "",
}
async def _handle_rpc_call(
self,
msg: dict,
primitives: Optional[Any],
computer_primitives: Optional[Any],
) -> dict:
"""Answer one RPC message from the subprocess.
Dispatch, memoisation and interrupts are shared with the one-shot
path via :meth:`FunctionManager._handle_rpc_call`, so a pooled session
cannot drift into being silently unsteerable. A
:class:`ControlledInterruption` propagates to the execute loop, which
owns telling the child to unwind.
"""
request_id = msg.get("id")
try:
result = await self._function_manager._handle_rpc_call(
path=msg.get("path", ""),
kwargs=msg.get("kwargs", {}),
primitives=primitives,
computer_primitives=computer_primitives,
)
except ControlledInterruption:
raise
except Exception as e:
return {"type": "rpc_error", "id": request_id, "error": str(e)}
return {
"type": "rpc_result",
"id": request_id,
"result": self._function_manager._make_json_serializable(result),
}
async def get_state(self, timeout: float = 30.0) -> Dict[str, Any]:
"""
Get serialized user-defined state from the persistent subprocess.
This is used for read_only mode to capture the current state before
executing in an ephemeral subprocess.
Args:
timeout: Timeout for state retrieval.
Returns:
Dict of serialized state variables.
Raises:
RuntimeError: If the subprocess has died or retrieval fails.
asyncio.TimeoutError: If retrieval exceeds timeout.
"""
async with self._lock:
if not self.is_alive():
raise RuntimeError(
f"Venv {self._venv_id} subprocess has died (returncode={self._process.returncode})",
)
await self._write_message({"type": "get_state"})
async def wait_for_state() -> Dict[str, Any]:
while True:
msg = await self._read_message()
if msg.get("type") == "state":
return msg.get("state", {})
# Ignore other message types while waiting
if timeout is not None:
return await asyncio.wait_for(wait_for_state(), timeout=timeout)
return await wait_for_state()
async def shutdown(self, timeout: float = 5.0) -> None:
"""
Gracefully shut down the subprocess.
Args:
timeout: Timeout for graceful shutdown before force-killing.
"""
if self._closed:
return
self._closed = True
if self._process.returncode is not None:
return
try:
# Try graceful shutdown
await self._write_message({"type": "shutdown"})
await asyncio.wait_for(self._process.wait(), timeout=timeout)
except (asyncio.TimeoutError, Exception):
# Force kill if graceful shutdown fails
try:
if sys.platform != "win32":
# Kill entire process group
os.killpg(os.getpgid(self._process.pid), signal.SIGTERM)
else:
self._process.terminate()
await asyncio.wait_for(self._process.wait(), timeout=2.0)
except Exception:
try:
self._process.kill()
except Exception:
pass
@dataclass
class SessionMetadata:
venv_id: int
session_id: int
created_at: datetime
last_used: datetime
class SessionLimitError(RuntimeError):
def __init__(self, *, message: str):
super().__init__(message)
self.message = message
def to_error_dict(self) -> dict:
return {"error": self.message, "error_type": "resource_limit"}
class VenvPool:
"""
Manages a pool of persistent venv subprocess connections.
Each sandbox gets its own VenvPool, ensuring state isolation between
different actors/sandboxes while preserving state across function calls
within the same sandbox.
Connections are keyed by (venv_id, session_id), allowing multiple independent
stateful sessions per venv. Each session has its own subprocess and globals.
"""
_instances = WeakSet()
def __init__(self, *, max_total_sessions: int = 20) -> None:
# Key: (venv_id, session_id) -> _VenvConnection
self._connections: Dict[Tuple[int, int], _VenvConnection] = {}
self._metadata: Dict[Tuple[int, int], SessionMetadata] = {}
self._lock = asyncio.Lock()
self._closed = False
self._max_total_sessions = int(max_total_sessions)