Skip to content
1 change: 1 addition & 0 deletions openhands-sdk/openhands/sdk/conversation/event_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ def append(self, event: Event) -> None:
)

target_path = self._path(self._length, event_id=evt_id)

self._fs.write(target_path, event.model_dump_json(exclude_none=True))
self._idx_to_id[self._length] = evt_id
self._id_to_idx[evt_id] = self._length
Expand Down
4 changes: 2 additions & 2 deletions openhands-sdk/openhands/sdk/conversation/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def _save_base_state(self, fs: FileStore) -> None:
"preserve secrets."
)
payload = self.model_dump_json(exclude_none=True, context=context)
fs.write(BASE_STATE, payload)
fs.write(BASE_STATE, payload, cache=False)

# ===== Factory: open-or-create (no load/save methods needed) =====
@classmethod
Expand Down Expand Up @@ -299,7 +299,7 @@ def create(
)

try:
base_text = file_store.read(BASE_STATE)
base_text = file_store.read(BASE_STATE, cache=False)
except FileNotFoundError:
base_text = None

Expand Down
4 changes: 2 additions & 2 deletions openhands-sdk/openhands/sdk/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class FileStore(ABC):
"""

@abstractmethod
def write(self, path: str, contents: str | bytes) -> None:
def write(self, path: str, contents: str | bytes, **kwargs) -> None:
"""Write contents to a file at the specified path.

Args:
Expand All @@ -23,7 +23,7 @@ def write(self, path: str, contents: str | bytes) -> None:
"""

@abstractmethod
def read(self, path: str) -> str:
def read(self, path: str, **kwargs) -> str:
"""Read and return the contents of a file as a string.

Args:
Expand Down
16 changes: 10 additions & 6 deletions openhands-sdk/openhands/sdk/io/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,32 +59,36 @@ def get_full_path(self, path: str) -> str:
return full

@observe(name="LocalFileStore.write", span_type="TOOL")
def write(self, path: str, contents: str | bytes) -> None:
def write(self, path: str, contents: str | bytes, **kwargs) -> None:
cache = kwargs.get("cache", True)

full_path = self.get_full_path(path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
if isinstance(contents, str):
with open(full_path, "w", encoding="utf-8") as f:
f.write(contents)
self.cache[full_path] = contents
if cache:
self.cache[full_path] = contents
else:
with open(full_path, "wb") as f:
f.write(contents)
# Don't cache binary content - LocalFileStore is meant for JSON data
# If binary data is written and then read, it will error on read

def read(self, path: str) -> str:
def read(self, path: str, **kwargs) -> str:
cache = kwargs.get("cache", True)
full_path = self.get_full_path(path)

if full_path in self.cache:
if cache and full_path in self.cache:
return self.cache[full_path]

if not os.path.exists(full_path):
raise FileNotFoundError(path)

with open(full_path, encoding="utf-8") as f:
result = f.read()

self.cache[full_path] = result
if cache:
self.cache[full_path] = result
return result

@observe(name="LocalFileStore.list", span_type="TOOL")
Expand Down
4 changes: 2 additions & 2 deletions openhands-sdk/openhands/sdk/io/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ def __init__(self, files: dict[str, str] | None = None) -> None:
if files is not None:
self.files = files

def write(self, path: str, contents: str | bytes) -> None:
def write(self, path: str, contents: str | bytes, **_kwargs) -> None:
if isinstance(contents, bytes):
contents = contents.decode("utf-8")
self.files[path] = contents

def read(self, path: str) -> str:
def read(self, path: str, **_kwargs) -> str:
if path not in self.files:
raise FileNotFoundError(path)
return self.files[path]
Expand Down
6 changes: 4 additions & 2 deletions openhands-tools/openhands/tools/tom_consult/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def _load_processing_history(self) -> dict[str, Any]:
from tom_swe.memory.locations import get_usermodeling_dir

history_file = f"{get_usermodeling_dir(self.user_id)}/processed_sessions_timestamps.json" # noqa: E501
content = self.file_store.read(history_file)
content = self.file_store.read(history_file, cache=False)
return json.loads(content)
except FileNotFoundError:
return {}
Expand Down Expand Up @@ -417,7 +417,9 @@ def _save_processing_history(self, session_ids: list[str]) -> None:

history_file = f"{get_usermodeling_dir(self.user_id)}/processed_sessions_timestamps.json" # noqa: E501

self.file_store.write(history_file, json.dumps(history, indent=2))
self.file_store.write(
history_file, json.dumps(history, indent=2), cache=False
)
logger.info(
f"📝 Tom: Updated processing history for {len(session_ids)} sessions"
) # noqa: E501
Expand Down
45 changes: 45 additions & 0 deletions tests/sdk/conversation/local/test_state_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
ConversationTokenCallbackType,
)
from openhands.sdk.event.llm_convertible import MessageEvent, SystemPromptEvent
from openhands.sdk.io.local import LocalFileStore
from openhands.sdk.llm import LLM, Message, TextContent
from openhands.sdk.llm.llm_registry import RegistryEvent
from openhands.sdk.security.confirmation_policy import AlwaysConfirm
Expand Down Expand Up @@ -1274,3 +1275,47 @@ def test_agent_verify_fails_when_builtin_tool_removed():
# Should fail because builtin tools don't match
with pytest.raises(ValueError, match="tools cannot be changed mid-conversation"):
runtime_agent.verify(persisted_agent)


def test_conversation_state_fs_cache():
"""Test that conversation state is properly persisted and loaded from file system
(FS) cache, with verification of cache memory behavior."""
with tempfile.TemporaryDirectory() as temp_dir:
llm = LLM(
model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="test-llm"
)
agent = Agent(llm=llm, tools=[])
conv_id = uuid.UUID("12345678-1234-5678-9abc-123456789011")
persist_path_for_state = LocalConversation.get_persistence_dir(
temp_dir, conv_id
)
state = ConversationState.create(
workspace=LocalWorkspace(working_dir="/tmp"),
persistence_dir=persist_path_for_state,
agent=agent,
id=conv_id,
)

state.stats.register_llm(RegistryEvent(llm=llm))

# Set various flags
state.execution_status = ConversationExecutionStatus.FINISHED
state.confirmation_policy = AlwaysConfirm()

# Create a new ConversationState that loads from the same persistence
# directory
loaded_state = ConversationState.create(
workspace=LocalWorkspace(working_dir="/tmp"),
persistence_dir=persist_path_for_state,
agent=agent,
id=conv_id,
)

# Verify key fields are preserved
assert loaded_state.id == state.id
assert loaded_state.agent.llm.model == state.agent.llm.model
# Verify flags are preserved
assert loaded_state.execution_status == ConversationExecutionStatus.FINISHED
assert loaded_state.confirmation_policy == AlwaysConfirm()
assert isinstance(loaded_state._fs, LocalFileStore)
assert len(loaded_state._fs.cache) == 0
31 changes: 31 additions & 0 deletions tests/sdk/io/test_filestore_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,34 @@ def test_cache_with_evict_correct():
total_len = len(cache["key2"]) + len(cache["key3"])
# Verify memory statistics match the total size of key2 and key3
assert total_len == cache.current_memory


def test_cache_enable_and_disable():
"""Test that cache can be enabled and disabled via constructor."""
with tempfile.TemporaryDirectory() as temp_dir:
# Cache enabled
# When cache is allowed (enabled):
# - Data will be stored in the in-memory cache after write/read operations.
# - The cache dictionary will contain the data, and its length will be
# greater than 0.
store_with_cache = LocalFileStore(temp_dir, cache_limit_size=0)
store_with_cache.write("test.txt", "content")
assert len(store_with_cache.cache) == 1
store_with_cache.read("test.txt")
assert len(store_with_cache.cache) == 1
store_with_cache.cache.clear()
assert len(store_with_cache.cache) == 0
store_with_cache.read("test.txt")
assert len(store_with_cache.cache) == 1

# Cache disabled
# When cache is disallowed (disabled):
# - Data will NOT be stored in the in-memory cache, even after
# write/read operations.
# - The cache dictionary will remain empty (length = 0) regardless
# of file operations.
store_no_cache = LocalFileStore(temp_dir, cache_limit_size=10)
store_no_cache.write("test.txt", "content", cache=False)
assert len(store_no_cache.cache) == 0
store_no_cache.read("test.txt", cache=False)
assert len(store_no_cache.cache) == 0
Loading