Skip to content

Commit 3574ced

Browse files
committed
fix: do not cache failed command lookups
Review finding, and a real availability bug rather than a style point. find_system_command was lru_cached, which caches None as readily as a path. A package manager replacing a binary unlinks and relinks it, so a lookup landing in that window finds nothing. Caching that answer made one unlucky moment permanent for the rest of a long-lived agent's life: every later cross-user launch would fail on a command sitting on disk the whole time. Replaced with a dict that stores successful lookups only. Successes stay valid for the life of the process and these lookups sit on process-launch and signal-delivery paths, so caching them is still worth it; re-walking a handful of directories on the miss path costs nothing worth having. clear_command_cache() replaces cache_clear() for tests that patch the directory list. Both halves are pinned, because "do not cache misses" could otherwise be satisfied by caching nothing at all and losing the reason the cache exists. Mutation-checked: caching the miss as well fails test_a_command_that_appears_later_is_found and nothing else, against a green baseline with the source restored afterwards. Signed-off-by: David Leong <116610336+leongdl@users.noreply.github.com>
1 parent 7f50a40 commit 3574ced

2 files changed

Lines changed: 70 additions & 12 deletions

File tree

‎src/openjd/sessions/_system_commands.py‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@
3333
from __future__ import annotations
3434

3535
import os
36-
from functools import lru_cache
3736
from typing import Optional, Tuple
3837

3938
__all__ = [
4039
"SystemCommandNotFoundError",
40+
"clear_command_cache",
4141
"TRUSTED_SYSTEM_DIRECTORIES",
4242
"find_system_command",
4343
"system_command_path",
@@ -124,27 +124,45 @@ def _is_executable_file(path: str) -> bool:
124124
return os.path.isfile(path) and os.access(path, os.X_OK)
125125

126126

127-
@lru_cache(maxsize=None)
127+
_RESOLVED_COMMANDS: dict[str, str] = {}
128+
"""Cache of successful lookups only, keyed by bare command name.
129+
130+
Successes are safe to keep for the life of the process: a resolved path stays
131+
valid, and these lookups sit on process-launch and signal-delivery paths where a
132+
directory walk per signal is wasteful.
133+
134+
Failures are not cached, and that asymmetry is the point. A package manager
135+
replacing a binary unlinks and relinks it, so a lookup landing in that window sees
136+
nothing. Caching that answer would make one unlucky moment permanent for the rest
137+
of a long-lived agent's life, turning a transient miss into a session that can
138+
never start a cross-user process again. Re-walking a handful of directories on the
139+
miss path costs nothing worth having.
140+
"""
141+
142+
143+
def clear_command_cache() -> None:
144+
"""Discard resolved paths. For tests that patch the trusted directory list."""
145+
_RESOLVED_COMMANDS.clear()
146+
147+
128148
def find_system_command(name: str) -> Optional[str]:
129149
"""Return the absolute path to ``name``, or ``None`` if it is not installed.
130150
131151
Searches :data:`TRUSTED_SYSTEM_DIRECTORIES` in order. ``PATH`` is not
132152
consulted. Use this for commands whose absence is tolerable; use
133153
:func:`system_command_path` when the command is required.
134154
135-
The result is cached: the filesystem layout does not change underneath a
136-
running session, and these lookups sit on process-launch and
137-
signal-delivery paths. Tests that patch
138-
:data:`TRUSTED_SYSTEM_DIRECTORIES` must call
139-
``find_system_command.cache_clear()``.
140-
141155
Raises:
142156
ValueError: if ``name`` is not a bare command name.
143157
"""
144158
_validate_command_name(name)
159+
cached = _RESOLVED_COMMANDS.get(name)
160+
if cached is not None:
161+
return cached
145162
for directory in TRUSTED_SYSTEM_DIRECTORIES:
146163
candidate = os.path.join(directory, name)
147164
if _is_executable_file(candidate):
165+
_RESOLVED_COMMANDS[name] = candidate
148166
return candidate
149167
return None
150168

‎test/openjd/sessions_v0/test_system_commands.py‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from openjd.sessions._os_checker import is_posix
2323
from openjd.sessions._system_commands import (
2424
SystemCommandNotFoundError,
25+
clear_command_cache,
2526
TRUSTED_SYSTEM_DIRECTORIES,
2627
find_system_command,
2728
system_command_path,
@@ -32,11 +33,11 @@
3233

3334
@pytest.fixture(autouse=True)
3435
def clear_resolver_cache():
35-
"""``find_system_command`` is ``lru_cache``d, so a result computed under one
36-
patched directory list would otherwise leak into the next test."""
37-
find_system_command.cache_clear()
36+
"""Successful lookups are cached, so a path resolved under one patched
37+
directory list would otherwise leak into the next test."""
38+
clear_command_cache()
3839
yield
39-
find_system_command.cache_clear()
40+
clear_command_cache()
4041

4142

4243
@pytest.fixture
@@ -297,3 +298,42 @@ def test_sudo_resolves_on_this_host(self) -> None:
297298
pytest.skip("sudo is not installed on this host")
298299

299300
assert os.path.dirname(system_command_path("sudo")) in TRUSTED_SYSTEM_DIRECTORIES
301+
302+
303+
class TestCacheDoesNotRememberAbsence:
304+
"""Successes are cached; failures are not.
305+
306+
A package manager replacing a binary unlinks and relinks it, so a lookup
307+
landing in that window finds nothing. Caching that answer would make one
308+
unlucky moment permanent for the rest of a long-lived agent's life: every
309+
later cross-user launch would fail on a command that is sitting on disk.
310+
"""
311+
312+
def test_a_command_that_appears_later_is_found(self, tmp_path: Path) -> None:
313+
# GIVEN a lookup that misses, as it would mid-upgrade
314+
with patch(f"{_MODULE}.TRUSTED_SYSTEM_DIRECTORIES", (str(tmp_path),)):
315+
assert find_system_command("target-cmd") is None
316+
317+
# WHEN the binary appears
318+
target = tmp_path / "target-cmd"
319+
target.write_text("#!/bin/sh\ntrue\n")
320+
target.chmod(target.stat().st_mode | stat.S_IXUSR)
321+
322+
# THEN the next lookup finds it rather than repeating the cached miss
323+
assert find_system_command("target-cmd") == str(target)
324+
325+
def test_a_resolved_path_is_cached(self, executable_dir: Path) -> None:
326+
"""The other half of the asymmetry. Without this, 'do not cache misses'
327+
could be satisfied by caching nothing at all, and the reason the cache
328+
exists (these lookups sit on signal-delivery paths) would be lost."""
329+
# GIVEN one successful lookup
330+
with patch(f"{_MODULE}.TRUSTED_SYSTEM_DIRECTORIES", (str(executable_dir),)):
331+
first = find_system_command("target-cmd")
332+
assert first == str(executable_dir / "target-cmd")
333+
334+
# WHEN the directory list no longer contains it, and the file is gone
335+
(executable_dir / "target-cmd").unlink()
336+
337+
# THEN the cached answer is still returned, without touching the filesystem
338+
with patch(f"{_MODULE}.TRUSTED_SYSTEM_DIRECTORIES", ()):
339+
assert find_system_command("target-cmd") == first

0 commit comments

Comments
 (0)