python-repl-mcp 0.2.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_repl_mcp/__init__.py +5 -0
- python_repl_mcp/_helper.py +197 -0
- python_repl_mcp/_winjob.py +175 -0
- python_repl_mcp/config.py +84 -0
- python_repl_mcp/errors.py +63 -0
- python_repl_mcp/fileio.py +130 -0
- python_repl_mcp/kernel.py +724 -0
- python_repl_mcp/launcher.py +43 -0
- python_repl_mcp/opencode.py +195 -0
- python_repl_mcp/protocol.py +210 -0
- python_repl_mcp/server.py +318 -0
- python_repl_mcp/service.py +866 -0
- python_repl_mcp/worker.py +549 -0
- python_repl_mcp-0.2.5.dist-info/METADATA +218 -0
- python_repl_mcp-0.2.5.dist-info/RECORD +19 -0
- python_repl_mcp-0.2.5.dist-info/WHEEL +5 -0
- python_repl_mcp-0.2.5.dist-info/entry_points.txt +2 -0
- python_repl_mcp-0.2.5.dist-info/licenses/LICENSE +21 -0
- python_repl_mcp-0.2.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
"""Per-chat worker slots, admission and lifecycle ownership.
|
|
2
|
+
|
|
3
|
+
All state lives on one asyncio event loop. A slot is reserved *before* any
|
|
4
|
+
native resource exists, stays reserved through cleanup, and is removed only by
|
|
5
|
+
object identity. Callers borrow slots; the service owns every reset/stop it has
|
|
6
|
+
accepted, so cancelling a caller cannot orphan a process.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
from collections.abc import Callable, Coroutine
|
|
16
|
+
from dataclasses import dataclass, field, replace
|
|
17
|
+
from enum import StrEnum
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from pydantic import ValidationError
|
|
22
|
+
|
|
23
|
+
from python_repl_mcp import fileio
|
|
24
|
+
from python_repl_mcp._helper import ExitUnconfirmed
|
|
25
|
+
from python_repl_mcp.config import Config
|
|
26
|
+
from python_repl_mcp.errors import (
|
|
27
|
+
CapacityExceeded,
|
|
28
|
+
CleanupIncomplete,
|
|
29
|
+
FileError,
|
|
30
|
+
KernelStartError,
|
|
31
|
+
ReplError,
|
|
32
|
+
SessionBusy,
|
|
33
|
+
SessionDirectoryUnavailable,
|
|
34
|
+
ShuttingDown,
|
|
35
|
+
StaleWorker,
|
|
36
|
+
StartupFailed,
|
|
37
|
+
)
|
|
38
|
+
from python_repl_mcp.kernel import ExecuteOutcome, Kernel
|
|
39
|
+
from python_repl_mcp.opencode import OpenCode
|
|
40
|
+
from python_repl_mcp.protocol import (
|
|
41
|
+
MAX_ARG_CHARS,
|
|
42
|
+
MAX_ARGV,
|
|
43
|
+
ProtocolError,
|
|
44
|
+
Request,
|
|
45
|
+
encode_frame,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
_LOGGER = logging.getLogger(__name__)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _reject_drive_relative(file_path: str) -> None:
|
|
52
|
+
"""A drive-relative path would resolve against the dispatcher, not the chat."""
|
|
53
|
+
path = Path(file_path).expanduser()
|
|
54
|
+
if os.name == "nt" and path.drive and not path.is_absolute():
|
|
55
|
+
raise FileError(f"a file path must be absolute or relative to the chat directory: {file_path}")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SlotState(StrEnum):
|
|
59
|
+
STARTING = "starting"
|
|
60
|
+
READY = "ready"
|
|
61
|
+
CLOSING = "closing"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(slots=True)
|
|
65
|
+
class _Slot:
|
|
66
|
+
session_id: str
|
|
67
|
+
kernel: Kernel
|
|
68
|
+
state: SlotState = SlotState.STARTING
|
|
69
|
+
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
|
70
|
+
lifecycle: asyncio.Task[None] | None = None
|
|
71
|
+
generation: int = 0
|
|
72
|
+
idle_timer: asyncio.TimerHandle | None = None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(slots=True)
|
|
76
|
+
class _Preflight:
|
|
77
|
+
"""Identity marker shared by the file reads waiting on one session."""
|
|
78
|
+
|
|
79
|
+
waiters: int = 0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ReplService:
|
|
83
|
+
"""Owns the session map and every worker process behind it."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, config: Config) -> None:
|
|
86
|
+
self._config = config
|
|
87
|
+
self._slots: dict[str, _Slot] = {}
|
|
88
|
+
self._preflights: dict[str, _Preflight] = {}
|
|
89
|
+
self._closed = False
|
|
90
|
+
self._tasks: set[asyncio.Task[object]] = set()
|
|
91
|
+
# File-read owners are cancelled at shutdown; lookups and lifecycle
|
|
92
|
+
# owners are joined through their own bounded deadlines.
|
|
93
|
+
self._file_readers: set[asyncio.Task[object]] = set()
|
|
94
|
+
self._lookup_abandons: set[asyncio.Event] = set()
|
|
95
|
+
self._shutdown_task: asyncio.Task[None] | None = None
|
|
96
|
+
self._directory_lookups = asyncio.Semaphore(config.max_sessions)
|
|
97
|
+
self._file_reads = asyncio.Semaphore(config.max_sessions)
|
|
98
|
+
# A helper that may still be running must not be followed by another one.
|
|
99
|
+
self._lookup_blocked = False
|
|
100
|
+
self._file_reads_blocked = False
|
|
101
|
+
# A directory can stay locked after its stop returns. Keep only its
|
|
102
|
+
# path, bounded like the slots, so one later operation can retry it.
|
|
103
|
+
self._retained_spools: set[Path] = set()
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def closed(self) -> bool:
|
|
107
|
+
return self._closed
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def session_count(self) -> int:
|
|
111
|
+
return len(self._slots)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def session_id(self) -> str | None:
|
|
115
|
+
return self._config.session_id
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def pooled(self) -> bool:
|
|
119
|
+
return self._config.opencode is not None
|
|
120
|
+
|
|
121
|
+
# -- execution ---------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
async def execute(
|
|
124
|
+
self,
|
|
125
|
+
session_id: str,
|
|
126
|
+
code: str,
|
|
127
|
+
timeout_seconds: float,
|
|
128
|
+
*,
|
|
129
|
+
filename: str = "<cell>",
|
|
130
|
+
argv: list[str] | None = None,
|
|
131
|
+
file_mode: bool = False,
|
|
132
|
+
file_workdir: Path | None = None,
|
|
133
|
+
resolved_workdir: Path | None = None,
|
|
134
|
+
) -> ExecuteOutcome:
|
|
135
|
+
self._check_open()
|
|
136
|
+
slot = self._slots.get(session_id)
|
|
137
|
+
if slot is None:
|
|
138
|
+
slot = self._reserve(session_id)
|
|
139
|
+
generation = slot.generation
|
|
140
|
+
admitted_lifecycle = slot.lifecycle
|
|
141
|
+
admitted_kernel = slot.kernel
|
|
142
|
+
self._check_not_busy(slot)
|
|
143
|
+
prepare: Callable[[Kernel], None] | None = None
|
|
144
|
+
if file_mode:
|
|
145
|
+
|
|
146
|
+
def prepare_request(kernel: Kernel) -> None:
|
|
147
|
+
if file_workdir is not None and kernel.workdir != file_workdir:
|
|
148
|
+
raise StaleWorker("the worker directory changed while this file was read")
|
|
149
|
+
kernel.prepare_file_request(code, filename=filename, argv=argv)
|
|
150
|
+
|
|
151
|
+
prepare = prepare_request
|
|
152
|
+
hooks = self._config.hooks
|
|
153
|
+
if hooks is not None and hooks.execution_waiting is not None and slot.lock.locked():
|
|
154
|
+
await hooks.execution_waiting(session_id)
|
|
155
|
+
async with slot.lock:
|
|
156
|
+
self._check_open()
|
|
157
|
+
if self._slots.get(session_id) is not slot:
|
|
158
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
159
|
+
if slot.generation != generation:
|
|
160
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
161
|
+
if admitted_lifecycle is None and slot.lifecycle is not None:
|
|
162
|
+
# A lifecycle operation was accepted after this call was admitted.
|
|
163
|
+
raise StaleWorker("a lifecycle operation replaced the worker")
|
|
164
|
+
self._check_not_busy(slot)
|
|
165
|
+
if file_workdir is not None and slot.kernel.workdir not in (None, file_workdir):
|
|
166
|
+
raise StaleWorker("the worker directory changed while this file was read")
|
|
167
|
+
try:
|
|
168
|
+
await self._ensure_ready(slot, prepare, resolved_workdir=resolved_workdir)
|
|
169
|
+
except KernelStartError as exc:
|
|
170
|
+
self._discard_unstarted(slot, generation)
|
|
171
|
+
raise StartupFailed(str(exc)) from exc
|
|
172
|
+
except ProtocolError as exc:
|
|
173
|
+
self._discard_unstarted(slot, generation)
|
|
174
|
+
raise FileError("file and arguments exceed the private frame limit") from exc
|
|
175
|
+
except SessionDirectoryUnavailable, StaleWorker:
|
|
176
|
+
self._discard_unstarted(slot, generation)
|
|
177
|
+
raise
|
|
178
|
+
except asyncio.CancelledError:
|
|
179
|
+
# Only a confirmed-closed admitted kernel may be reaped. A
|
|
180
|
+
# starting kernel is shared with later callers and must keep
|
|
181
|
+
# starting after this waiter is cancelled.
|
|
182
|
+
if admitted_kernel.is_closed:
|
|
183
|
+
self._reap(slot, admitted_kernel)
|
|
184
|
+
if self.pooled:
|
|
185
|
+
self._discard_unstarted(slot, generation)
|
|
186
|
+
raise
|
|
187
|
+
except ReplError:
|
|
188
|
+
self._release_closed_slot(slot, generation)
|
|
189
|
+
raise
|
|
190
|
+
if slot.generation != generation or self._lifecycle_active(slot):
|
|
191
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
192
|
+
kernel = slot.kernel
|
|
193
|
+
if slot.kernel is not kernel or slot.state is not SlotState.READY or not kernel.is_ready:
|
|
194
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
195
|
+
fresh = kernel.cell_count == 0
|
|
196
|
+
try:
|
|
197
|
+
outcome = await kernel.execute(
|
|
198
|
+
code,
|
|
199
|
+
timeout_seconds,
|
|
200
|
+
fresh=fresh,
|
|
201
|
+
filename=filename,
|
|
202
|
+
argv=argv,
|
|
203
|
+
file_mode=file_mode,
|
|
204
|
+
)
|
|
205
|
+
except asyncio.CancelledError:
|
|
206
|
+
kernel.request_close()
|
|
207
|
+
self._retire_in_background(slot, kernel)
|
|
208
|
+
raise
|
|
209
|
+
self._reap(slot, kernel)
|
|
210
|
+
self._arm_idle(slot)
|
|
211
|
+
return replace(
|
|
212
|
+
outcome,
|
|
213
|
+
kernel_id=kernel.kernel_id,
|
|
214
|
+
workdir=str(kernel.workdir) if kernel.workdir is not None else None,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
async def run_file(
|
|
218
|
+
self,
|
|
219
|
+
session_id: str,
|
|
220
|
+
file_path: str,
|
|
221
|
+
arguments: list[str],
|
|
222
|
+
timeout_seconds: float,
|
|
223
|
+
) -> ExecuteOutcome:
|
|
224
|
+
"""Read one script before any worker is started, then run it in the chat namespace."""
|
|
225
|
+
self._check_open()
|
|
226
|
+
if "\0" in file_path:
|
|
227
|
+
raise FileError("the file path contains a NUL character")
|
|
228
|
+
admitted = self._slots.get(session_id)
|
|
229
|
+
preflight = self._register_preflight(session_id)
|
|
230
|
+
try:
|
|
231
|
+
resolved = None
|
|
232
|
+
workdir = self._config.workdir
|
|
233
|
+
if self.pooled:
|
|
234
|
+
_reject_drive_relative(file_path)
|
|
235
|
+
bound = admitted.kernel.workdir if admitted is not None and not admitted.kernel.is_closing else None
|
|
236
|
+
if bound is None:
|
|
237
|
+
resolved = await self._resolve_chat_workdir(session_id)
|
|
238
|
+
workdir = resolved
|
|
239
|
+
else:
|
|
240
|
+
workdir = bound
|
|
241
|
+
path, source = await self._read_script(str(self._absolute_script_path(file_path, workdir)), workdir)
|
|
242
|
+
if admitted is not None and self._slots.get(session_id) is not admitted:
|
|
243
|
+
raise StaleWorker("the worker was stopped or replaced while the file was read")
|
|
244
|
+
if len(arguments) > MAX_ARGV - 1:
|
|
245
|
+
raise FileError(f"more than {MAX_ARGV - 1} script arguments were supplied")
|
|
246
|
+
for argument in arguments:
|
|
247
|
+
if len(argument) > MAX_ARG_CHARS:
|
|
248
|
+
raise FileError("a script argument exceeds the size limit")
|
|
249
|
+
try:
|
|
250
|
+
encode_frame(
|
|
251
|
+
Request(
|
|
252
|
+
id=0,
|
|
253
|
+
code=source or "\n",
|
|
254
|
+
stdout="",
|
|
255
|
+
stderr="",
|
|
256
|
+
mode="file",
|
|
257
|
+
filename=str(path),
|
|
258
|
+
argv=[str(path), *arguments],
|
|
259
|
+
)
|
|
260
|
+
)
|
|
261
|
+
except (ProtocolError, ValidationError) as exc:
|
|
262
|
+
raise FileError("file and arguments exceed the private frame limit") from exc
|
|
263
|
+
if self._preflights.get(session_id) is not preflight:
|
|
264
|
+
raise StaleWorker("a stop or reset replaced the file read")
|
|
265
|
+
finally:
|
|
266
|
+
self._release_preflight(session_id, preflight)
|
|
267
|
+
outcome = await self.execute(
|
|
268
|
+
session_id,
|
|
269
|
+
source or "\n",
|
|
270
|
+
timeout_seconds,
|
|
271
|
+
filename=str(path),
|
|
272
|
+
argv=[str(path), *arguments],
|
|
273
|
+
file_mode=True,
|
|
274
|
+
file_workdir=workdir if self.pooled else None,
|
|
275
|
+
resolved_workdir=resolved,
|
|
276
|
+
)
|
|
277
|
+
return replace(outcome, file=str(path))
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def _absolute_script_path(file_path: str, workdir: Path) -> Path:
|
|
281
|
+
"""Resolve the caller's path context in the server process, cheaply.
|
|
282
|
+
|
|
283
|
+
``Path.absolute`` uses this process's per-drive current directory, which
|
|
284
|
+
is what standalone mode always did; it performs no filesystem I/O. The
|
|
285
|
+
helper then resolves symlinks where it can be terminated.
|
|
286
|
+
"""
|
|
287
|
+
try:
|
|
288
|
+
path = Path(file_path).expanduser()
|
|
289
|
+
if not path.is_absolute():
|
|
290
|
+
path = workdir / path
|
|
291
|
+
return path.absolute()
|
|
292
|
+
except (OSError, ValueError) as exc:
|
|
293
|
+
raise FileError(f"could not resolve file: {file_path}") from exc
|
|
294
|
+
|
|
295
|
+
async def _read_script(self, file_path: str, workdir: Path) -> tuple[Path, str]:
|
|
296
|
+
"""Admit one bounded, terminable read; the caller can leave at the deadline."""
|
|
297
|
+
loop = asyncio.get_running_loop()
|
|
298
|
+
deadline = loop.time() + self._config.handshake_timeout
|
|
299
|
+
if self._file_reads_blocked:
|
|
300
|
+
raise FileError("an earlier file-read helper did not confirm exit; restart the MCP server")
|
|
301
|
+
try:
|
|
302
|
+
await asyncio.wait_for(self._file_reads.acquire(), max(0.0, deadline - loop.time()))
|
|
303
|
+
except TimeoutError as exc:
|
|
304
|
+
raise FileError("reading the script exceeded the file-preflight budget") from exc
|
|
305
|
+
owner = loop.create_task(self._file_read(file_path, workdir, deadline))
|
|
306
|
+
self._track_file_read(owner)
|
|
307
|
+
try:
|
|
308
|
+
return await asyncio.wait_for(asyncio.shield(owner), max(0.0, deadline - loop.time()))
|
|
309
|
+
except TimeoutError as exc:
|
|
310
|
+
raise FileError("reading the script exceeded the file-preflight budget") from exc
|
|
311
|
+
|
|
312
|
+
async def _file_read(self, file_path: str, workdir: Path, deadline: float) -> tuple[Path, str]:
|
|
313
|
+
try:
|
|
314
|
+
self._check_open()
|
|
315
|
+
if self._file_reads_blocked:
|
|
316
|
+
raise FileError("an earlier file-read helper did not confirm exit; restart the MCP server")
|
|
317
|
+
hooks = self._config.hooks
|
|
318
|
+
before_publish = hooks.before_helper_publish if hooks is not None else None
|
|
319
|
+
before_exit = hooks.before_helper_exit if hooks is not None else None
|
|
320
|
+
return await fileio.read_script(
|
|
321
|
+
file_path,
|
|
322
|
+
workdir,
|
|
323
|
+
deadline,
|
|
324
|
+
before_publish=before_publish,
|
|
325
|
+
before_exit=before_exit,
|
|
326
|
+
)
|
|
327
|
+
except ExitUnconfirmed as exc:
|
|
328
|
+
self._file_reads_blocked = True
|
|
329
|
+
raise FileError("an earlier file-read helper did not confirm exit; restart the MCP server") from exc
|
|
330
|
+
finally:
|
|
331
|
+
self._file_reads.release()
|
|
332
|
+
|
|
333
|
+
# -- lifecycle ---------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
async def reset(self, session_id: str) -> None:
|
|
336
|
+
self._check_open()
|
|
337
|
+
if self._lookup_blocked:
|
|
338
|
+
# A replacement needs a lookup; refuse before the warm worker is retired.
|
|
339
|
+
raise SessionDirectoryUnavailable(
|
|
340
|
+
"an earlier chat-directory helper did not confirm exit; restart the MCP server"
|
|
341
|
+
)
|
|
342
|
+
slot = self._slots.get(session_id) or self._reserve(session_id)
|
|
343
|
+
self._check_not_busy(slot)
|
|
344
|
+
self._invalidate_preflights(session_id)
|
|
345
|
+
await asyncio.shield(self._start_lifecycle(slot, self._do_reset(slot)))
|
|
346
|
+
|
|
347
|
+
async def stop(self, session_id: str) -> None:
|
|
348
|
+
self._check_open()
|
|
349
|
+
slot = self._slots.get(session_id)
|
|
350
|
+
if slot is not None:
|
|
351
|
+
self._check_not_busy(slot)
|
|
352
|
+
# Claim before the first await: overlapping stops cannot both attempt
|
|
353
|
+
# the same path, and paths retained by this operation wait for the next.
|
|
354
|
+
claimed = self._claim_retained_spools()
|
|
355
|
+
self._invalidate_preflights(session_id)
|
|
356
|
+
try:
|
|
357
|
+
if slot is None:
|
|
358
|
+
# Accepted without a worker: a read that started earlier still
|
|
359
|
+
# belongs to a chat that has now been asked to stop.
|
|
360
|
+
return
|
|
361
|
+
await asyncio.shield(self._start_lifecycle(slot, self._do_stop(slot)))
|
|
362
|
+
finally:
|
|
363
|
+
self._drop_spools(claimed)
|
|
364
|
+
|
|
365
|
+
async def _do_reset(self, slot: _Slot) -> None:
|
|
366
|
+
try:
|
|
367
|
+
slot.state = SlotState.CLOSING
|
|
368
|
+
slot.generation += 1
|
|
369
|
+
await self._retire(slot)
|
|
370
|
+
if self._closed:
|
|
371
|
+
raise ShuttingDown("the server is shutting down")
|
|
372
|
+
kernel = self._new_kernel(slot.session_id)
|
|
373
|
+
slot.kernel = kernel
|
|
374
|
+
try:
|
|
375
|
+
await self._bind_workdir(slot, slot.kernel)
|
|
376
|
+
except SessionDirectoryUnavailable:
|
|
377
|
+
self._remove(slot)
|
|
378
|
+
raise
|
|
379
|
+
await self._start_kernel(slot, kernel)
|
|
380
|
+
self._arm_idle(slot)
|
|
381
|
+
except BaseException:
|
|
382
|
+
current = slot.kernel
|
|
383
|
+
if self._slots.get(slot.session_id) is slot and current.is_closed:
|
|
384
|
+
# The failed replacement rolled back and confirmed its exit, so
|
|
385
|
+
# it no longer owns capacity. An unconfirmed tree keeps the slot.
|
|
386
|
+
self._queue_retired_spool(current)
|
|
387
|
+
self._remove(slot)
|
|
388
|
+
raise
|
|
389
|
+
finally:
|
|
390
|
+
slot.lifecycle = None
|
|
391
|
+
|
|
392
|
+
async def _do_stop(self, slot: _Slot) -> None:
|
|
393
|
+
try:
|
|
394
|
+
slot.state = SlotState.CLOSING
|
|
395
|
+
slot.generation += 1
|
|
396
|
+
kernel = slot.kernel
|
|
397
|
+
await self._retire(slot)
|
|
398
|
+
if slot.kernel is not kernel:
|
|
399
|
+
# Defensive: a replacement must never survive a stop.
|
|
400
|
+
await self._retire(slot)
|
|
401
|
+
self._remove(slot)
|
|
402
|
+
finally:
|
|
403
|
+
slot.lifecycle = None
|
|
404
|
+
|
|
405
|
+
async def _retire(self, slot: _Slot) -> None:
|
|
406
|
+
kernel = slot.kernel
|
|
407
|
+
kernel.request_close()
|
|
408
|
+
confirmed = False
|
|
409
|
+
try:
|
|
410
|
+
await asyncio.shield(kernel.close())
|
|
411
|
+
confirmed = True
|
|
412
|
+
except CleanupIncomplete:
|
|
413
|
+
raise
|
|
414
|
+
except Exception as exc:
|
|
415
|
+
raise CleanupIncomplete(f"worker cleanup failed: {exc}") from exc
|
|
416
|
+
finally:
|
|
417
|
+
kernel.dispose()
|
|
418
|
+
# An unconfirmed tree still owns its files; only a clean close hands
|
|
419
|
+
# the failed path to the service for a later retry.
|
|
420
|
+
if confirmed:
|
|
421
|
+
retired = kernel.take_retired_spool()
|
|
422
|
+
if retired is not None:
|
|
423
|
+
self._retain_spool(retired)
|
|
424
|
+
|
|
425
|
+
# -- shutdown ----------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
async def close(self) -> None:
|
|
428
|
+
task = self._shutdown_task
|
|
429
|
+
if task is None:
|
|
430
|
+
self._closed = True
|
|
431
|
+
# No lookup may start another helper stage after shutdown began.
|
|
432
|
+
for abandoned in self._lookup_abandons:
|
|
433
|
+
abandoned.set()
|
|
434
|
+
# Termination starts synchronously, before this coroutine awaits:
|
|
435
|
+
# a startup waiter that becomes runnable afterwards cannot submit.
|
|
436
|
+
slots = list(self._slots.values())
|
|
437
|
+
for slot in slots:
|
|
438
|
+
self._cancel_idle(slot)
|
|
439
|
+
slot.kernel.request_close()
|
|
440
|
+
task = asyncio.get_running_loop().create_task(self._do_close(slots))
|
|
441
|
+
self._shutdown_task = task
|
|
442
|
+
cancelled = False
|
|
443
|
+
while not task.done():
|
|
444
|
+
try:
|
|
445
|
+
await asyncio.shield(task)
|
|
446
|
+
except asyncio.CancelledError:
|
|
447
|
+
# A leaving waiter never cancels the single shutdown owner; it
|
|
448
|
+
# still confirms bounded native exits before the loop unwinds.
|
|
449
|
+
cancelled = True
|
|
450
|
+
if cancelled:
|
|
451
|
+
raise asyncio.CancelledError
|
|
452
|
+
await task
|
|
453
|
+
|
|
454
|
+
async def _do_close(self, slots: list[_Slot]) -> None:
|
|
455
|
+
"""The single shutdown owner: join and sweep the snapshotted resources."""
|
|
456
|
+
# Capture the paths pending at admission; one attempt each, then drop.
|
|
457
|
+
known = self._claim_retained_spools()
|
|
458
|
+
# Helpers are owned but terminable; cancel them so shutdown does not
|
|
459
|
+
# wait for a filesystem deadline. Their cleanup confirms or reports exit.
|
|
460
|
+
for helper in [task for task in self._file_readers if not task.done()]:
|
|
461
|
+
helper.cancel()
|
|
462
|
+
try:
|
|
463
|
+
pending = [task for task in self._tasks if not task.done()]
|
|
464
|
+
if pending:
|
|
465
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
466
|
+
finally:
|
|
467
|
+
# Cancellation of the lifespan must not leave a ready worker's
|
|
468
|
+
# Job Object or transport open.
|
|
469
|
+
for slot in slots:
|
|
470
|
+
slot.kernel.force_release()
|
|
471
|
+
self._slots.clear()
|
|
472
|
+
self._drop_spools(known)
|
|
473
|
+
await asyncio.sleep(0)
|
|
474
|
+
|
|
475
|
+
# -- internals ---------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
def _retain_spool(self, path: Path) -> None:
|
|
478
|
+
"""Keep only a failed path, bounded like slots; never retain a worker."""
|
|
479
|
+
self._retained_spools.add(path)
|
|
480
|
+
while len(self._retained_spools) > self._config.max_sessions:
|
|
481
|
+
dropped = self._retained_spools.pop()
|
|
482
|
+
_LOGGER.warning("too many pending REPL capture directories; forgetting %s", dropped.name)
|
|
483
|
+
|
|
484
|
+
def _claim_retained_spools(self) -> set[Path]:
|
|
485
|
+
"""Synchronously take the paths pending at this operation's acceptance."""
|
|
486
|
+
claimed = set(self._retained_spools)
|
|
487
|
+
self._retained_spools -= claimed
|
|
488
|
+
return claimed
|
|
489
|
+
|
|
490
|
+
def _drop_spools(self, paths: set[Path]) -> None:
|
|
491
|
+
"""One attempt per claimed path; a still-locked path is logged and dropped."""
|
|
492
|
+
for path in sorted(paths):
|
|
493
|
+
try:
|
|
494
|
+
shutil.rmtree(path)
|
|
495
|
+
except FileNotFoundError:
|
|
496
|
+
continue
|
|
497
|
+
except OSError as exc:
|
|
498
|
+
_LOGGER.warning("could not remove REPL capture directory %s (%s)", path.name, type(exc).__name__)
|
|
499
|
+
|
|
500
|
+
def _new_kernel(self, session_id: str) -> Kernel:
|
|
501
|
+
return Kernel(session_id=session_id, config=self._config, on_dead=self._kernel_lost)
|
|
502
|
+
|
|
503
|
+
def _kernel_lost(self, kernel: Kernel) -> None:
|
|
504
|
+
"""An idle worker died: release its slot and spool without waiting for a call."""
|
|
505
|
+
for slot in self._slots.values():
|
|
506
|
+
if slot.kernel is kernel:
|
|
507
|
+
if not kernel.is_closing and not slot.lock.locked() and not self._lifecycle_active(slot):
|
|
508
|
+
self._retire_in_background(slot, kernel)
|
|
509
|
+
return
|
|
510
|
+
|
|
511
|
+
def _reserve(self, session_id: str) -> _Slot:
|
|
512
|
+
if len(self._slots) >= self._config.max_sessions:
|
|
513
|
+
raise CapacityExceeded(f"the server already owns {self._config.max_sessions} workers")
|
|
514
|
+
slot = _Slot(session_id=session_id, kernel=self._new_kernel(session_id))
|
|
515
|
+
self._slots[session_id] = slot
|
|
516
|
+
return slot
|
|
517
|
+
|
|
518
|
+
def _register_preflight(self, session_id: str) -> _Preflight:
|
|
519
|
+
"""Join the session's current file-read batch; the caller releases it in ``finally``."""
|
|
520
|
+
marker = self._preflights.get(session_id)
|
|
521
|
+
if marker is None:
|
|
522
|
+
marker = _Preflight()
|
|
523
|
+
self._preflights[session_id] = marker
|
|
524
|
+
marker.waiters += 1
|
|
525
|
+
return marker
|
|
526
|
+
|
|
527
|
+
def _release_preflight(self, session_id: str, marker: _Preflight) -> None:
|
|
528
|
+
marker.waiters -= 1
|
|
529
|
+
if marker.waiters == 0 and self._preflights.get(session_id) is marker:
|
|
530
|
+
del self._preflights[session_id]
|
|
531
|
+
|
|
532
|
+
def _invalidate_preflights(self, session_id: str) -> None:
|
|
533
|
+
"""Cut off the reads accepted before this lifecycle call.
|
|
534
|
+
|
|
535
|
+
The marker is removed, not mutated, so a read that starts later owns a
|
|
536
|
+
fresh marker while older waiters can only release their own object.
|
|
537
|
+
"""
|
|
538
|
+
self._preflights.pop(session_id, None)
|
|
539
|
+
|
|
540
|
+
async def _ensure_ready(
|
|
541
|
+
self,
|
|
542
|
+
slot: _Slot,
|
|
543
|
+
prepare: Callable[[Kernel], None] | None = None,
|
|
544
|
+
*,
|
|
545
|
+
resolved_workdir: Path | None = None,
|
|
546
|
+
) -> None:
|
|
547
|
+
kernel = slot.kernel
|
|
548
|
+
start = kernel.start_task
|
|
549
|
+
if kernel.is_closed or (
|
|
550
|
+
start is not None
|
|
551
|
+
and start.done()
|
|
552
|
+
and (start.cancelled() or start.exception() is not None or not kernel.is_ready)
|
|
553
|
+
):
|
|
554
|
+
# One selection point: retire the old worker and install a clean,
|
|
555
|
+
# not-yet-started kernel; the caller prepares it exactly once.
|
|
556
|
+
await self._retire(slot)
|
|
557
|
+
self._check_open()
|
|
558
|
+
self._ensure_current(slot)
|
|
559
|
+
kernel = self._replace(slot)
|
|
560
|
+
# The retired worker's directory is no longer a valid binding.
|
|
561
|
+
resolved_workdir = None
|
|
562
|
+
|
|
563
|
+
await self._bind_workdir(slot, kernel, resolved_workdir)
|
|
564
|
+
self._ensure_current(slot)
|
|
565
|
+
if prepare is not None:
|
|
566
|
+
prepare(kernel)
|
|
567
|
+
if not kernel.is_ready:
|
|
568
|
+
start = kernel.start_task
|
|
569
|
+
if start is None:
|
|
570
|
+
await self._start_kernel(slot, kernel)
|
|
571
|
+
elif not start.done():
|
|
572
|
+
await self._await_start(slot, kernel, start)
|
|
573
|
+
|
|
574
|
+
if slot.kernel is not kernel or not kernel.is_ready:
|
|
575
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
576
|
+
slot.state = SlotState.READY
|
|
577
|
+
|
|
578
|
+
async def _resolve_chat_workdir(self, session_id: str) -> Path:
|
|
579
|
+
opencode = self._config.opencode
|
|
580
|
+
if opencode is None:
|
|
581
|
+
return self._config.workdir
|
|
582
|
+
self._check_open()
|
|
583
|
+
if self._lookup_blocked:
|
|
584
|
+
raise SessionDirectoryUnavailable(
|
|
585
|
+
"an earlier chat-directory helper did not confirm exit; restart the MCP server"
|
|
586
|
+
)
|
|
587
|
+
loop = asyncio.get_running_loop()
|
|
588
|
+
deadline = loop.time() + self._config.handshake_timeout
|
|
589
|
+
abandoned = asyncio.Event()
|
|
590
|
+
# The permit wait is the caller's: a cancelled or expired call never
|
|
591
|
+
# leaves a helper queued to start later.
|
|
592
|
+
try:
|
|
593
|
+
await asyncio.wait_for(self._directory_lookups.acquire(), max(0.0, deadline - loop.time()))
|
|
594
|
+
except TimeoutError as exc:
|
|
595
|
+
raise SessionDirectoryUnavailable("the chat-directory lookup did not start in time") from exc
|
|
596
|
+
lookup = loop.create_task(self._lookup(opencode, session_id, deadline, abandoned))
|
|
597
|
+
self._lookup_abandons.add(abandoned)
|
|
598
|
+
lookup.add_done_callback(lambda _: self._lookup_abandons.discard(abandoned))
|
|
599
|
+
self._track(lookup)
|
|
600
|
+
# Ownership transferred: a leaving caller stops waiting, not the cleanup.
|
|
601
|
+
try:
|
|
602
|
+
return await asyncio.wait_for(asyncio.shield(lookup), max(0.0, deadline - loop.time()))
|
|
603
|
+
except TimeoutError as exc:
|
|
604
|
+
abandoned.set()
|
|
605
|
+
raise SessionDirectoryUnavailable("the chat-directory lookup did not finish in time") from exc
|
|
606
|
+
except asyncio.CancelledError:
|
|
607
|
+
abandoned.set()
|
|
608
|
+
raise
|
|
609
|
+
|
|
610
|
+
async def _lookup(
|
|
611
|
+
self,
|
|
612
|
+
opencode: OpenCode,
|
|
613
|
+
session_id: str,
|
|
614
|
+
deadline: float,
|
|
615
|
+
abandoned: asyncio.Event,
|
|
616
|
+
) -> Path:
|
|
617
|
+
try:
|
|
618
|
+
self._check_open()
|
|
619
|
+
if self._lookup_blocked:
|
|
620
|
+
raise SessionDirectoryUnavailable(
|
|
621
|
+
"an earlier chat-directory helper did not confirm exit; restart the MCP server"
|
|
622
|
+
)
|
|
623
|
+
hooks = self._config.hooks
|
|
624
|
+
before = hooks.before_helper_publish if hooks is not None else None
|
|
625
|
+
try:
|
|
626
|
+
return await opencode.workdir(
|
|
627
|
+
session_id,
|
|
628
|
+
self._config.workdir,
|
|
629
|
+
deadline=deadline,
|
|
630
|
+
abandoned=abandoned,
|
|
631
|
+
before_publish=before,
|
|
632
|
+
)
|
|
633
|
+
except ExitUnconfirmed:
|
|
634
|
+
# Fail closed: never launch another helper beside one that may
|
|
635
|
+
# still be alive. Warm chats keep working; new ones need a restart.
|
|
636
|
+
self._lookup_blocked = True
|
|
637
|
+
raise SessionDirectoryUnavailable(
|
|
638
|
+
"an earlier chat-directory helper did not confirm exit; restart the MCP server"
|
|
639
|
+
) from None
|
|
640
|
+
finally:
|
|
641
|
+
self._directory_lookups.release()
|
|
642
|
+
|
|
643
|
+
async def _bind_workdir(self, slot: _Slot, kernel: Kernel, resolved: Path | None = None) -> None:
|
|
644
|
+
if kernel.workdir is not None:
|
|
645
|
+
return
|
|
646
|
+
workdir = resolved or await self._resolve_chat_workdir(slot.session_id)
|
|
647
|
+
self._check_open()
|
|
648
|
+
if self._slots.get(slot.session_id) is not slot or slot.kernel is not kernel or kernel.is_closing:
|
|
649
|
+
raise StaleWorker("the worker was replaced while its chat directory was resolved")
|
|
650
|
+
kernel.workdir = workdir
|
|
651
|
+
|
|
652
|
+
def _replace(self, slot: _Slot) -> Kernel:
|
|
653
|
+
self._check_open()
|
|
654
|
+
self._cancel_idle(slot)
|
|
655
|
+
if self.pooled and slot.kernel.workdir is not None:
|
|
656
|
+
self._invalidate_preflights(slot.session_id)
|
|
657
|
+
kernel = self._new_kernel(slot.session_id)
|
|
658
|
+
slot.kernel = kernel
|
|
659
|
+
return kernel
|
|
660
|
+
|
|
661
|
+
async def _start_kernel(self, slot: _Slot, kernel: Kernel) -> None:
|
|
662
|
+
if self._slots.get(slot.session_id) is not slot:
|
|
663
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
664
|
+
slot.state = SlotState.STARTING
|
|
665
|
+
task = kernel.ensure_started()
|
|
666
|
+
self._track(task)
|
|
667
|
+
task.add_done_callback(lambda _: self._arm_started(slot, kernel))
|
|
668
|
+
await self._await_start(slot, kernel, task)
|
|
669
|
+
if not kernel.is_ready:
|
|
670
|
+
slot.state = SlotState.CLOSING
|
|
671
|
+
raise StartupFailed("the worker stopped during startup")
|
|
672
|
+
slot.state = SlotState.READY
|
|
673
|
+
|
|
674
|
+
async def _await_start(self, slot: _Slot, kernel: Kernel, task: asyncio.Task[None]) -> None:
|
|
675
|
+
try:
|
|
676
|
+
# The spawn owner keeps running; only the tool waiter is bounded.
|
|
677
|
+
await asyncio.wait_for(asyncio.shield(task), self._config.handshake_timeout)
|
|
678
|
+
except TimeoutError as exc:
|
|
679
|
+
slot.state = SlotState.CLOSING
|
|
680
|
+
kernel.request_close()
|
|
681
|
+
self._retire_failed_start(slot, kernel)
|
|
682
|
+
raise StartupFailed("the worker did not start within the handshake window") from exc
|
|
683
|
+
except CleanupIncomplete:
|
|
684
|
+
slot.state = SlotState.CLOSING
|
|
685
|
+
raise
|
|
686
|
+
except Exception as exc:
|
|
687
|
+
slot.state = SlotState.CLOSING
|
|
688
|
+
if isinstance(exc, KernelStartError):
|
|
689
|
+
raise StartupFailed(str(exc)) from exc
|
|
690
|
+
raise StartupFailed(f"the worker did not start: {exc}") from exc
|
|
691
|
+
|
|
692
|
+
def _reap(self, slot: _Slot, kernel: Kernel, *, background: bool = False) -> None:
|
|
693
|
+
if background and slot.lock.locked():
|
|
694
|
+
# A caller is currently retiring/replacing this slot; it owns the
|
|
695
|
+
# decision and the background close must not delete it underneath.
|
|
696
|
+
return
|
|
697
|
+
if self._slots.get(slot.session_id) is not slot or slot.kernel is not kernel:
|
|
698
|
+
return
|
|
699
|
+
if self._lifecycle_active(slot):
|
|
700
|
+
return
|
|
701
|
+
if kernel.is_closed:
|
|
702
|
+
self._remove(slot)
|
|
703
|
+
self._queue_retired_spool(kernel)
|
|
704
|
+
elif not kernel.is_ready:
|
|
705
|
+
slot.state = SlotState.CLOSING
|
|
706
|
+
if not background and not kernel.is_closed:
|
|
707
|
+
self._retire_in_background(slot, kernel)
|
|
708
|
+
|
|
709
|
+
def _release_closed_slot(self, slot: _Slot, generation: int) -> None:
|
|
710
|
+
"""Release capacity after a failed start whose rollback confirmed exit."""
|
|
711
|
+
if self._slots.get(slot.session_id) is not slot or slot.generation != generation:
|
|
712
|
+
return
|
|
713
|
+
if self._lifecycle_active(slot):
|
|
714
|
+
return
|
|
715
|
+
kernel = slot.kernel
|
|
716
|
+
if not kernel.is_closed:
|
|
717
|
+
# An unconfirmed tree still owns its slot and capture directory.
|
|
718
|
+
return
|
|
719
|
+
self._queue_retired_spool(kernel)
|
|
720
|
+
self._remove(slot)
|
|
721
|
+
|
|
722
|
+
def _retire_in_background(self, slot: _Slot, kernel: Kernel) -> None:
|
|
723
|
+
slot.state = SlotState.CLOSING
|
|
724
|
+
if self._slots.get(slot.session_id) is not slot or slot.kernel is not kernel:
|
|
725
|
+
return
|
|
726
|
+
task = kernel.close()
|
|
727
|
+
self._track(task)
|
|
728
|
+
task.add_done_callback(lambda _: self._reap(slot, kernel, background=True))
|
|
729
|
+
|
|
730
|
+
def _retire_failed_start(self, slot: _Slot, kernel: Kernel) -> None:
|
|
731
|
+
"""Release a lazily-created slot once its failed start has rolled back."""
|
|
732
|
+
if self._slots.get(slot.session_id) is not slot or slot.kernel is not kernel:
|
|
733
|
+
return
|
|
734
|
+
task = kernel.close()
|
|
735
|
+
self._track(task)
|
|
736
|
+
task.add_done_callback(lambda _: self._remove_failed_start(slot, kernel))
|
|
737
|
+
|
|
738
|
+
def _remove_failed_start(self, slot: _Slot, kernel: Kernel) -> None:
|
|
739
|
+
if (
|
|
740
|
+
self._slots.get(slot.session_id) is slot
|
|
741
|
+
and slot.kernel is kernel
|
|
742
|
+
and not self._lifecycle_active(slot)
|
|
743
|
+
and kernel.is_closed
|
|
744
|
+
):
|
|
745
|
+
self._remove(slot)
|
|
746
|
+
self._queue_retired_spool(kernel)
|
|
747
|
+
|
|
748
|
+
def _queue_retired_spool(self, kernel: Kernel) -> None:
|
|
749
|
+
retired = kernel.take_retired_spool()
|
|
750
|
+
if retired is not None:
|
|
751
|
+
self._retain_spool(retired)
|
|
752
|
+
|
|
753
|
+
def _start_lifecycle(self, slot: _Slot, operation: Coroutine[Any, Any, None]) -> asyncio.Task[None]:
|
|
754
|
+
task = asyncio.get_running_loop().create_task(operation)
|
|
755
|
+
slot.lifecycle = task
|
|
756
|
+
self._track(task)
|
|
757
|
+
return task
|
|
758
|
+
|
|
759
|
+
def _track(self, task: asyncio.Task[object]) -> None:
|
|
760
|
+
self._tasks.add(task)
|
|
761
|
+
|
|
762
|
+
def _done(finished: asyncio.Task[object]) -> None:
|
|
763
|
+
self._tasks.discard(finished)
|
|
764
|
+
if not finished.cancelled():
|
|
765
|
+
finished.exception()
|
|
766
|
+
|
|
767
|
+
task.add_done_callback(_done)
|
|
768
|
+
|
|
769
|
+
def _track_file_read(self, task: asyncio.Task[object]) -> None:
|
|
770
|
+
"""Track a terminable file-read owner; shutdown cancels it."""
|
|
771
|
+
self._file_readers.add(task)
|
|
772
|
+
task.add_done_callback(self._file_readers.discard)
|
|
773
|
+
self._track(task)
|
|
774
|
+
|
|
775
|
+
def _check_open(self) -> None:
|
|
776
|
+
if self._closed:
|
|
777
|
+
raise ShuttingDown("the server is shutting down")
|
|
778
|
+
|
|
779
|
+
def _ensure_current(self, slot: _Slot) -> None:
|
|
780
|
+
if self._slots.get(slot.session_id) is not slot:
|
|
781
|
+
raise StaleWorker("the worker was replaced while this call waited")
|
|
782
|
+
if self._lifecycle_active(slot):
|
|
783
|
+
raise StaleWorker("a lifecycle operation replaced the worker")
|
|
784
|
+
|
|
785
|
+
def _check_not_busy(self, slot: _Slot) -> None:
|
|
786
|
+
if self._lifecycle_active(slot):
|
|
787
|
+
raise SessionBusy("a lifecycle operation is in progress for this chat")
|
|
788
|
+
|
|
789
|
+
@staticmethod
|
|
790
|
+
def _lifecycle_active(slot: _Slot) -> bool:
|
|
791
|
+
return slot.lifecycle is not None and not slot.lifecycle.done()
|
|
792
|
+
|
|
793
|
+
def _discard_unstarted(self, slot: _Slot, generation: int) -> None:
|
|
794
|
+
"""Drop a current unstarted slot after preparation rejected the request."""
|
|
795
|
+
kernel = slot.kernel
|
|
796
|
+
if self._slots.get(slot.session_id) is not slot or slot.generation != generation:
|
|
797
|
+
return
|
|
798
|
+
if self._lifecycle_active(slot):
|
|
799
|
+
return
|
|
800
|
+
if kernel.start_task is not None or kernel.is_ready or kernel.is_closed:
|
|
801
|
+
return
|
|
802
|
+
kernel.dispose()
|
|
803
|
+
self._queue_retired_spool(kernel)
|
|
804
|
+
self._remove(slot)
|
|
805
|
+
|
|
806
|
+
def _cancel_idle(self, slot: _Slot) -> None:
|
|
807
|
+
if slot.idle_timer is not None:
|
|
808
|
+
slot.idle_timer.cancel()
|
|
809
|
+
slot.idle_timer = None
|
|
810
|
+
|
|
811
|
+
def _arm_idle(self, slot: _Slot) -> None:
|
|
812
|
+
"""Start the idle window for a ready, current worker."""
|
|
813
|
+
self._cancel_idle(slot)
|
|
814
|
+
if self._config.idle_timeout <= 0 or self._closed:
|
|
815
|
+
return
|
|
816
|
+
if self._slots.get(slot.session_id) is not slot:
|
|
817
|
+
return
|
|
818
|
+
if not slot.kernel.is_ready or slot.kernel.is_closing:
|
|
819
|
+
return
|
|
820
|
+
slot.idle_timer = asyncio.get_running_loop().call_later(
|
|
821
|
+
self._config.idle_timeout, self._idle_expired, slot, slot.generation
|
|
822
|
+
)
|
|
823
|
+
|
|
824
|
+
def _idle_expired(self, slot: _Slot, generation: int) -> None:
|
|
825
|
+
slot.idle_timer = None
|
|
826
|
+
# Give a cell already queued for this worker one loop turn to acquire
|
|
827
|
+
# the slot; only then claim the stop lifecycle synchronously.
|
|
828
|
+
asyncio.get_running_loop().call_soon(self._idle_claim, slot, generation)
|
|
829
|
+
|
|
830
|
+
def _idle_claim(self, slot: _Slot, generation: int) -> None:
|
|
831
|
+
if slot.idle_timer is not None:
|
|
832
|
+
# The worker completed and armed a fresh window after this claim
|
|
833
|
+
# was queued; the old expiry is stale.
|
|
834
|
+
return
|
|
835
|
+
if self._closed or self._slots.get(slot.session_id) is not slot or slot.generation != generation:
|
|
836
|
+
return
|
|
837
|
+
if slot.kernel.is_closing or not slot.kernel.is_ready:
|
|
838
|
+
return
|
|
839
|
+
if slot.lock.locked() or self._lifecycle_active(slot):
|
|
840
|
+
# A call or reset owns the slot; its completion re-arms the timer.
|
|
841
|
+
if not self._lifecycle_active(slot):
|
|
842
|
+
self._arm_idle(slot)
|
|
843
|
+
return
|
|
844
|
+
# Same-turn lifecycle claim: a later execute sees SessionBusy, never a
|
|
845
|
+
# killed cell. Idle eviction uses the explicit stop path.
|
|
846
|
+
claimed = self._claim_retained_spools()
|
|
847
|
+
|
|
848
|
+
async def operation() -> None:
|
|
849
|
+
try:
|
|
850
|
+
await self._do_stop(slot)
|
|
851
|
+
finally:
|
|
852
|
+
self._drop_spools(claimed)
|
|
853
|
+
|
|
854
|
+
self._start_lifecycle(slot, operation())
|
|
855
|
+
|
|
856
|
+
def _arm_started(self, slot: _Slot, kernel: Kernel) -> None:
|
|
857
|
+
"""Arm TTL after a service-owned start even if its waiter was cancelled."""
|
|
858
|
+
if self._slots.get(slot.session_id) is slot and slot.kernel is kernel and kernel.is_ready:
|
|
859
|
+
self._arm_idle(slot)
|
|
860
|
+
|
|
861
|
+
def _remove(self, slot: _Slot) -> None:
|
|
862
|
+
self._cancel_idle(slot)
|
|
863
|
+
if self._slots.get(slot.session_id) is slot:
|
|
864
|
+
del self._slots[slot.session_id]
|
|
865
|
+
if self.pooled and slot.kernel.workdir is not None:
|
|
866
|
+
self._invalidate_preflights(slot.session_id)
|