Skip to content

render_template reports any template compile/cache failure as "Prompt file ... not found", ending runs during condensation #7103

Backlog

Description

@neubig

This issue was created by an AI agent (OpenHands) on behalf of @neubig.

Summary

openhands.sdk.context.prompts.prompt._get_template catches every exception from Jinja's get_template() and replaces it with FileNotFoundError("Prompt file <path> not found"). So when a template file exists but cannot be compiled or cached, the user gets an error that says the file is missing. Examples: a Jinja syntax error, a decode error, or a failed write or read of the Jinja bytecode cache under <OH_PERSISTENCE_DIR or ~/.openhands>/cache/jinja (disk full, read-only or unwritable directory).

The condenser renders its packaged summarizing_system.j2 template on every condensation, and this happens outside its error handling. A bytecode-cache I/O failure therefore ends the conversation run during message preparation with "Prompt file …/condenser/prompts/summarizing_system.j2 not found", even though the file is present. This happens even for a SOFT, event-count condensation, which would otherwise be skipped.

Impact

  • Built-in templates: if the disk is full or the Jinja cache directory cannot be written when the condenser first renders its template in a process, run() / arun() fail with ConversationRunError caused by FileNotFoundError: Prompt file …/summarizing_system.j2 not found. No model request is made. The error points to a missing or broken package, but the package is fine. The real cause is visible only in __context__. Each new attempt in the same process fails the same way, because _get_template only caches successes.
  • Custom templates (system_prompt_filename= an absolute or custom path): a template with a syntax error is reported as "not found". The user goes looking for a path problem instead of the syntax error.
  • Missing custom template: Agent(...) and Conversation(...) construct without error. The plain FileNotFoundError appears only at the first send_message() / run() (init_state → static_system_message), and again on every resume, because init_state re-renders the static prompt for restored conversations too.

Root cause

All links are at af85e22.

prompt.py#L59-L87:

@lru_cache(maxsize=64)
def _get_env(prompt_dir: str) -> Environment:
    cache_folder = get_user_persistence_dir() / "cache" / "jinja"
    cache_folder.mkdir(parents=True, exist_ok=True)
    bcc = FileSystemBytecodeCache(directory=str(cache_folder))
    env = Environment(loader=FlexibleFileSystemLoader(prompt_dir), bytecode_cache=bcc, ...)

@lru_cache(maxsize=256)
def _get_template(prompt_dir: str, template_name: str) -> Template:
    env = _get_env(prompt_dir)
    try:
        return env.get_template(template_name)
    except Exception:
        raise FileNotFoundError(
            f"Prompt file {os.path.join(prompt_dir, template_name)} not found"
        )
  • env.get_template() compiles the template and then calls FileSystemBytecodeCache.dump_bytecode(). In Jinja 3.1 that creates a NamedTemporaryFile in the cache directory and re-raises any write error (ENOSPC, EACCES, …). It also raises TemplateSyntaxError / UnicodeDecodeError for a bad template. All of these become "not found". The real error is only kept as __context__, because there is no from e.
  • The only real "missing" case is already handled by FlexibleFileSystemLoader.get_source (TemplateNotFound, L34-L35) and by the absolute-path check in render_template (L107-L110).

