The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(sessions): one transcript-format rule and one missing-display-index probe
kshitijk4poor880b9cd444a9
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex e433b71836f..a10305f970f 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -332,15 +332,17 @@ def _cmd_export(db, args):from hermes_cli.session_export_md import redact_session_datareturn redact_session_data(data)- # HTML and --only are read by people, so they carry the turns in-place compaction archived; JSONL stays the- # live rows import_sessions restores.- shown = args.format == "html" or bool(getattr(args, "only", None))+ from hermes_cli.session_export import SAVE_TRANSCRIPT_FORMATS+ # --only is a transcript view too (md/jsonl of what the user saw); md/qmd without --only go to _export_markdown.+ shown = args.format in SAVE_TRANSCRIPT_FORMATS or bool(getattr(args, "only", None))def _collect_sessions():"""--session-id / filters / bare export -> redacted session dicts, or None after printing an error."""+ def _one(session_id):+ return _redact(db.export_session(session_id, include_compacted=shown))if args.session_id:resolved = db.resolve_session_id(args.session_id)- data = _redact(db.export_session(resolved, include_compacted=shown)) if resolved else None+ data = _one(resolved) if resolved else Noneif not data:_not_found(args.session_id)return None@@ -349,7 +351,7 @@ def _cmd_export(db, args):candidates = db.list_prune_candidates(**filters)if args.dry_run:return _print_dry_run_preview(candidates, filters)- return [s for s in (_redact(db.export_session(row["id"], include_compacted=shown)) for row in candidates) if s]+ return [s for s in (_one(row["id"]) for row in candidates) if s]if args.dry_run:return print("--dry-run requires at least one filter.")return [_redact(s) for s in db.export_all(source=None, include_compacted=shown)]@@ -547,8 +549,8 @@ def _export_markdown_single(db, args, export_one, output_dir, lineage_is_logicalf"to {exported_items[0][1] if n == 1 else output_dir}")if not args.delete_after_verified:return- # The file only proves it matches the dict it was written from. Whether the store still holds that history- # is decided inside delete_session's transaction (expected_display_messages), so no caller-side re-read.+ # verify_export_file proves file == dict; store == dict is decided inside delete_session's transaction+ # (expected_display_messages), where no writer can slip between the check and the delete.expected_messages = {}for data, exported_path, snapshots in exported_items:ok, reason = verify_export_file(exported_path, data)diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 61fef4b6f95..a1aa9ed6372 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -46,6 +46,10 @@ _TURN_LEASE_ROW_SQL = "SELECT holder, expires_at FROM session_turn_leases WHERE_DELETE_COMPRESSION_LOCK_SQL = "DELETE FROM compression_locks WHERE session_id = ? AND holder = ?"_DISPLAY_ACTIVE_CLAUSE = " AND (active = 1 OR compacted = 1)"_DISPLAY_META_ROW_SQL = "SELECT display_metadata FROM messages WHERE id = ? AND session_id IN ({ids})" + _DISPLAY_ACTIVE_CLAUSE+# A display row is indexed only when both halves are set; the read path backfills before projecting, so+# the in-transaction delete fence must refuse (not project) any session this probe still matches.+_DISPLAY_INDEX_MISSING_SQL = ("SELECT 1 FROM messages WHERE session_id = ?" + _DISPLAY_ACTIVE_CLAUSE+ + " AND (display_order IS NULL OR display_identity IS NULL) LIMIT 1")_ACTIVE_IDS_SQL = "SELECT id FROM messages WHERE session_id = ? AND active = 1 ORDER BY id"_LIVE_IDENTITY_SQL = ("SELECT id, role, content, tool_call_id, tool_calls FROM messages ""WHERE session_id = ? AND active = 1 ORDER BY id LIMIT ?")@@ -899,16 +903,13 @@ class SessionMessagesMixin:columns = set(self._message_column_names(conn))if not {"display_order", "display_identity"} <= columns:return False- missing_sql = (- "SELECT 1 FROM messages WHERE session_id = ? AND (active = 1 OR compacted = 1) "- "AND (display_order IS NULL OR display_identity IS NULL) LIMIT 1")- if self._read_one(missing_sql, (session_id,)) is None:+ if self._read_one(_DISPLAY_INDEX_MISSING_SQL, (session_id,)) is None:return Trueif getattr(self, "read_only", False):return Falsedef _do(conn):- missing = conn.execute(missing_sql, (session_id,)).fetchone()+ missing = conn.execute(_DISPLAY_INDEX_MISSING_SQL, (session_id,)).fetchone()if missing is None:return Truefirst_id: Dict[bytes, int] = {}@@ -1030,10 +1031,7 @@ class SessionMessagesMixin:"""Exact display snapshot on an already-held transaction; None means fail closed."""if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None:return None- if conn.execute(- "SELECT 1 FROM messages WHERE session_id = ? AND (active = 1 OR compacted = 1) "- "AND display_order IS NULL LIMIT 1", (session_id,),- ).fetchone():+ if conn.execute(_DISPLAY_INDEX_MISSING_SQL, (session_id,)).fetchone():return Nonereturn [self._row_to_message_dict(row, warn_context="verified delete", summary_flag=True)@@ -1057,7 +1055,7 @@ class SessionMessagesMixin:raise ValueError("after_id is incompatible with include_compacted (deduped display reads use offset paging)")active_clause = self._active_clause(include_inactive, include_compacted)if include_compacted and not include_inactive and self._ensure_display_order(session_id):- # Route through the IOERR-retrying reader (#100871), never a bare _read_ctx.+ # _read_retrying_ioerr: mode=ro pooled readers see a transient IOERR mid-checkpoint (#100871).rows = self._read_retrying_ioerr(lambda conn: self._display_rows_from_conn(conn, session_id, limit=limit, offset=offset, latest=latest))diff --git a/tests/hermes_state/test_read_path_transient_ioerr.py b/tests/hermes_state/test_read_path_transient_ioerr.pyindex 1e6be6cf545..83ef5e7247c 100644--- a/tests/hermes_state/test_read_path_transient_ioerr.py+++ b/tests/hermes_state/test_read_path_transient_ioerr.py@@ -15,7 +15,7 @@ class _FlakyReads(sqlite3.Connection):"""Real SQLite connection whose first N SELECTs fail the way a mid-checkpoint mode=ro reader does."""def execute(self, sql, *args, **kwargs): # type: ignore[override]- if str(sql).lstrip().upper().startswith(_STATE["fail_prefix"]):+ if str(sql).lstrip().upper().startswith(_STATE["fail_prefix"].upper()):_STATE["attempts"] += 1if _STATE["failures_left"] > 0:_STATE["failures_left"] -= 1@@ -62,11 +62,13 @@ def test_persistent_ioerr_propagates_after_the_budget(db):assert db._db_corrupt is False # busy/EIO is not corruption: no quarantine[email protected]("include_compacted, fail_prefix", [(False, "SELECT"), (True, "WITH")])[email protected]("include_compacted, fail_prefix", [(False, "SELECT"), (True, "WITH page AS")])def test_transient_ioerr_on_get_messages_is_retried(db, include_compacted, fail_prefix):"""Both message read paths -- live rows and the deduped display-history CTE -- replay a transient IOERR."""db.append_message("s", "user", "hi")- _STATE.update(failures_left=1, attempts=0, fail_prefix=fail_prefix) # WITH: only the display CTE can fail+ # "WITH page AS" names the display CTE itself: _ensure_display_order's SELECT probe runs first and must not+ # absorb the failure, and a reshaped query that no longer runs through the retrying reader fails loudly.+ _STATE.update(failures_left=1, attempts=0, fail_prefix=fail_prefix)rows = db.get_messages("s", include_compacted=include_compacted)assert [r["content"] for r in rows] == ["hi"]assert _STATE["failures_left"] == 0 and _STATE["attempts"] == 2 # one failure, one replay