Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

perf(core): share one TLS context across every httpx client

rubenluetke10-beep28b7e8a8d56b
diff --git a/jarvis/__init__.py b/jarvis/__init__.py
index 0e0bc778a1..2b7efeb011 100644
--- a/jarvis/__init__.py
+++ b/jarvis/__init__.py
@@ -1,3 +1,11 @@
"""Personal Jarvis — a voice-driven, cross-platform meta-orchestrator."""
__version__ = "2.3.2"
+
+# Every httpx client in the process shares one parsed CA bundle instead of
+# re-parsing it (~200 ms of CPU) per client. Patches httpx lazily, the moment
+# it is first imported; importing ``jarvis`` itself still loads nothing heavy.
+from jarvis.core.shared_tls import install_when_imported as _install_shared_tls
+
+_install_shared_tls()
+del _install_shared_tls
diff --git a/jarvis/core/shared_tls.py b/jarvis/core/shared_tls.py
new file mode 100644
index 0000000000..48970aa874
--- /dev/null
+++ b/jarvis/core/shared_tls.py
@@ -0,0 +1,174 @@
+"""One verified TLS context per process, shared by every httpx client.
+
+An ``httpx`` transport built with the default ``verify=True`` calls
+``ssl.create_default_context(cafile=certifi.where())``, which parses the whole
+certifi bundle (~230 KB of PEM) into a fresh OpenSSL store. Measured on the
+maintainer box: ~200 ms of CPU for EVERY ``httpx.Client`` / ``AsyncClient`` —
+and for every SDK client built on top of one (openai, anthropic, ...). The
+system store alone costs ~15 ms; the certifi parse is the whole bill.
+
+The app builds clients in dozens of places, many of them per request and many
+of them ON the backend event loop. Under memory pressure that parse is where
+the loop sat: six of the 22 "Event loop STALLED for 15 s" reports in the
+desktop log (2026-09-28 .. 10-02) end in ``create_ssl_context``. One shared
+context makes the second and every later client free.
+
+Sharing is safe because the context is never handed out for mutation:
+
+* Only the default case is shared — ``verify=True`` and no client certificate.
+ An explicit ``SSLContext``, ``verify=False`` or ``cert=...`` is passed
+ through untouched.
+* ``SSL_CERT_FILE`` / ``SSL_CERT_DIR`` (honoured by httpx when ``trust_env``)
+ are part of the cache key, so changing them still takes effect.
+* httpcore calls ``set_alpn_protocols`` on the context before EVERY connection.
+ On a context shared across threads that is a write racing other threads'
+ ``SSL_new`` (CPython releases the GIL there). Each context is therefore built
+ for one ALPN list (HTTP/1.1, or HTTP/1.1 + h2) and ignores a repeated write
+ of the same list, so the shared object is never written after creation.
+
+:func:`install_when_imported` wires this into httpx without importing it: it
+patches ``httpx.HTTPTransport`` / ``AsyncHTTPTransport`` right after httpx is
+first imported. ``jarvis/__init__.py`` calls it, so every process that imports
+the package — desktop app, background service, CLI, mission workers — gets it.
+The patch checks the transport signature first (AP-28: capability, not
+version); an httpx that no longer matches is left alone and simply pays the
+old per-client cost.
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import sys
+import threading
+from typing import TYPE_CHECKING, Any, Final
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ import ssl
+ from types import ModuleType
+
+#: Transport parameters the patch reads; a transport lacking any is left alone.
+_REQUIRED_PARAMS: Final[frozenset[str]] = frozenset({"verify", "cert", "trust_env", "http2"})
+_PATCHED_MARK: Final[str] = "_jarvis_shared_tls"
+
+_lock = threading.Lock()
+_contexts: dict[tuple[bool, str | None, str | None], ssl.SSLContext] = {}
+
+
+def shared_ssl_context(*, http2: bool = False, trust_env: bool = True) -> ssl.SSLContext:
+ """The process-wide default client context for this ALPN shape.
+
+ Built exactly the way httpx builds its default (same trust store, same
+ ``SSL_CERT_FILE`` / ``SSL_CERT_DIR`` handling), once per key.
+ """
+ cafile = (os.environ.get("SSL_CERT_FILE") or None) if trust_env else None
+ capath = (os.environ.get("SSL_CERT_DIR") or None) if trust_env else None
+ key = (bool(http2), cafile, capath)
+ ctx = _contexts.get(key)
+ if ctx is not None:
+ return ctx
+ with _lock:
+ ctx = _contexts.get(key)
+ if ctx is None:
+ import httpx
+
+ ctx = httpx.create_ssl_context(verify=True, trust_env=trust_env)
+ _pin_alpn(ctx, ["http/1.1", "h2"] if http2 else ["http/1.1"])
+ _contexts[key] = ctx
+ return ctx
+
+
+def _pin_alpn(ctx: ssl.SSLContext, protocols: list[str]) -> None:
+ """Set the ALPN list once and turn repeats of the same list into no-ops."""
+ ctx.set_alpn_protocols(protocols)
+ original = ctx.set_alpn_protocols
+
+ def set_alpn_protocols(requested: Any) -> None:
+ if list(requested) != protocols:
+ # Never happens through httpcore (the key carries the http2 flag);
+ # a foreign caller still gets the list it asked for.
+ original(requested)
+
+ # Instance attribute: shadows the method for this one context only.
+ ctx.set_alpn_protocols = set_alpn_protocols # type: ignore[method-assign]
+
+
+def _patch_transport(cls: type) -> bool:
+ """Route ``cls``'s default ``verify=True`` to the shared context."""
+ init = cls.__init__
+ if getattr(init, _PATCHED_MARK, False):
+ return True
+ import inspect # lazy: this module is imported with the bare ``jarvis`` package
+
+ try:
+ params = inspect.signature(init).parameters
+ except (TypeError, ValueError):
+ return False
+ if not _REQUIRED_PARAMS <= params.keys():
+ return False
+
+ @functools.wraps(init)
+ def __init__(self: Any, *args: Any, **kwargs: Any) -> None: # noqa: N807
+ # httpx passes every transport argument by keyword; anything else is
+ # a caller we do not understand, so it keeps the stock behaviour.
+ if not args and kwargs.get("verify", True) is True and kwargs.get("cert") is None:
+ kwargs["verify"] = shared_ssl_context(
+ http2=bool(kwargs.get("http2", False)),
+ trust_env=bool(kwargs.get("trust_env", True)),
+ )
+ init(self, *args, **kwargs)
+
+ setattr(__init__, _PATCHED_MARK, True)
+ cls.__init__ = __init__ # type: ignore[method-assign]
+ return True
+
+
+def install(httpx_module: ModuleType) -> bool:
+ """Patch an imported httpx; ``False`` when it lacks what the patch needs."""
+ if not callable(getattr(httpx_module, "create_ssl_context", None)):
+ return False
+ patched = False
+ for name in ("HTTPTransport", "AsyncHTTPTransport"):
+ cls = getattr(httpx_module, name, None)
+ if isinstance(cls, type):
+ patched = _patch_transport(cls) or patched
+ return patched
+
+
+class _InstallOnImport:
+ """One-shot ``sys.meta_path`` finder: patch httpx right after it loads."""
+
+ def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any:
+ if fullname != "httpx":
+ return None
+ try:
+ sys.meta_path.remove(self)
+ except ValueError:
+ pass # another thread's import already took it out; resolve normally
+ from importlib.util import find_spec
+
+ spec = find_spec(fullname)
+ loader = getattr(spec, "loader", None)
+ exec_module = getattr(loader, "exec_module", None)
+ if exec_module is None:
+ return spec
+
+ def exec_and_install(module: ModuleType) -> None:
+ exec_module(module)
+ install(module)
+
+ loader.exec_module = exec_and_install # type: ignore[union-attr]
+ return spec
+
+
+def install_when_imported() -> None:
+ """Patch httpx now if it is loaded, else the moment it first is."""
+ module = sys.modules.get("httpx")
+ if module is not None:
+ install(module)
+ return
+ if not any(isinstance(finder, _InstallOnImport) for finder in sys.meta_path):
+ sys.meta_path.insert(0, _InstallOnImport())
+
+
+__all__ = ["install", "install_when_imported", "shared_ssl_context"]
diff --git a/tests/unit/core/test_shared_tls.py b/tests/unit/core/test_shared_tls.py
new file mode 100644
index 0000000000..6c1e88a359
--- /dev/null
+++ b/tests/unit/core/test_shared_tls.py
@@ -0,0 +1,138 @@
+"""The process-wide TLS context httpx transports share (jarvis.core.shared_tls)."""
+
+from __future__ import annotations
+
+import ssl
+import sys
+
+import httpx
+import pytest
+
+from jarvis.core import shared_tls
+
+
+class _FakeTransport:
+ """Mirrors the keyword signature of httpx's transports."""
+
+ def __init__(
+ self,
+ verify: object = True,
+ cert: object = None,
+ trust_env: bool = True,
+ http1: bool = True,
+ http2: bool = False,
+ ) -> None:
+ self.verify = verify
+
+
+def fake_transport() -> type[_FakeTransport]:
+ cls = type("PatchedFake", (_FakeTransport,), {})
+ assert shared_tls._patch_transport(cls)
+ return cls
+
+
[email protected](autouse=True)
+def _no_cert_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SSL_CERT_FILE", raising=False)
+ monkeypatch.delenv("SSL_CERT_DIR", raising=False)
+
+
+def test_default_verify_gets_one_shared_context(fake_transport) -> None:
+ first = fake_transport(verify=True, http2=False)
+ second = fake_transport(http2=False)
+ assert isinstance(first.verify, ssl.SSLContext)
+ assert first.verify is second.verify
+ assert first.verify.verify_mode == ssl.CERT_REQUIRED
+ assert first.verify.check_hostname
+
+
+def test_http2_clients_get_their_own_context(fake_transport) -> None:
+ h1 = fake_transport(http2=False)
+ h2 = fake_transport(http2=True)
+ assert h1.verify is not h2.verify
+
+
+def test_explicit_choices_pass_through(fake_transport) -> None:
+ custom = ssl.create_default_context()
+ assert fake_transport(verify=False).verify is False
+ assert fake_transport(verify=custom).verify is custom
+ assert fake_transport(verify=True, cert="client.pem").verify is True
+ assert fake_transport(True).verify is True # positional caller: stock path
+
+
+def test_cert_env_vars_are_part_of_the_key(fake_transport, monkeypatch) -> None:
+ import certifi
+
+ plain = fake_transport().verify
+ monkeypatch.setenv("SSL_CERT_FILE", certifi.where())
+ from_env = fake_transport().verify
+ ignored_env = fake_transport(trust_env=False).verify
+ assert from_env is not plain
+ assert ignored_env is plain
+
+
+def test_repeated_alpn_write_never_touches_the_shared_context(monkeypatch) -> None:
+ ctx = ssl.create_default_context()
+ writes: list[list[str]] = []
+ original = ctx.set_alpn_protocols
+ ctx.set_alpn_protocols = lambda p: (writes.append(list(p)), original(p)) # type: ignore[method-assign]
+ shared_tls._pin_alpn(ctx, ["http/1.1"])
+ ctx.set_alpn_protocols(["http/1.1"])
+ ctx.set_alpn_protocols(["http/1.1"])
+ assert writes == [["http/1.1"]]
+ ctx.set_alpn_protocols(["http/1.1", "h2"]) # a foreign shape still applies
+ assert writes[-1] == ["http/1.1", "h2"]
+
+
+def test_patch_is_idempotent_and_capability_gated() -> None:
+ cls = type("Twice", (_FakeTransport,), {})
+ assert shared_tls._patch_transport(cls)
+ patched_init = cls.__init__
+ assert shared_tls._patch_transport(cls)
+ assert cls.__init__ is patched_init
+
+ class _Unknown:
+ def __init__(self, verify: object = True) -> None:
+ self.verify = verify
+
+ stock_init = _Unknown.__init__
+ assert not shared_tls._patch_transport(_Unknown)
+ assert _Unknown.__init__ is stock_init
+
+
+def test_install_skips_an_httpx_without_create_ssl_context() -> None:
+ module = type(sys)("fake_httpx")
+ module.HTTPTransport = type("HTTPTransport", (_FakeTransport,), {})
+ stock_init = module.HTTPTransport.__init__
+ assert not shared_tls.install(module)
+ assert module.HTTPTransport.__init__ is stock_init
+
+
+def test_real_httpx_is_patched_once_jarvis_is_imported() -> None:
+ import jarvis # noqa: F401 — the import installs the patch
+
+ assert getattr(httpx.HTTPTransport.__init__, shared_tls._PATCHED_MARK, False)
+ assert getattr(httpx.AsyncHTTPTransport.__init__, shared_tls._PATCHED_MARK, False)
+ with httpx.Client() as a, httpx.Client() as b:
+ # Building clients must not fail and must not re-parse the CA bundle;
+ # the shared context is what the default path now resolves to.
+ assert a is not b
+ assert shared_tls.shared_ssl_context() is shared_tls.shared_ssl_context()
+
+
+def test_import_hook_patches_httpx_on_first_import(monkeypatch) -> None:
+ finder = shared_tls._InstallOnImport()
+ installed: list[object] = []
+ monkeypatch.setattr(shared_tls, "install", installed.append)
+ monkeypatch.setattr(sys, "meta_path", [finder, *sys.meta_path])
+ monkeypatch.delitem(sys.modules, "httpx")
+
+ spec = finder.find_spec("httpx")
+ assert finder not in sys.meta_path # one-shot
+ from importlib.util import module_from_spec
+
+ module = module_from_spec(spec)
+ spec.loader.exec_module(module)
+ assert installed == [module]
+ assert finder.find_spec("not_httpx") is None