diff --git a/README.md b/README.md index 7f68ab17..3bbe3580 100644 --- a/README.md +++ b/README.md @@ -440,6 +440,28 @@ dagger call python-sdk mod --path my-module config set \ --base-image python:3.13-slim ``` +### Serve calls from one process + +A module can ask the engine to run its calls in one warm process per session, +which skips the interpreter start and the imports of every call after the +first: + +```toml +[tool.dagger] +serve = true +``` + +The setting takes effect at the next `dagger generate`, which adds a `serve` +member to the module's generated entrypoint. Only an engine that includes +module server support serves calls this way. On any other engine the module +keeps working, and every call runs in a new process. + +The process runs one call at a time. Before each call ends, it restores +`os.environ` and the working directory. Everything else persists into the +later calls of the same session and module: module globals, files written to +the container, and secrets a global holds. A call that finds the process busy +runs in a new process, so a call cannot rely on what an earlier call left. + ## Generate SDK files `dagger generate` regenerates every recorded scope. A recorded module can also diff --git a/dagger-module.toml b/dagger-module.toml index 1ae197c4..e7b1f000 100644 --- a/dagger-module.toml +++ b/dagger-module.toml @@ -7,7 +7,7 @@ source = "dang" [[dependencies]] name = "sdk-helpers" -source = "github.com/dagger/sdk-helpers@v1.0.10" +source = "github.com/dagger/sdk-helpers@v1.0.11" [[dependencies]] name = "python-sdk-runtime" diff --git a/dagger.lock b/dagger.lock index 38cdf5b6..15509dc5 100644 --- a/dagger.lock +++ b/dagger.lock @@ -4,12 +4,14 @@ [["version","2"]] ["","git-latest",["github.com/dagger/alpine"],"refs/heads/main"] ["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.10"]],"refs/tags/v1.0.10"] +["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.11"]],"refs/tags/v1.0.11"] ["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.8"]],"refs/tags/v1.0.8"] ["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.9"]],"refs/tags/v1.0.9"] ["","git-sha",["github.com/containernetworking/plugins","refs/tags/v1.9.0"],"9b3772e1a7abf93cbb7c6526a28bc0d27b830e02"] ["","git-sha",["github.com/dagger/alpine","main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"] ["","git-sha",["github.com/dagger/alpine","refs/heads/main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"] ["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.10"],"3d0cf3b4f6c901b288658421af8f2e3bbaebc663"] +["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.11"],"3be7456c40d9206b648ac44e418f30aa79bc6190"] ["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.8"],"31dafd0c74d9a08faa00c09dce87a5af072e7a9d"] ["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.9"],"daffbc01a1b3f3df7b1c417a7d2c83cd06d1bd33"] ["","git-sha",["github.com/libfuse/sshfs","refs/tags/sshfs-3.7.6"],"7a2d988775446ebe7af9b01c99b3b8e86bddb05a"] diff --git a/sdk/codegen/src/codegen/packages.py b/sdk/codegen/src/codegen/packages.py index d160168f..8b4a8175 100644 --- a/sdk/codegen/src/codegen/packages.py +++ b/sdk/codegen/src/codegen/packages.py @@ -51,6 +51,7 @@ SESSION_NAMES = frozenset( { "_as_session", + "_generation", "_loads", "_ready", "aclose", diff --git a/sdk/src/dagger/client/_session.py b/sdk/src/dagger/client/_session.py index adef1448..a7518126 100644 --- a/sdk/src/dagger/client/_session.py +++ b/sdk/src/dagger/client/_session.py @@ -61,9 +61,15 @@ def from_env(cls) -> "ConnectParams | None": raise ClientConnectionError(msg) from e +# A module server sets these per call, so that each call's requests reach the +# engine as that call's client, whichever session sends them. +request_headers: dict[str, str] = {} + + class TelemetryTransport(httpx.AsyncHTTPTransport): async def handle_async_request(self, request: httpx.Request) -> httpx.Response: propagate.inject(request.headers) + request.headers.update(request_headers) return await super().handle_async_request(request) @@ -365,6 +371,7 @@ def __init__(self, connection: BaseConnection | None = None) -> None: # set up: the session the generated global client builds is over it. self.connection = SharedConnection() if connection is None else connection self._loads: dict[str, _Load] = {} + self._generation = _load_generation @property def session(self) -> ClientSession: # type: ignore[override] @@ -406,6 +413,9 @@ def __getattr__(self, name: str) -> Any: async def load(self, target: "Target") -> None: """Serve the module a target names, once per session.""" + if self._generation != _load_generation: + self.forget() + self._generation = _load_generation entry = self._loads.setdefault(target.name, _Load(target)) if entry.target != target: # Whole descriptors: the two may differ only by pin, and the @@ -430,6 +440,17 @@ async def load(self, target: "Target") -> None: entry.done = True +# A module server runs each call as another engine client, which has loaded +# nothing, so it makes every session forget its loads between calls. +_load_generation = 0 + + +def forget_loads() -> None: + """Make every session load its targets again.""" + global _load_generation # noqa: PLW0603 + _load_generation += 1 + + _module_runtime = False diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index f0f27d2a..e748795c 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -2,19 +2,16 @@ import argparse import json -import logging import pathlib import sys +import tomllib from typing import Any import anyio from dagger import telemetry -from dagger._exceptions import QueryError from dagger.client._session import mark_module_runtime -from dagger.mod._exceptions import ModuleError - -logger = logging.getLogger(__package__) +from dagger.mod._exceptions import log_failure def main(argv: list[str] | None = None) -> int: @@ -58,15 +55,17 @@ def main(argv: list[str] | None = None) -> int: call.add_argument("--output", required=True, type=pathlib.Path) call.set_defaults(run=_call) + serve = commands.add_parser( + "serve", + help="import the module once and run the calls the engine sends, one at a time", + ) + serve.set_defaults(run=_serve) + args = parser.parse_args(argv) try: args.run(args) - except (ModuleError, QueryError) as e: - logger.error(str(e)) # noqa: TRY400 - the message is the whole story - return 2 - except Exception: - logger.exception("Unhandled exception") - return 1 + except Exception as e: # noqa: BLE001 - log_failure logs the traceback + return log_failure(e) return 0 @@ -83,9 +82,17 @@ def _entrypoint(args: argparse.Namespace) -> None: client_version=args.client_version, output=args.output, outside=args.outside, + serve=_opts_in_to_serve(pathlib.Path("pyproject.toml")), ) +def _opts_in_to_serve(pyproject: pathlib.Path) -> bool: + if not pyproject.is_file(): + return False + config = tomllib.loads(pyproject.read_text()).get("tool", {}).get("dagger", {}) + return config.get("serve") is True + + def _describe(args: argparse.Namespace) -> None: from dagger.client._descriptor import registering_types from dagger.mod._describe import describe_json @@ -108,6 +115,13 @@ def _call(args: argparse.Namespace) -> None: args.output.write_text(json.dumps(result)) +def _serve(_: argparse.Namespace) -> None: + from dagger.mod._serve import serve + from dagger.mod.cli import load_module + + serve(load_module()) + + async def _dispatch(request: dict[str, Any]) -> Any: from dagger.mod.cli import load_module diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 06ca546b..7cbe7ee7 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -18,18 +18,21 @@ HEADER = "# Code generated by dagger. DO NOT EDIT.\n" -def write_entrypoint( +def write_entrypoint( # noqa: PLR0913 desc: ModuleDescription, *, name: str, client_version: str, output: pathlib.Path, outside: Sequence[str] = (), + serve: bool = False, ) -> None: """Write types.dang and main.dang for the module.""" output.mkdir(parents=True, exist_ok=True) (output / "types.dang").write_text(render_types(desc)) - (output / "main.dang").write_text(render_main(name, client_version, outside)) + (output / "main.dang").write_text( + render_main(name, client_version, outside, serve=serve) + ) def render_types(desc: ModuleDescription) -> str: @@ -44,13 +47,20 @@ def render_types(desc: ModuleDescription) -> str: return "\n".join(lines) -def render_main(name: str, client_version: str, outside: Sequence[str] = ()) -> str: +def render_main( + name: str, + client_version: str, + outside: Sequence[str] = (), + *, + serve: bool = False, +) -> str: """Return the module and each directory outside it from sources. `client_version` is the engine release the module's code is generated for, which the entrypoint declares when it starts the module's process. `outside` holds the directories outside the module that its build reads, - relative to the module directory. + relative to the module directory. `serve` adds the member an engine + starts one warm module process from, for the module's calls in a session. """ return MAIN_TEMPLATE.format( header=HEADER, @@ -63,6 +73,7 @@ def render_main(name: str, client_version: str, outside: Sequence[str] = ()) -> for path in outside ), exclude=SOURCES_EXCLUDE, + serve=SERVE_MEMBER if serve else "", ) @@ -201,6 +212,14 @@ def _indent(lines: list[str], width: int) -> list[str]: SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]' +SERVE_MEMBER = """ pub serve: Container! { + runtime + .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .withDefaultArgs(["python", "-m", "dagger.mod", "serve"]) + } + +""" + MAIN_TEMPLATE = """{header} type Entrypoint implements ModuleEntrypoint {{ let moduleName: String! = {name} @@ -237,7 +256,7 @@ def _indent(lines: list[str], width: int) -> list[str]: (result :: JSON!) }} - let runtime: Container! {{ +{serve} let runtime: Container! {{ PythonModuleBuild( contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), subPath: currentModule.sourceSubpath, diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index e1a03712..82f47234 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -18,6 +18,18 @@ logger = logging.getLogger(__package__) +def log_failure(e: Exception) -> int: + """Log why a call or command failed and return its exit status. + + Call it from the except block, which gives the traceback. + """ + if isinstance(e, ModuleError | QueryError): + logger.error(str(e)) + return 2 + logger.exception("Unhandled exception") # noqa: LOG004 - called from an except block + return 1 + + class ModuleError(DaggerError): """Base class for all errors raised by modules. diff --git a/sdk/src/dagger/mod/_serve.py b/sdk/src/dagger/mod/_serve.py new file mode 100644 index 00000000..c37b383b --- /dev/null +++ b/sdk/src/dagger/mod/_serve.py @@ -0,0 +1,143 @@ +"""Serve a module's calls from one warm process, one call at a time. + +The engine connects to PORT once per call and sends one frame, ``C``, with +the call. The server answers with ``O`` and ``E`` frames, the call's output +on file descriptors 1 and 2, then one ``R`` frame with the result JSON or one +``X`` frame with the error message, and closes the connection. A frame is a +one-byte kind, a four-byte big-endian payload length, and the payload. +""" + +import base64 +import contextlib +import json +import os +import pathlib +import selectors +import socket +import sys +import threading +from collections.abc import Iterator +from typing import Any + +import anyio +from opentelemetry import context, propagate + +from dagger import telemetry +from dagger.client import _session +from dagger.mod._exceptions import log_failure +from dagger.mod._module import Module + +PORT = 8737 +# Long enough to drain a call's last output, short enough that a process the +# call left running, which still holds the pipes, does not stall the server. +DRAIN_SECONDS = 1.0 +# How soon a pump blocked on such a process notices that the call ended. +POLL_SECONDS = 0.05 + + +def serve(mod: Module) -> None: + """Listen only once the module is imported: a connection means ready.""" + telemetry.initialize() + with socket.create_server(("127.0.0.1", PORT)) as listener: + anyio.run(_serve_calls, mod, listener) + + +async def _serve_calls(mod: Module, listener: socket.socket) -> None: + while True: + conn, _ = await anyio.to_thread.run_sync(listener.accept) + with conn: + await serve_call(mod, conn) + + +async def serve_call(mod: Module, conn: socket.socket) -> None: + """Run the call conn sends, as the client it names, and answer on conn.""" + with conn.makefile("rb") as f: + head = f.read(5) + call = json.loads(f.read(int.from_bytes(head[1:], "big"))) + metadata = base64.b64encode(json.dumps({"client_id": call["clientID"]}).encode()) + channel = _Channel(conn) + environ, cwd = os.environ.copy(), pathlib.Path.cwd() + _session.request_headers["X-Dagger-Client-Metadata"] = metadata.decode() + token = context.attach(propagate.extract({"traceparent": call["traceparent"]})) + try: + with channel.capture(): + kind, payload = await _run(mod, call["request"]) + finally: + context.detach(token) + _session.request_headers.clear() + os.chdir(cwd) + os.environ.clear() + os.environ.update(environ) + channel.send(kind, payload, last=True) + + +async def _run(mod: Module, request: dict[str, Any]) -> tuple[bytes, bytes]: + try: + result = await mod.dispatch(request) + except Exception as e: # noqa: BLE001 - log_failure logs the traceback + log_failure(e) + return b"X", (str(e) or type(e).__name__).encode() + finally: + # The next call is another client, which has loaded nothing, so every + # session must load again, including one a global holds. + await _session.default_session().close() + _session.forget_loads() + telemetry.flush() + return b"R", json.dumps(result).encode() + + +class _Channel: + def __init__(self, conn: socket.socket): + self._conn = conn + self._lock = threading.Lock() + self._open = True + + def send(self, kind: bytes, payload: bytes, *, last: bool = False) -> None: + with self._lock: + if self._open: + self._conn.sendall(kind + len(payload).to_bytes(4, "big") + payload) + self._open = self._open and not last + + @contextlib.contextmanager + def capture(self) -> Iterator[None]: + """Send fds 1 and 2 as frames, so subprocess output goes out too.""" + for stream in (sys.stdout, sys.stderr): + stream.flush() + saved = [os.dup(1), os.dup(2)] + stop = threading.Event() + pumps = [self._pump(1, b"O", stop), self._pump(2, b"E", stop)] + try: + yield + finally: + for stream in (sys.stdout, sys.stderr): + stream.flush() + for fd, old in zip((1, 2), saved, strict=True): + os.dup2(old, fd) + os.close(old) + for pump in pumps: + pump.join(DRAIN_SECONDS) + stop.set() + for pump in pumps: + pump.join() + + def _pump(self, fd: int, kind: bytes, stop: threading.Event) -> threading.Thread: + read, write = os.pipe() + os.dup2(write, fd) + os.close(write) + pump = threading.Thread(target=self._forward, args=(read, kind, stop)) + pump.start() + return pump + + def _forward(self, read: int, kind: bytes, stop: threading.Event) -> None: + # A selector, not select(), which refuses descriptors from 1024 up. + try: + with selectors.DefaultSelector() as selector, contextlib.suppress(OSError): + selector.register(read, selectors.EVENT_READ) + while not stop.is_set(): + if not selector.select(POLL_SECONDS): + continue + if not (chunk := os.read(read, 65536)): + break + self.send(kind, chunk) + finally: + os.close(read) diff --git a/sdk/src/dagger/telemetry.py b/sdk/src/dagger/telemetry.py index 992ca9a9..9c49a94a 100644 --- a/sdk/src/dagger/telemetry.py +++ b/sdk/src/dagger/telemetry.py @@ -28,6 +28,7 @@ from opentelemetry.trace import get_tracer_provider, propagation __all__ = [ + "flush", "get_tracer", "initialize", "otel_configured", @@ -68,6 +69,13 @@ def shutdown(): tracer_provider.shutdown() +def flush(): + """Export the spans that have ended, keeping the provider running.""" + tracer_provider = get_tracer_provider() + if isinstance(tracer_provider, sdktrace.TracerProvider): + tracer_provider.force_flush() + + def otel_configured() -> bool: """Checks for OpenTelemetry configuration via OTEL_ environment variables.""" return any(k for k in os.environ if k.startswith("OTEL_")) diff --git a/sdk/tests/mod/golden/main_serve.dang b/sdk/tests/mod/golden/main_serve.dang new file mode 100644 index 00000000..f31764ea --- /dev/null +++ b/sdk/tests/mod/golden/main_serve.dang @@ -0,0 +1,51 @@ +# Code generated by dagger. DO NOT EDIT. + +type Entrypoint implements ModuleEntrypoint { + let moduleName: String! = "main" + let clientVersion: String! = "v1.0.0-beta.24" + + pub sources(workspace: Workspace!): Directory! { + directory + .withDirectory(workspace.cwd, workspace.directory(".", exclude: ["**/.git", "**/.venv", "**/__pycache__"], gitignore: true)) + } + + pub types: [TypeDef!]! { + ModuleTypes().all + } + + pub call( + receiverType: String!, + receiverValue: JSON, + fnName: String!, + fnArgs: JSON!, + callDigest: String, + ): JSON! { + let request = JSON.encode({{ + receiverType: receiverType, + receiverValue: receiverValue, + fnName: fnName, + fnArgs: fnArgs, + }}) + let result = runtime + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") + .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .withExec(["python", "-m", "dagger.mod", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) + .file("/dagger/result.json") + .contents + (result :: JSON!) + } + + pub serve: Container! { + runtime + .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .withDefaultArgs(["python", "-m", "dagger.mod", "serve"]) + } + + let runtime: Container! { + PythonModuleBuild( + contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), + subPath: currentModule.sourceSubpath, + moduleName: moduleName, + ).installed + } +} diff --git a/sdk/tests/mod/test_entrypoint.py b/sdk/tests/mod/test_entrypoint.py index a3949452..a8c4c5e7 100644 --- a/sdk/tests/mod/test_entrypoint.py +++ b/sdk/tests/mod/test_entrypoint.py @@ -104,6 +104,10 @@ def test_main_outside_golden(): _assert_golden("main_outside.dang", rendered) +def test_main_serve_golden(): + _assert_golden("main_serve.dang", render_main("main", "v1.0.0-beta.24", serve=True)) + + def test_main_declares_client_version(): rendered = render_main("main", 'v1.0.0-beta.24+"commit"') assert 'let clientVersion: String! = "v1.0.0-beta.24+\\"commit\\""' in rendered @@ -163,14 +167,27 @@ def test_write_entrypoint(mod: Module, tmp_path: pathlib.Path): @pytest.mark.parametrize( - ("args", "outside"), + ("args", "outside", "config", "serves"), [ - ([], []), - (["--outside=../lib", "--outside=../../shared"], ["../lib", "../../shared"]), + ([], [], "", False), + ( + ["--outside=../lib", "--outside=../../shared"], + ["../lib", "../../shared"], + "", + False, + ), + ([], [], "[tool.dagger]\nserve = true\n", True), + ([], [], "[tool.dagger]\nserve = false\n", False), ], ) -def test_command(tmp_path: pathlib.Path, args: list[str], outside: list[str]): - (tmp_path / "pyproject.toml").write_text('[project]\nname = "hello"\n') +def test_command( + tmp_path: pathlib.Path, + args: list[str], + outside: list[str], + config: str, + serves: bool, +): + (tmp_path / "pyproject.toml").write_text(f'[project]\nname = "hello"\n{config}') pkg = tmp_path / "src" / "hello" pkg.mkdir(parents=True) (pkg / "__init__.py").write_text( @@ -210,3 +227,4 @@ def test_command(tmp_path: pathlib.Path, args: list[str], outside: list[str]): assert main.count("workspace.directory(") == len(outside) + 1 for path in outside: assert f'workspace.directory("{path}", ' in main + assert ("pub serve: Container!" in main) is serves diff --git a/sdk/tests/mod/test_serve.py b/sdk/tests/mod/test_serve.py new file mode 100644 index 00000000..1629d7e8 --- /dev/null +++ b/sdk/tests/mod/test_serve.py @@ -0,0 +1,208 @@ +import base64 +import fcntl +import json +import os +import pathlib +import resource +import socket +import subprocess +import sys +import threading +import time + +import httpx +import pytest +from opentelemetry import trace + +from dagger.client import _load, _session +from dagger.client._descriptor import Target +from dagger.mod import Module, _serve +from dagger.mod._serve import serve_call + +pytestmark = pytest.mark.anyio + +TRACE_ID = "4bf92f3577b34da6a3ce929d0e0e4736" +GLOBAL_SESSION = _session.Session() +LINGERING: list[subprocess.Popen] = [] + + +@pytest.fixture +def mod() -> Module: + m = Module("Foo") + + @m.object_type + class Foo: + @m.function + def talk(self) -> str: + os.write(1, b"to stdout ") + subprocess.run( + [sys.executable, "-c", "import os; os.write(2, b'from a child')"], + check=True, + ) + return "said" + + @m.function + def mess(self) -> dict[str, str]: + os.environ["LEFT_BEHIND"] = "yes" + os.chdir("/") + span = trace.get_current_span().get_span_context() + return { + "header": _session.request_headers["X-Dagger-Client-Metadata"], + "trace": format(span.trace_id, "032x"), + } + + @m.function + async def load(self) -> str: + await GLOBAL_SESSION.load(Target("dep", "github.com/x/dep")) + return "loaded" + + @m.function + def linger(self) -> str: + LINGERING.append(subprocess.Popen(["sleep", "30"])) + return "left" + + @m.function + def fail(self) -> str: + msg = "broken" + raise ValueError(msg) + + return m + + +async def _call(mod: Module, fn: str) -> list[tuple[bytes, bytes]]: + call = json.dumps( + { + "request": { + "receiverType": "Foo", + "receiverValue": None, + "fnName": fn, + "fnArgs": "{}", + }, + "clientID": "call-1", + "traceparent": f"00-{TRACE_ID}-00f067aa0ba902b7-01", + } + ).encode() + engine, server = socket.socketpair() + with engine, server: + engine.sendall(b"C" + len(call).to_bytes(4, "big") + call) + await serve_call(mod, server) + server.shutdown(socket.SHUT_WR) + data = b"".join(iter(lambda: engine.recv(65536), b"")) + frames = [] + while data: + size = int.from_bytes(data[1:5], "big") + frames.append((data[:1], data[5 : 5 + size])) + data = data[5 + size :] + return frames + + +def _output(frames: list[tuple[bytes, bytes]], kind: bytes) -> bytes: + return b"".join(payload for k, payload in frames if k == kind) + + +async def test_sends_output_then_result(mod: Module): + frames = await _call(mod, "talk") + assert _output(frames, b"O") == b"to stdout " + assert _output(frames, b"E") == b"from a child" + assert frames[-1] == (b"R", b'"said"') + assert [k for k, _ in frames].count(b"R") == 1 + + +async def test_binds_the_call_and_restores_the_process( + mod: Module, monkeypatch: pytest.MonkeyPatch +): + session = _session.default_session() + forgotten = [] + monkeypatch.setattr(session, "forget", lambda: forgotten.append(session)) + cwd = pathlib.Path.cwd() + + kind, payload = (await _call(mod, "mess"))[-1] + + assert kind == b"R" + result = json.loads(payload) + assert json.loads(base64.b64decode(result["header"])) == {"client_id": "call-1"} + assert result["trace"] == TRACE_ID + assert _session.request_headers == {} + assert "LEFT_BEHIND" not in os.environ + assert pathlib.Path.cwd() == cwd + assert forgotten == [session] + assert _session.default_session() is session + + +async def test_error_keeps_serving(mod: Module): + assert (await _call(mod, "fail"))[-1] == (b"X", b"broken") + assert (await _call(mod, "talk"))[-1] == (b"R", b'"said"') + + +async def test_transport_sends_request_headers(monkeypatch: pytest.MonkeyPatch): + sent = [] + + async def handle(_, request: httpx.Request) -> httpx.Response: + sent.append(request.headers.get("X-Test")) + return httpx.Response(200) + + monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handle) + monkeypatch.setitem(_session.request_headers, "X-Test", "bound") + transport = _session.TelemetryTransport() + await transport.handle_async_request(httpx.Request("POST", "http://x/query")) + assert sent == ["bound"] + + +async def test_every_session_loads_again(mod: Module, monkeypatch: pytest.MonkeyPatch): + loaded = [] + + async def load_target(session, target): + loaded.append((session, target.name)) + + monkeypatch.setattr(_load, "load_target", load_target) + await _call(mod, "load") + await _call(mod, "load") + assert loaded == [(GLOBAL_SESSION, "dep")] * 2 + + +def _open_fds() -> list[pathlib.Path]: + return sorted(pathlib.Path("/proc/self/fd").iterdir()) + + +async def test_process_left_running_releases_the_pumps( + mod: Module, monkeypatch: pytest.MonkeyPatch +): + monkeypatch.setattr(_serve, "DRAIN_SECONDS", 0.1) + # The worker thread a sync function runs in outlives its call. + await _call(mod, "talk") + threads, fds = threading.active_count(), _open_fds() + started = time.monotonic() + try: + assert (await _call(mod, "linger"))[-1] == (b"R", b'"left"') + assert time.monotonic() - started < 5 + assert threading.active_count() == threads + assert _open_fds() == fds + finally: + for proc in LINGERING: + proc.kill() + proc.wait() + + +async def test_output_from_a_descriptor_above_1024( + mod: Module, monkeypatch: pytest.MonkeyPatch +): + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + if hard != resource.RLIM_INFINITY and hard < 2048: + pytest.skip("cannot open descriptors above 1024") + pipe = os.pipe + + def high_pipe() -> tuple[int, int]: + read, write = pipe() + high = fcntl.fcntl(read, fcntl.F_DUPFD_CLOEXEC, 1024) + os.close(read) + return high, write + + resource.setrlimit(resource.RLIMIT_NOFILE, (2048, hard)) + try: + with monkeypatch.context() as patched: + patched.setattr(_serve.os, "pipe", high_pipe) + frames = await _call(mod, "talk") + finally: + resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard)) + assert _output(frames, b"O") == b"to stdout " + assert _output(frames, b"E") == b"from a child"