Why this ends a run during message preparation: LLMSummarizingCondenser._generate_condensation / _agenerate_condensation call _build_summary_messages(), which calls render_template(prompt_dir, "summarizing_system.j2") (llm_summarizing_condenser.py#L209-L226). That call happens before the try that turns summarizer failures into NoCondensationAvailableException (L257-L266). RollingCondenser.condense / acondense only catch NoCondensationAvailableException (condenser/base.py#L163-L178). So the FileNotFoundError escapes prepare_llm_messages / aprepare_llm_messages and Agent.step / astep, even when the requirement was SOFT.

The packaged templates are present. The wheel ships *.j2 as package data, and agent-server.spec collects condenser/prompts/*.j2 and prompts/templates/*.j2; I checked that collect_data_files returns both. So resolving built-in templates differently would not fix this. The problem is how errors are classified.

Reproduction

The templates and prompt.py are real and nothing in them is mocked. The full-disk case uses a real 2 MiB tmpfs. The run cases replace the LLM provider (litellm_completion / litellm_acompletion) with a function that fails the test if it is called, to show that no model request happens.

uv sync --dev --frozen
# optional, for the full-disk run test:
sudo mkdir -p /mnt/ohfull && sudo mount -t tmpfs -o size=2m tmpfs /mnt/ohfull
sudo chown "$(id -u):$(id -g)" /mnt/ohfull
# save the file below as tests/sdk/context/test_prompt_not_found_repro.py
OH_FULL_DIR=/mnt/ohfull uv run pytest tests/sdk/context/test_prompt_not_found_repro.py -s -q -p no:cacheprovider
tests/sdk/context/test_prompt_not_found_repro.py
"""Repro: render_template reports *any* template load/compile failure as
"Prompt file ... not found", even when the file exists.

The templates are the real packaged ones; nothing in prompt.py is mocked.
"""

import asyncio
import errno
import os
import stat
from pathlib import Path

import pytest
from pydantic import SecretStr

import openhands.sdk.context.condenser.llm_summarizing_condenser as cond_mod
import openhands.sdk.llm.llm as llm_mod
from openhands.sdk.agent import Agent
from openhands.sdk.context.condenser import LLMSummarizingCondenser
from openhands.sdk.context.prompts import prompt as prompt_mod
from openhands.sdk.context.prompts.prompt import render_template
from openhands.sdk.conversation import Conversation
from openhands.sdk.conversation.exceptions import ConversationRunError
from openhands.sdk.event import MessageEvent
from openhands.sdk.llm import LLM, Message, TextContent
from tests.sdk.context.view.conftest import (
    create_action_event,
    create_observation_event,
)


CONDENSER_PROMPTS = os.path.join(os.path.dirname(cond_mod.__file__), "prompts")
FULL_DIR = os.environ.get("OH_FULL_DIR")


@pytest.fixture(autouse=True)
def fresh_jinja(tmp_path, monkeypatch):
    monkeypatch.setenv("OH_PERSISTENCE_DIR", str(tmp_path / "oh"))
    prompt_mod._get_env.cache_clear()
    prompt_mod._get_template.cache_clear()
    yield
    prompt_mod._get_env.cache_clear()
    prompt_mod._get_template.cache_clear()


def _report(exc: BaseException, path: str) -> None:
    print(f"\n  file exists: {os.path.isfile(path)}")
    print(f"  raised: {type(exc).__name__}: {exc}")
    print(f"  __cause__: {exc.__cause__!r}  __context__: {exc.__context__!r}")


def test_malformed_custom_template_reported_as_missing(tmp_path):
    tpl = tmp_path / "custom_system_prompt.j2"
    tpl.write_text("You are helpful. {% if %}\n")
    with pytest.raises(FileNotFoundError) as ei:
        render_template(str(tmp_path), str(tpl))
    _report(ei.value, str(tpl))
    assert tpl.is_file() and "not found" in str(ei.value)


@pytest.mark.skipif(os.getuid() == 0, reason="root ignores directory modes")
def test_unwritable_bytecode_cache_reported_as_missing(tmp_path):
    cache = tmp_path / "oh" / "cache" / "jinja"
    cache.mkdir(parents=True)
    cache.chmod(stat.S_IRUSR | stat.S_IXUSR)  # read-only cache dir
    try:
        with pytest.raises(FileNotFoundError) as ei:
            render_template(CONDENSER_PROMPTS, "summarizing_system.j2")
    finally:
        cache.chmod(stat.S_IRWXU)
    path = os.path.join(CONDENSER_PROMPTS, "summarizing_system.j2")
    _report(ei.value, path)
    assert os.path.isfile(path)


@pytest.mark.skipif(not FULL_DIR, reason="needs OH_FULL_DIR on a small tmpfs")
@pytest.mark.parametrize("mode", ["sync", "async"])
def test_full_disk_condensation_ends_run_with_prompt_not_found(
    tmp_path, monkeypatch, mode
):
    full = Path(FULL_DIR)
    for p in full.iterdir():
        p.unlink() if p.is_file() else None
    monkeypatch.setenv("OH_PERSISTENCE_DIR", str(full / f"oh-{mode}"))
    llm_calls = []

    def completion(*a, **k):
        llm_calls.append(k)
        raise AssertionError("LLM must not be reached")

    async def acompletion(*a, **k):
        return completion(*a, **k)

    monkeypatch.setattr(llm_mod, "litellm_completion", completion)
    monkeypatch.setattr(llm_mod, "litellm_acompletion", acompletion)

    llm = LLM(model="gpt-4o", api_key=SecretStr("k"), usage_id="a", num_retries=0)
    condenser = LLMSummarizingCondenser(
        llm=llm.model_copy(update={"usage_id": "c"}), max_size=20, keep_first=2
    )
    conv = Conversation(  # in-memory event store: only the jinja cache hits disk
        agent=Agent(llm=llm, tools=[], condenser=condenser),
        workspace=str(tmp_path),
        visualizer=None,
        stuck_detection=False,
    )
    conv._ensure_agent_ready()
    conv.state.append_event(
        MessageEvent(
            source="user",
            llm_message=Message(role="user", content=[TextContent(text="go")]),
        )
    )
    for i in range(15):  # 31 events > max_size=20 -> SOFT event-count condensation
        a = create_action_event(f"r{i}", f"c{i}")
        o = create_observation_event(f"c{i}", content=f"out {i}")
        conv.state.append_event(a)
        conv.state.append_event(o.model_copy(update={"action_id": a.id}))

    with open(full / "filler.bin", "wb") as f:  # disk is now full
        try:
            while True:
                f.write(b"\0" * 4096)
                f.flush()
        except OSError as e:
            assert e.errno == errno.ENOSPC
    try:
        with pytest.raises(ConversationRunError) as ei:
            conv.run() if mode == "sync" else asyncio.run(conv.arun())
    finally:
        (full / "filler.bin").unlink()
    path = os.path.join(CONDENSER_PROMPTS, "summarizing_system.j2")
    print(f"\n[{mode}] status={conv.state.execution_status.value} llm_calls={len(llm_calls)}")
    _report(ei.value.__cause__, path)
    assert isinstance(ei.value.__cause__, FileNotFoundError)
    assert os.path.isfile(path) and not llm_calls

Observed on main at af85e22 (run as a non-root user):

test_malformed_custom_template_reported_as_missing
  file exists: True
  raised: FileNotFoundError: Prompt file /tmp/pytest-of-openhands/pytest-13/test_malformed_custom_template0/custom_system_prompt.j2 not found
  __cause__: None  __context__: TemplateSyntaxError("Expected an expression, got 'end of statement block'")
test_unwritable_bytecode_cache_reported_as_missing
  file exists: True
  raised: FileNotFoundError: Prompt file .../openhands/sdk/context/condenser/prompts/summarizing_system.j2 not found
  __cause__: None  __context__: PermissionError(13, 'Permission denied')
test_full_disk_condensation_ends_run_with_prompt_not_found[sync]
[sync] status=error llm_calls=0
  file exists: True
  raised: FileNotFoundError: Prompt file .../openhands/sdk/context/condenser/prompts/summarizing_system.j2 not found
  __cause__: None  __context__: OSError(28, 'No space left on device')
test_full_disk_condensation_ends_run_with_prompt_not_found[async]
[async] status=error llm_calls=0
  file exists: True
  raised: FileNotFoundError: Prompt file .../openhands/sdk/context/condenser/prompts/summarizing_system.j2 not found
  __cause__: None  __context__: OSError(28, 'No space left on device')
4 passed

Missing custom template (Agent(llm=..., tools=[], system_prompt_filename="/tmp/rca/does_not_exist.j2")): Agent(...) and Conversation(...) succeed. send_message("hi") then raises FileNotFoundError: Prompt file /tmp/rca/does_not_exist.j2 not found from _ensure_agent_ready → init_state → static_system_message → render_template.

Expected behavior

  • "not found" is reported only when the template file really does not exist (TemplateNotFound).
  • A template syntax or decode error is reported as such, with the template path, and is not reported as "not found".
  • A bytecode-cache I/O failure does not stop the template from rendering. The cache is an optimization: render without it, and log a warning.
  • A failure to render the condenser's own prompt does not end a run when the condensation requirement is SOFT.
  • (Nice to have) a missing custom system_prompt_filename is reported when the agent or conversation is configured, as a typed configuration error, and not only on the first message.

Suggested fix

  1. In _get_template, catch only TemplateNotFound and turn it into FileNotFoundError(...) from e. Let TemplateSyntaxError, UnicodeDecodeError and other errors propagate, or wrap them in a typed PromptTemplateError(path) from e.
  2. Make the bytecode cache best-effort. Either subclass FileSystemBytecodeCache so that dump_bytecode / load_bytecode log OSError (and unpickling errors) and continue, or on such an error fall back to an Environment without bytecode_cache. Also handle a failing cache_folder.mkdir.
  3. In LLMSummarizingCondenser, build the summary messages inside the existing try (or turn template errors into NoCondensationAvailableException). Then a SOFT requirement degrades to the unchanged view, and HARD goes through the normal fallback.
  4. Optional: check that a custom system_prompt_filename exists in an AgentBase validator, or when Conversation is created.

Acceptance criteria

  • render_template on an existing template with a Jinja syntax error raises an error that names the syntax problem (not "not found"), and keeps the original exception as __cause__.
  • With the Jinja cache directory unwritable or the disk full, rendering summarizing_system.j2 still returns the rendered prompt.
  • With the same cache failure, a sync and an async conversation whose view needs SOFT condensation keep running (or condense), and do not end with FileNotFoundError.
  • A template that really is missing still raises FileNotFoundError naming the path.
  • (If item 4 is done) creating an agent or conversation with a missing custom system_prompt_filename fails with a typed configuration error before any model request. Fixing the path lets the next turn run.

Related: #7102 covers how the same full-disk condition breaks conversation state persistence. This issue is separate: here the template exists, and the failure is only in classifying errors and handling the Jinja cache.


OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

Verified against main at af85e22: _get_template converts every env.get_template() failure into FileNotFoundError without from e; _get_env performs an unprotected mkdir and always attaches a FileSystemBytecodeCache (jinja2 pinned at 3.1.6, whose cache write path re-raises OSError); LLMSummarizingCondenser builds summary messages before the try that raises NoCondensationAvailableException; RollingCondenser.condense/acondense catch only that exception; and LocalConversation.arun does not catch FileNotFoundError, so it ends the run as ConversationRunError. The repo's other render_template call sites (agent base, AgentContext, ask-agent) would get the corrected error classification centrally, but this issue is bounded to the failure modes and run-ending behavior described here.

Priority is medium, matching sibling issue #7102 from the same ENOSPC investigation (reproduced on main, but no external user report or production evidence in the issue or discussion).

Non-goals: construction-time validation of a missing custom system_prompt_filename (marked optional by the author; changes when configuration errors surface); the disk-full state persistence failure (tracked in #7102); new typed prompt error types or Jinja environment changes beyond best-effort cache handling; altering SOFT/HARD condensation semantics.

Acceptance Criteria

  • Rendering an existing template with a Jinja syntax error raises an exception that reports the syntax problem (not "not found"), includes the template path, and keeps the original exception as __cause__.
  • A template that does not exist still raises FileNotFoundError naming the path.
  • With the Jinja bytecode-cache directory unwritable or on a full disk, rendering the packaged summarizing_system.j2 still returns the rendered prompt.
  • When a cache directory cannot be created, _get_env either skips or degrades the bytecode cache instead of raising FileNotFoundError.
  • With a render-time cache failure, sync and async conversations whose view has a SOFT condensation requirement complete their run without ConversationRunError caused by FileNotFoundError, and each render succeeds from then on (no repeated cache failure per attempt).
  • A HARD condensation requirement still ends the run through the existing hard-context-reset path when rendering fails, preserving the original error in the exception chain (no new swallow behavior).
  • Behavioral changes to render_template, AgentContext, agent base, or condensers are covered under the repository's SDK API-compatibility policy and by tests in the adjacent suites (tests/sdk/context/, condenser tests).

Activity

  1. added
    bug
    on Nov 24, 2026
  2. added
    priority:medium
    ready-for-dev
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpriority:mediumready-for-dev

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions