Skip to content
Python

fix(sessions): a change in the middle of a session's history is saved, not lost or repeated (OPE-243)

Devika Verma9368a47b4287
diff --git a/coworker/conversations.py b/coworker/conversations.py
index bc964d06..a52db466 100644
--- a/coworker/conversations.py
+++ b/coworker/conversations.py
@@ -82,6 +82,10 @@ class ConversationStore:
self.db_path = self.base / "coworker.db"
self._lock = threading.RLock()
+ # Per session: the message objects the .jsonl is known to hold, in order, as of
+ # this store's last save/load. Lets save() tell a pure append from a change in
+ # the middle without re-reading the file.
+ self._persisted: dict[str, list[dict]] = {}
self._conn = sqlite3.connect(self.db_path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._conn.executescript("""
@@ -276,6 +280,35 @@ class ConversationStore:
for m in messages:
f.write(json.dumps(m) + "\n")
+ def _rewrite(self, sid: str, messages: list[dict]) -> None:
+ # Atomic rewrite: write the full log to a temp file, then replace in one
+ # step. An in-place open(..., "w") truncates the file immediately, so a
+ # crash mid-rewrite would erase the conversation history (same
+ # tmp-then-replace pattern as subscriptions.ChannelBuffer._save).
+ path = self._file(sid)
+ tmp = path.with_suffix(".tmp")
+ with open(tmp, "w", encoding="utf-8") as f:
+ for m in messages:
+ f.write(json.dumps(m) + "\n")
+ tmp.replace(path)
+
+ def _saved_prefix_unchanged(self, sid: str, messages: list[dict], existing: int) -> bool:
+ """True when the first `existing` messages are exactly what the file already holds,
+ so the new ones can simply be appended. Checked by object identity against what
+ this store last saved or loaded for the session (cheap); without that record (first
+ save in this process, or load() changed the list), by comparing the file's lines."""
+ if existing == 0:
+ return True
+ if len(messages) < existing:
+ return False
+ known = self._persisted.get(sid)
+ if known is not None and len(known) == existing:
+ return all(a is b for a, b in zip(messages, known))
+ lines = [ln for ln in self._file(sid).read_text(encoding="utf-8").splitlines() if ln.strip()]
+ return len(lines) == existing and all(
+ json.dumps(m) == ln for m, ln in zip(messages, lines)
+ )
+
def _backfill_counts(self) -> None:
"""One-time per session: move any inline blob into a .jsonl and persist
title + n_msgs in the index. Skips already-migrated rows on later startups."""
@@ -330,19 +363,16 @@ class ConversationStore:
self._append(sid, legacy)
existing = self._count(sid)
- if len(record.messages) > existing:
- self._append(sid, record.messages[existing:])
- elif len(record.messages) < existing: # rare; not append-only
- # Atomic rewrite: write the full log to a temp file, then replace in one
- # step. An in-place open(..., "w") truncates the file immediately, so a
- # crash mid-rewrite would erase the conversation history (same
- # tmp-then-replace pattern as subscriptions.ChannelBuffer._save).
- path = self._file(sid)
- tmp = path.with_suffix(".tmp")
- with open(tmp, "w", encoding="utf-8") as f:
- for m in record.messages:
- f.write(json.dumps(m) + "\n")
- tmp.replace(path)
+ if self._saved_prefix_unchanged(sid, record.messages, existing):
+ if len(record.messages) > existing:
+ self._append(sid, record.messages[existing:])
+ else:
+ # Not a pure append: a message was inserted, removed or moved before the
+ # end (load()'s pairing repair, the engine's dangling-call stubs, a shrink).
+ # Appending by count here would skip the inserted message and write the
+ # shifted tail twice, so rewrite the whole log instead.
+ self._rewrite(sid, record.messages)
+ self._persisted[sid] = list(record.messages)
title = record.title or title_from(record.messages)
self._conn.execute(
@@ -388,6 +418,7 @@ class ConversationStore:
if not row:
return None
messages = self._read_jsonl(session_id)
+ from_file = messages is not None
if messages is None:
try:
messages = json.loads(row["messages"] or "[]")
@@ -396,7 +427,15 @@ class ConversationStore:
# Self-heal: ensure every tool result immediately follows its call.
# An interrupted turn can persist a user message between an assistant
# tool_calls block and its tool result, which providers reject (400).
+ raw = messages
messages = self._repair_tool_pairing(messages)
+ with self._lock:
+ if from_file and messages == raw and self._count(session_id) == len(raw):
+ self._persisted[session_id] = list(messages)
+ else:
+ # The healed list (or skipped corrupt lines) differs from the file: the
+ # next save must not treat it as an append.
+ self._persisted.pop(session_id, None)
return SessionRecord(
session_id=session_id,
workspace=row["workspace"],
@@ -561,6 +600,7 @@ class ConversationStore:
"DELETE FROM sessions WHERE session_id = ?", (session_id,)
)
self._conn.commit()
+ self._persisted.pop(session_id, None)
path = self._file(session_id)
if path.exists():
path.unlink()
diff --git a/tests/test_conversation_save_mid_change.py b/tests/test_conversation_save_mid_change.py
new file mode 100644
index 00000000..385db9ef
--- /dev/null
+++ b/tests/test_conversation_save_mid_change.py
@@ -0,0 +1,113 @@
+"""ConversationStore.save when the message list changed in the MIDDLE, not only at the end.
+
+`save()` used to persist by count: if the in-memory list was longer than the file it
+appended `messages[existing:]`. Two code paths change the list in the middle:
+
+* `load()` heals tool-call/result pairing (`_repair_tool_pairing`): it synthesises a
+ placeholder result right after an orphaned call and moves a misplaced result up.
+* `TurnEngine._repair_dangling_tool_calls` inserts a stub result right after the
+ assistant message whose call never got one.
+
+After either, appending by count wrote a shifted tail: the inserted message was never
+saved and the message after it was written twice, again on every load-and-save cycle.
+"""
+
+from __future__ import annotations
+
+import json
+
+from coworker.conversations import ConversationStore
+from coworker.sessions import SessionRecord
+
+
+def _assistant_call(call_id="c1"):
+ return {"role": "assistant", "content": None, "tool_calls": [
+ {"id": call_id, "type": "function", "function": {"name": "run_shell", "arguments": "{}"}}]}
+
+
+def _record(sid, messages):
+ return SessionRecord(session_id=sid, workspace="/w", model="m", mode="interactive", messages=messages)
+
+
+def _file_lines(store, sid):
+ return [json.loads(line) for line in store._file(sid).read_text(encoding="utf-8").splitlines() if line.strip()]
+
+
+def test_save_after_load_repair_persists_the_placeholder_and_does_not_duplicate(tmp_path):
+ store = ConversationStore(tmp_path / "state")
+ sid = "abc123def456"
+ # An interrupted turn left a call with no result, followed by the next user message.
+ store.save(_record(sid, [{"role": "user", "content": "go"}, _assistant_call("c1"),
+ {"role": "user", "content": "next"}]))
+
+ rec = store.load(sid) # heals: placeholder inserted after the call
+ assert [m["role"] for m in rec.messages] == ["user", "assistant", "tool", "user"]
+ rec.messages.append({"role": "assistant", "content": "answer"})
+ store.save(rec)
+
+ assert _file_lines(store, sid) == rec.messages
+ # And it stays correct across another load-and-save cycle.
+ again = store.load(sid)
+ assert again.messages == rec.messages
+ store.save(again)
+ assert _file_lines(store, sid) == rec.messages
+ assert [m.get("content") for m in _file_lines(store, sid)].count("next") == 1
+
+
+def test_save_after_mid_history_insert_writes_the_inserted_message(tmp_path):
+ store = ConversationStore(tmp_path / "state")
+ sid = "abc123def457"
+ msgs = [{"role": "user", "content": "go"}, _assistant_call("c1"),
+ {"role": "tool", "tool_call_id": "c1", "content": "{}"}, {"role": "user", "content": "more"}]
+ store.save(_record(sid, msgs))
+ # Something inserts a message in the middle (as the engine's dangling-call repair does),
+ # then a new message is appended.
+ msgs.insert(1, {"role": "notice", "kind": "note", "text": "inserted"})
+ msgs.append({"role": "assistant", "content": "done"})
+ store.save(_record(sid, msgs))
+ assert _file_lines(store, sid) == msgs
+
+
+def test_restart_mid_approval_then_mode_switch_then_new_turn(tmp_path):
+ """The sequence seen in the app: a turn parks on an approval and is saved, the app is
+ quit, the reopened session switches mode (a notice is saved after the parked call),
+ then a new message runs `_repair_dangling_tool_calls`, which inserts the stub between
+ the call and the notice."""
+ from types import SimpleNamespace
+
+ from coworker.engine import TurnEngine
+
+ store = ConversationStore(tmp_path / "state")
+ sid = "abc123def459"
+ store.save(_record(sid, [{"role": "user", "content": "run it"}, _assistant_call("c1")]))
+
+ rec = store.load(sid) # trailing call: pending, left as is
+ rec.messages.append({"role": "notice", "kind": "mode_switch", "text": "Discuss is on."})
+ store.save(rec)
+
+ TurnEngine._repair_dangling_tool_calls(SimpleNamespace(messages=rec.messages))
+ rec.messages.append({"role": "user", "content": "never mind"})
+ rec.messages.append({"role": "assistant", "content": "OK"})
+ store.save(rec)
+
+ assert _file_lines(store, sid) == rec.messages
+ assert [m["role"] for m in _file_lines(store, sid)] == [
+ "user", "assistant", "tool", "notice", "user", "assistant"]
+
+
+def test_plain_append_still_appends(tmp_path):
+ """The common path stays an append: the existing lines are not rewritten."""
+ store = ConversationStore(tmp_path / "state")
+ sid = "abc123def458"
+ msgs = [{"role": "user", "content": "go"}, {"role": "assistant", "content": "ok"}]
+ store.save(_record(sid, msgs))
+ path = store._file(sid)
+ before = path.stat().st_ino if hasattr(path.stat(), "st_ino") else None
+ head = path.read_text(encoding="utf-8")
+ msgs.append({"role": "user", "content": "again"})
+ store.save(_record(sid, msgs))
+ text = path.read_text(encoding="utf-8")
+ assert text.startswith(head)
+ assert _file_lines(store, sid) == msgs
+ if before is not None and before != 0:
+ assert path.stat().st_ino == before # same file, appended to, not replaced