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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(config): stop re-parsing jarvis.toml on the event loop
Ruben Lütke9da6d85c6baa
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex f4ea467974..c3e0ea0bc0 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2738,7 +2738,76 @@ class JarvisConfig(BaseModel):# Loading logic# ----------------------------------------------------------------------+#: Parsed ``jarvis.toml`` payloads, keyed by path → (identity, data).+#:+#: ``load_config`` is called from over a hundred sites, several of them on the+#: event loop that also serves every WebSocket — a provider building its client+#: calls it per instantiation, and a fallback chain instantiates several+#: providers per turn. Re-reading and re-parsing a 50 KB TOML there costs ~8 ms+#: of blocked loop each time, and far worse than the milliseconds: ``tomllib``+#: allocates thousands of short-lived objects per parse, so in a long-running+#: process holding a large object graph the garbage collector starts dominating+#: and a single parse can stall for minutes. Measured live 2026-07-28: the+#: backend thread sat in ``tomllib`` at a fixed byte offset for over ten+#: minutes at 88 % of a core with ``/api/health`` timing out, while the very+#: same file parsed in 8 ms in a fresh process. The window title said+#: "Not responding" and keystrokes typed into an Agentic-IDE pane arrived+#: seconds late, because they queue behind this on the one loop.+_TOML_CACHE: dict[Path, tuple[tuple[int, int], dict[str, Any]]] = {}+_TOML_CACHE_LOCK = threading.Lock()+++def _copy_toml_data(value: Any) -> Any:+ """Structural copy of a parsed TOML payload.++ Handing out the cached object itself is not an option: ``_apply_env_overrides``+ writes overrides straight into the dict it is given, so the cache would+ accumulate every override ever applied and answer later callers with a+ config that was never on disk.++ A hand-rolled walk rather than ``copy.deepcopy`` because TOML yields only+ dicts, lists and immutable scalars (including ``datetime``), so none of+ deepcopy's memo bookkeeping or ``__deepcopy__`` dispatch buys anything here+ — and it is what keeps the copy cheap enough to be worth caching at all+ (0.10 ms against 0.73 ms and an 8.18 ms parse).+ """+ if type(value) is dict:+ return {key: _copy_toml_data(item) for key, item in value.items()}+ if type(value) is list:+ return [_copy_toml_data(item) for item in value]+ return value+++def clear_config_cache() -> None:+ """Forget every parsed TOML payload.++ The cache invalidates itself off the file's identity, so this exists for+ the two cases that identity cannot see: a test that rewrites a fixture+ within one filesystem timestamp tick, and :mod:`jarvis.core.config_writer`+ announcing a write it just made rather than waiting to be found out.+ """+ with _TOML_CACHE_LOCK:+ _TOML_CACHE.clear()++def _load_toml(path: Path) -> dict[str, Any]:+ # Modification time AND size, because either alone is forgeable by an+ # ordinary edit: a rewrite within the same timestamp tick keeps the mtime,+ # and flipping a single flag keeps the size. A file we cannot stat is+ # simply not cached — the read below then reports the real error.+ identity: tuple[int, int] | None = None+ try:+ info = path.stat()+ identity = (info.st_mtime_ns, info.st_size)+ except OSError:+ identity = None++ if identity is not None:+ with _TOML_CACHE_LOCK:+ cached = _TOML_CACHE.get(path)+ if cached is not None and cached[0] == identity:+ return _copy_toml_data(cached[1])+# tomllib does not accept UTF-8 BOM; Windows editors (Notepad etc.)# write it automatically on Save-As. If the file is otherwise readable,# we should not silently cripple the entire brain stack — so strip the@@ -2746,7 +2815,15 @@ def _load_toml(path: Path) -> dict[str, Any]:raw = path.read_bytes()if raw.startswith(b"\xef\xbb\xbf"):raw = raw[3:]- return tomllib.loads(raw.decode("utf-8"))+ data = tomllib.loads(raw.decode("utf-8"))++ if identity is not None:+ with _TOML_CACHE_LOCK:+ _TOML_CACHE[path] = (identity, data)+ # The stored payload must stay the pristine parse, so the caller gets+ # its own copy to mutate rather than the object the cache keeps.+ return _copy_toml_data(data)+ return datadef _load_yaml(path: Path) -> dict[str, Any]:diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 420f0e12b1..4b8c3e5b8a 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -29,7 +29,7 @@ from pathlib import Pathimport tomlkitfrom tomlkit import TOMLDocument-from .config import DEFAULT_CONFIG_FILE, PROJECT_ROOT+from .config import DEFAULT_CONFIG_FILE, PROJECT_ROOT, clear_config_cachelog = logging.getLogger(__name__)@@ -1880,6 +1880,14 @@ def _atomic_write(path: Path, content: str) -> None:if was_read_only and path.exists():current_mode = path.stat().st_modeos.chmod(path, current_mode & ~stat.S_IWRITE)+ # Announce the write rather than leaving the reader to notice it. The+ # parsed-TOML cache does check the file's identity, but a rewrite+ # landing inside one filesystem timestamp tick that happens to keep the+ # byte count — flipping a flag is exactly that — would be invisible to+ # it, and serving a stale config after a save is the BUG-010 class of+ # failure this module exists to prevent. In ``finally`` because a+ # replace that raised may still have gone through.+ clear_config_cache()def _write_unique_temp(path: Path, content: str) -> Path:diff --git a/tests/unit/core/test_config_toml_cache.py b/tests/unit/core/test_config_toml_cache.pynew file mode 100644index 0000000000..4481787661--- /dev/null+++ b/tests/unit/core/test_config_toml_cache.py@@ -0,0 +1,184 @@+"""The parsed-TOML cache behind ``load_config``.++``load_config`` is called from over a hundred sites, several of them on the+event loop that also serves every WebSocket. Re-reading and re-parsing the+config there is what left the backend thread inside ``tomllib`` for over ten+minutes at 88 % of a core with ``/api/health`` timing out, the window titled+"Not responding", and keystrokes typed into an Agentic-IDE pane arriving+seconds late (measured 2026-07-28).++What the cache must never do is answer with something that was not on disk, so+these tests pin the two ways that could happen — a mutated payload leaking back+in, and a write going unnoticed — rather than only the happy path.+"""+from __future__ import annotations++import os+from pathlib import Path++import pytest++from jarvis.core import config as config_module+from jarvis.core.config import _load_toml, clear_config_cache++[email protected](autouse=True)+def _clean_cache():+ """No test may inherit or leave behind a cached payload."""+ clear_config_cache()+ yield+ clear_config_cache()+++def _write(path: Path, body: str) -> None:+ path.write_text(body, encoding="utf-8")+++def test_second_read_does_not_touch_the_parser(tmp_path, monkeypatch):+ """A repeat read is served from the cache, not by parsing again."""+ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n')++ assert _load_toml(target)["brain"]["primary"] == "gemini"++ calls: list[str] = []+ real_loads = config_module.tomllib.loads++ def counting_loads(text: str):+ calls.append(text)+ return real_loads(text)++ monkeypatch.setattr(config_module.tomllib, "loads", counting_loads)++ assert _load_toml(target)["brain"]["primary"] == "gemini"+ assert calls == [], "a cached payload must not be re-parsed"+++def test_caller_mutations_never_reach_the_cache(tmp_path):+ """The cache hands out copies — ``_apply_env_overrides`` mutates in place.++ This is the failure that would corrupt the config silently rather than+ loudly: every env override ever applied would accumulate in the cached dict+ and be served to callers as if it had been read from the file.+ """+ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n\n[ui]\nadmin_api_port = 47821\n')++ first = _load_toml(target)+ first["brain"]["primary"] = "mutated-by-caller"+ first["brain"]["injected"] = True+ first["ui"] = {"replaced": True}++ second = _load_toml(target)+ assert second["brain"]["primary"] == "gemini"+ assert "injected" not in second["brain"]+ assert second["ui"]["admin_api_port"] == 47821+++def test_nested_containers_are_copied_not_shared(tmp_path):+ """Copying has to reach all the way down, not just the top level."""+ target = tmp_path / "jarvis.toml"+ _write(+ target,+ "[brain.providers.gemini]\nbase_url = \"https://example.invalid\"\n"+ "[memory]\nnames = [\"a\", \"b\"]\n",+ )++ first = _load_toml(target)+ second = _load_toml(target)++ assert first["brain"]["providers"] is not second["brain"]["providers"]+ assert first["memory"]["names"] is not second["memory"]["names"]++ first["brain"]["providers"]["gemini"]["base_url"] = "https://tampered.invalid"+ first["memory"]["names"].append("c")++ third = _load_toml(target)+ assert third["brain"]["providers"]["gemini"]["base_url"] == "https://example.invalid"+ assert third["memory"]["names"] == ["a", "b"]+++def test_a_changed_file_is_read_again(tmp_path):+ """Editing the config must take effect — the whole point of invalidation."""+ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n')+ assert _load_toml(target)["brain"]["primary"] == "gemini"++ _write(target, '[brain]\nprimary = "openrouter"\n')+ # Force a distinct identity even on a filesystem with a coarse clock, so+ # this test pins invalidation rather than the host's timestamp resolution.+ os.utime(target, ns=(0, 10_000_000_000))++ assert _load_toml(target)["brain"]["primary"] == "openrouter"+++def test_a_same_size_rewrite_within_one_tick_is_caught_by_clear(tmp_path):+ """Identity can miss a rewrite; ``clear_config_cache`` is the backstop.++ A flag flip keeps the byte count, and a fast enough rewrite keeps the+ timestamp — which is precisely what ``config_writer._atomic_write``+ announces instead of leaving to chance.+ """+ target = tmp_path / "jarvis.toml"+ _write(target, "[ui]\nstart_hidden = true\n")+ assert _load_toml(target)["ui"]["start_hidden"] is True++ _write(target, "[ui]\nstart_hidden = fals\n".replace("fals", "false"))+ os.utime(target, ns=(0, 0)) # same identity as far as the cache can tell++ clear_config_cache()+ assert _load_toml(target)["ui"]["start_hidden"] is False+++def test_an_unstattable_path_still_raises_its_real_error(tmp_path):+ """A missing file reports itself, rather than being masked by the cache."""+ with pytest.raises(OSError):+ _load_toml(tmp_path / "does-not-exist.toml")+++def test_two_files_do_not_share_an_entry(tmp_path):+ """Keyed by path — a profile and the main config are not the same file."""+ one = tmp_path / "a.toml"+ other = tmp_path / "b.toml"+ _write(one, '[brain]\nprimary = "gemini"\n')+ _write(other, '[brain]\nprimary = "openrouter"\n')++ assert _load_toml(one)["brain"]["primary"] == "gemini"+ assert _load_toml(other)["brain"]["primary"] == "openrouter"+ assert _load_toml(one)["brain"]["primary"] == "gemini"+++def test_writer_invalidates_the_cache(tmp_path):+ """A write through ``config_writer`` is visible to the next read."""+ from jarvis.core import config_writer++ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n')+ assert _load_toml(target)["brain"]["primary"] == "gemini"++ config_writer._atomic_write(target, '[brain]\nprimary = "openrouter"\n')++ assert _load_toml(target)["brain"]["primary"] == "openrouter"+++def test_load_config_reflects_an_edit(tmp_path, monkeypatch):+ """End to end: the public entry point is not left holding a stale config.++ The env override is cleared deliberately. A developer machine really does+ export ``JARVIS__BRAIN__PRIMARY``, and env outranks the file by design — so+ leaving it in place would make this assert the precedence rule while+ claiming to assert the cache, and it would pass whether or not the cache+ ever invalidated.+ """+ from jarvis.core.config import load_config++ monkeypatch.delenv("JARVIS__BRAIN__PRIMARY", raising=False)++ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n')+ assert load_config(target).brain.primary == "gemini"++ _write(target, '[brain]\nprimary = "openrouter"\n')+ os.utime(target, ns=(0, 10_000_000_000))++ assert load_config(target).brain.primary == "openrouter"