diff --git a/hermes_cli/session_lost_and_found.py b/hermes_cli/session_lost_and_found.py index 2945acb742..368e0c885f 100644 --- a/hermes_cli/session_lost_and_found.py +++ b/hermes_cli/session_lost_and_found.py @@ -11,7 +11,9 @@ import sqlite3 import subprocess import tempfile from pathlib import Path -from typing import Any, Optional +from typing import Any, Optional, Sequence + +from hermes_cli.session_schema_history import SCHEMA_HISTORY, reachable_physical_layouts from hermes_cli.session_recovery import ( _AUXILIARY_TABLE_SCHEMAS, _AUXILIARY_TABLES, _CANONICAL_TABLES, _count_rows, _immediate_transaction, @@ -31,66 +33,23 @@ KNOWN_SOURCES = frozenset({ "tool", "subagent", "cron", "recovered", "imported", "acp", }) -# Historical sessions layouts. Columns are only ever appended, so an older record is a strict prefix. -SESSIONS_LAYOUT_NFIELDS = frozenset({55, 54, 52}) +# A record's field count is the column count of the table when the row was last written. It classifies +# the record but says nothing about which column each cell belongs to — live stores gain columns through +# ``_reconcile_columns()`` (ALTER TABLE ADD COLUMN), appended in physical add order, while SCHEMA_SQL +# declares several mid-definition (#101409). Cells are mapped by name through the layout +# ``infer_physical_layouts`` recovers, never zipped onto declared order. SESSIONS_LEGACY_MINIMAL_NFIELD = 14 SESSION_MODEL_USAGE_NFIELD = 18 -# Physical column order of a store that has been upgraded in place rather -# than created at the current schema: ``_reconcile_columns()`` APPENDS every -# newly declared column with ALTER TABLE ADD COLUMN, so the table keeps the -# order in which columns were added, not the order SCHEMA_SQL declares them. -# A record with N fields carries the first N names of the matching list -# (SQLite does not rewrite existing rows when a column is added). -# -# The sessions/messages orders below are the ones reported and verified -# against real salvaged rows in #101409, extended with the columns declared -# after that report (they are appended in the same way on any store upgraded -# since). Stores that also carry a column which was declared and then removed -# again (sessions.handoff_pending, sessions.icon, -# messages.anthropic_content_blocks — each shipped for days) are shifted from -# both known orders; such rows fail layout validation below and fall back to -# the conservative path rather than being mis-mapped. -PHYSICAL_LAYOUTS: dict[str, tuple[str, ...]] = { - "sessions": ( - "id", "source", "user_id", "model", "model_config", - "system_prompt", "parent_session_id", "started_at", "ended_at", - "end_reason", "message_count", "tool_call_count", "input_tokens", - "output_tokens", "cache_read_tokens", "cache_write_tokens", - "reasoning_tokens", "billing_provider", "billing_base_url", - "billing_mode", "estimated_cost_usd", "actual_cost_usd", - "cost_status", "cost_source", "pricing_version", "title", - "api_call_count", "handoff_state", "handoff_platform", - "handoff_error", "cwd", "rewind_count", "archived", - "session_key", "chat_id", "chat_type", "thread_id", "git_branch", - "git_repo_root", "compression_failure_cooldown_until", - "compression_failure_error", "display_name", "origin_json", - "expiry_finalized", "compression_fallback_streak", - "profile_name", "compression_ineffective_count", "pinned", - "system_prompt_hash", "last_activity_at", - "last_activity_description", "last_activity_provenance", - "git_metadata_generation", "title_source", "hidden", - "last_read_at", "compression_recovery_deadline", "tool_names", - ), - "messages": ( - "id", "session_id", "role", "content", "tool_call_id", - "tool_calls", "tool_name", "timestamp", "token_count", - "finish_reason", "reasoning", "reasoning_content", - "reasoning_details", "codex_reasoning_items", - "codex_message_items", "platform_message_id", "observed", - "active", "compacted", "effect_disposition", "api_content", - "display_kind", "display_metadata", "_compressed_summary", - ), - # Same class on the usage table: ``task`` is declared sixth but was added - # last, and ``billing_mode``/cost columns are declared before the counters - # they were added after. - "session_model_usage": ( - "session_id", "model", "billing_provider", "billing_base_url", - "api_call_count", "input_tokens", "output_tokens", - "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", - "estimated_cost_usd", "first_seen", "last_seen", "billing_mode", - "actual_cost_usd", "cost_status", "cost_source", "task", - ), +# Per-table cells whose salvaged value must look like what the column name +# says. On stores created at the original schema these sit in the shared +# base prefix, so they veto a width outright (-> unrecognized) rather than +# pick between candidates; the per-column type and text-shape rules below +# carry the discrimination between layouts. +_LAYOUT_SENTINELS: dict[str, tuple[str, ...]] = { + "sessions": ("id", "source", "started_at"), + "messages": ("session_id", "role", "timestamp"), + "session_model_usage": ("session_id", "model"), } # Plausible unix-epoch window for started_at heuristics on legacy layouts. @@ -326,10 +285,9 @@ def classify_lost_and_found_row(nfield: int, cells: tuple[Any, ...]) -> Optional second = cells[1] if len(cells) > 1 else None if nfield == SESSION_MODEL_USAGE_NFIELD: # session id first, model string second return "session_model_usage" if isinstance(second, str) and second else None - # Known sessions layouts, or an unknown historical one (>= 30 fields): session id + source is enough. - if ( - nfield in SESSIONS_LAYOUT_NFIELDS or nfield == SESSIONS_LEGACY_MINIMAL_NFIELD or nfield >= 30 - ) and _looks_like_source(second): + # Any historical sessions width: session id first + recognizable source second (every sessions + # layout ever shipped has at least the 14 original columns). + if nfield >= SESSIONS_LEGACY_MINIMAL_NFIELD and _looks_like_source(second): return "sessions" return None @@ -350,20 +308,7 @@ def _insert_prefix_row( notnull_substitutes[index] if value is None and index in notnull_substitutes else value for index, value in enumerate(values) ] - quoted, placeholders = _quoted_columns(dest_columns[: len(values)]) - cursor = dest.execute(f'INSERT OR IGNORE INTO "{table}" ({quoted}) VALUES ({placeholders})', values) - return cursor.rowcount == 1 - - -# Columns whose salvaged value must look right before a candidate layout is -# accepted for a record. They are the cells that differ hardest between the -# declared and the upgraded-physical order, so a wrong layout is rejected -# instead of silently shifting every field. -_LAYOUT_SENTINELS: dict[str, tuple[str, ...]] = { - "sessions": ("id", "source", "started_at"), - "messages": ("session_id", "role", "timestamp"), - "session_model_usage": ("session_id", "model"), -} + return _execute_insert(dest, table, dest_columns[: len(values)], values) def _declared_types(conn: sqlite3.Connection, table: str) -> dict[str, str]: @@ -373,20 +318,43 @@ def _declared_types(conn: sqlite3.Connection, table: str) -> dict[str, str]: } - def _type_conflicts(value: Any, declared: str) -> bool: - """True when a salvaged cell cannot belong to a column of this type.""" + """True when a salvaged cell cannot have come from a column of this type. + + Stricter than SQLite affinity on purpose: SQLite would happily keep a + non-numeric string in an INTEGER column, but Hermes never writes one, so + text sitting where a counter is declared means the layout is wrong. A + TEXT column always yields ``str`` (numbers are coerced on write), a REAL + column always yields ``float``, an INTEGER column yields ``int``. + """ if value is None: return False affinity = declared.upper() - if "INT" in affinity or "REAL" in affinity or "FLOA" in affinity or "DOUB" in affinity: - return not isinstance(value, (int, float)) if "CHAR" in affinity or "CLOB" in affinity or "TEXT" in affinity: return not isinstance(value, str) + if "REAL" in affinity or "FLOA" in affinity or "DOUB" in affinity: + return not isinstance(value, float) + if "INT" in affinity: + return not isinstance(value, int) return False +# Shapes of the text columns that move between the declared and physical +# orders. A salvaged string that does not fit the shape rules out the +# column for that position; a string that fits does not prove it. Only +# invariants every writer in this repo honours belong here (this is how the +# columns are actually written, not how they could theoretically be). +_SESSION_KEY_PATTERN = re.compile(r"^agent:[^:]+:") +# Machine tokens (``compression``, ``agent.compression_timeout``, ``api_key``, +# ``compute_host_shutdown``): never spaces, never mixed case. +_TOKEN_PATTERN = re.compile(r"^[a-z][a-z0-9_.:-]*$") +# The closed sets SessionDB writes (hermes_state.py: request/claim/complete/ +# fail_handoff; TITLE_SOURCE_* + _title_rank). chat_type is platform-supplied +# and open-ended, so it only gets the identifier shape. +_HANDOFF_STATES = frozenset({"pending", "running", "completed", "failed"}) +_TITLE_SOURCES = frozenset({"derived", "llm", "user"}) + def _sentinel_holds(name: str, value: Any) -> bool: if name == "id": # sessions.id; messages.id is a rowid alias, never a sentinel @@ -407,86 +375,224 @@ def _sentinel_holds(name: str, value: Any) -> bool: return True +def _text_shape_holds(kind: str, name: str, value: str) -> bool: + """Cheap per-column shape rules for text cells (see module comment above).""" -def _layout_fits_cells( - kind: str, - layout: list[str], - cells: tuple[Any, ...], - dest_types: dict[str, str], + if kind == "sessions": + if name == "session_key": + return bool(_SESSION_KEY_PATTERN.match(value)) + if name in ("chat_type", "end_reason", "cost_status", "cost_source", + "billing_mode", "last_activity_provenance", "handoff_platform"): + return bool(_TOKEN_PATTERN.match(value)) + if name == "pricing_version": + return bool(re.fullmatch(r"[a-z0-9][a-z0-9._-]*", value)) + if name == "title_source": + return value in _TITLE_SOURCES + if name == "handoff_state": + return value in _HANDOFF_STATES + if name == "parent_session_id": + return _is_session_id(value) + if name == "system_prompt_hash": + return bool(re.fullmatch(r"[0-9a-f]{64}", value)) + if name in ("model_config", "origin_json"): + return value[:1] in "{[" + if name in ("cwd", "git_repo_root"): + return value[:1] in "/~" or (len(value) > 1 and value[1] == ":") + if name == "billing_base_url": + return "://" in value + return True + if kind == "messages": + if name == "effect_disposition": + return bool(_TOKEN_PATTERN.match(value)) + if name in ("tool_calls", "reasoning_details", "codex_reasoning_items", + "codex_message_items", "api_content", "display_metadata"): + return value[:1] in "{[" or value == "" + if name in ("finish_reason", "display_kind"): + return bool(_TOKEN_PATTERN.match(value)) + return True + if kind == "session_model_usage": + if name == "billing_base_url": + return "://" in value or value == "" + if name in ("billing_mode", "cost_status", "cost_source"): + return value == "" or bool(_TOKEN_PATTERN.match(value)) + return True + return True + + +def _cell_fits(kind: str, name: str, value: Any, dest_types: dict[str, str]) -> bool: + if value is None: + return True + if name in _LAYOUT_SENTINELS[kind] and not _sentinel_holds(name, value): + return False + declared = dest_types.get(name) + # Columns since removed from the schema have no destination type; any + # value is admissible there (and is dropped on insert). + if declared is None: + return True + if _type_conflicts(value, declared): + return False + return not isinstance(value, str) or _text_shape_holds(kind, name, value) + + +def _row_invariants_hold( + kind: str, layout: tuple[str, ...], rows: Sequence[tuple[Any, ...]] ) -> bool: + """Cross-column invariants every writer honours, checked per record. + + ``handoff_error`` is only ever written together with ``handoff_state`` + (``mark_handoff_failed``); a record with a value at the position a + candidate calls ``handoff_error`` but NULL where it calls + ``handoff_state`` cannot have come from that layout. This is what + separates ``cwd`` from ``handoff_error`` when a store's rows never + handed off — the two are otherwise both free-form TEXT. + """ + + if kind != "sessions": + return True positions = {name: index for index, name in enumerate(layout)} - for name in _LAYOUT_SENTINELS[kind]: - if name not in positions or positions[name] >= len(cells): - return False - if not _sentinel_holds(name, cells[positions[name]]): - return False - for name, value in zip(layout, cells): - declared = dest_types.get(name) - if declared is not None and _type_conflicts(value, declared): + error_at = positions.get("handoff_error") + state_at = positions.get("handoff_state") + if error_at is None or state_at is None: + return True + for row in rows: + if ( + error_at < len(row) + and row[error_at] is not None + and (state_at >= len(row) or row[state_at] is None) + ): return False return True - -def select_physical_layout( +def infer_physical_layouts( kind: str, - cells: tuple[Any, ...], - dest_columns: list[str], + rows: Sequence[tuple[Any, ...]], dest_types: dict[str, str], -) -> Optional[list[str]]: - """Return the source column names for ``cells``, or None if unknown. +) -> dict[int, list[Optional[str]]]: + """Infer which source column each record position holds, per field count. - A salvaged record carries no schema, so the only way to know which cell - is ``started_at`` is to recognise the layout that produced it. Two are - known: the destination's own declared order (a store created at the - current schema, never ALTERed) and the upgraded-in-place physical order - (#101409). Both are checked against the record's sentinel cells and - column affinities; an unrecognised layout returns None so the caller can - fall back conservatively instead of shifting every field. + Salvaged records carry no schema. Every layout a real store can have is, + however, a known chain over the shipped schema history (see + ``session_schema_history``): the declared order at creation plus every + later column appended at upgrade time. This walks that graph, pruning + every branch whose column names contradict the salvaged cells (sentinel + columns must look like what they name; every cell must fit its column's + type affinity), and keeps the layouts that fit ALL records at once — the + whole population of a table was written by one store, so one physical + order produced every record of a given width. + + Returns, for each distinct record width, the column name each position + resolves to. A position is ``None`` when the surviving layouts disagree + on it (the cells there did not discriminate — typically all NULL/zero + counters) so the caller can leave that column alone rather than guess. + Returns an empty dict when no known layout fits the records. """ - candidates: list[list[str]] = [] - for full in (dest_columns, list(PHYSICAL_LAYOUTS.get(kind, ()))): - candidate = full[: len(cells)] - if candidate and candidate not in candidates: - candidates.append(candidate) - for candidate in candidates: - if _layout_fits_cells(kind, candidate, cells, dest_types): - return candidate - return None + if kind not in SCHEMA_HISTORY or not rows: + return {} + widths = sorted({len(row) for row in rows}) + # Distinct non-NULL values per position: a column's admissibility is a + # property of the value, not the row, and salvaged populations repeat + # values heavily (flags, counters, roles). Cap the sample per position — + # a few hundred distinct values discriminate as well as 150k. + by_position: list[set[Any]] = [set() for _ in range(widths[-1])] + for row in rows: + for index, value in enumerate(row): + if value is not None and len(by_position[index]) < 512: + by_position[index].add(value) + verdicts: dict[tuple[str, Any], bool] = {} + def fits(name: str, value: Any) -> bool: + key = (name, value) + verdict = verdicts.get(key) + if verdict is None: + verdict = verdicts[key] = _cell_fits(kind, name, value, dest_types) + return verdict + + # Cross-column invariants need whole rows, not per-position value sets; + # a candidate of width ``w`` only ever names the rows of that width. + rows_by_width: dict[int, list[tuple[Any, ...]]] = {w: [] for w in widths} + for row in rows: + rows_by_width[len(row)].append(row) + + def accept(layout: tuple[str, ...], first_new: int) -> bool: + for index in range(first_new, min(len(layout), len(by_position))): + name = layout[index] + for value in by_position[index]: + if not fits(name, value): + return False + same_width = rows_by_width.get(len(layout)) + return not same_width or _row_invariants_hold(kind, layout, same_width) + + # Enumerate once and bucket by width. A record of width ``k`` was written + # while the table had exactly ``k`` columns (ADD COLUMN runs at startup, + # before any row is written), so its layout is a chain state of exactly + # that length. + survivors_by_width: dict[int, list[tuple[str, ...]]] = {w: [] for w in widths} + for layout in reachable_physical_layouts(kind, accept): + bucket = survivors_by_width.get(len(layout)) + if bucket is not None and layout not in bucket: + bucket.append(layout) + + result: dict[int, list[Optional[str]]] = {} + for width, survivors in survivors_by_width.items(): + if not survivors: + continue + # Per-position consensus. Where the survivors disagree the cells did + # not discriminate (they fit every candidate column), so no name is + # evidence — the destination's own declared order included. Leave + # such positions alone rather than guess; the cells there are, by + # construction, values several columns could legitimately hold. + consensus: list[Optional[str]] = [] + for index in range(width): + names = {layout[index] for layout in survivors} + consensus.append(names.pop() if len(names) == 1 else None) + result[width] = consensus + return result def _insert_named_row( dest: sqlite3.Connection, table: str, - layout: list[str], + layout: Sequence[Optional[str]], cells: tuple[Any, ...], dest_columns: list[str], - notnull_substitutes: dict[str, Any], + notnull_substitutes: dict[int, Any], overrides: Optional[dict[str, Any]] = None, ) -> bool: - """INSERT salvaged cells by source column name, never by position.""" + """INSERT salvaged cells by source column name, never by position. - known = set(dest_columns) + ``layout[i]`` names the source column of ``cells[i]``; ``None`` positions + (ambiguous or since-removed columns) are skipped and take the destination + default. ``notnull_substitutes`` is index-keyed on ``dest_columns`` as + returned by ``_notnull_defaults``. + """ + + dest_index = {name: index for index, name in enumerate(dest_columns)} mapped: dict[str, Any] = {} for name, value in zip(layout, cells): - if name not in known: - continue # column dropped since the source was written - if value is None and name in notnull_substitutes: - value = notnull_substitutes[name] + index = dest_index.get(name) if name is not None else None + if index is None: + continue + if value is None and index in notnull_substitutes: + value = notnull_substitutes[index] mapped[name] = value + # NOT NULL columns the layout could not place (ambiguous or absent) take + # the same substitute the positional path uses, so the row still lands; + # the recovery verifier's plausibility gate audits the result. + for index, substitute in notnull_substitutes.items(): + mapped.setdefault(dest_columns[index], substitute) mapped.update(overrides or {}) - columns = list(mapped) - quoted = ", ".join(f'"{column}"' for column in columns) - placeholders = ", ".join("?" for _ in columns) - cursor = dest.execute( - f'INSERT OR IGNORE INTO "{table}" ({quoted}) VALUES ({placeholders})', - [mapped[column] for column in columns], - ) - return cursor.rowcount == 1 + return _execute_insert(dest, table, list(mapped), list(mapped.values())) +def _execute_insert( + dest: sqlite3.Connection, table: str, columns: list[str], values: list[Any] +) -> bool: + quoted, placeholders = _quoted_columns(columns) + cursor = dest.execute(f'INSERT OR IGNORE INTO "{table}" ({quoted}) VALUES ({placeholders})', values) + return cursor.rowcount == 1 + def _copy_direct_tables(lf_conn: sqlite3.Connection, dest: sqlite3.Connection) -> dict[str, int]: """Copy rows .recover managed to attribute to real canonical tables.""" @@ -517,7 +623,7 @@ def map_lost_and_found_rows(lf_conn: sqlite3.Connection, dest: sqlite3.Connectio """Best-effort mapping of a .recover output DB into a fresh SessionDB.""" report: dict[str, Any] = { "direct_table_rows": {}, "mapped": {"sessions": 0, "messages": 0, "session_model_usage": 0}, - "legacy_minimal_sessions": 0, "mapped_by_layout": 0, "unrecognized_layout_rows": 0, + "legacy_minimal_sessions": 0, "mapped_by_layout": 0, "unrecognized_layout_rows": 0, "inferred_layouts": {}, "unmapped_rows": 0, "insert_conflicts": 0, "lost_and_found_tables": [], } with _immediate_transaction(dest): @@ -537,6 +643,10 @@ def map_lost_and_found_rows(lf_conn: sqlite3.Connection, dest: sqlite3.Connectio lf_conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'lost_and_found%'") ] report["lost_and_found_tables"] = lf_tables + + # Pass 1: classify every record and group it by kind. The physical layout is a property of the + # whole population (one store wrote all of them), so it is inferred once per kind, not per row. + classified: dict[str, list[tuple[Any, int, tuple[Any, ...]]]] = {kind: [] for kind in targets} for lf_table in lf_tables: if _table_columns(lf_conn, lf_table)[:3] != ["rootpgno", "pgno", "nfield"]: continue @@ -552,25 +662,39 @@ def map_lost_and_found_rows(lf_conn: sqlite3.Connection, dest: sqlite3.Connectio if kind is None: report["unmapped_rows"] += 1 continue - columns, defaults = targets[kind] - layout = select_physical_layout(kind, cells, columns, dest_types[kind]) + classified[kind].append((lf_rowid, nfield, cells)) + + layouts = { + kind: infer_physical_layouts(kind, [cells for _, _, cells in records], dest_types[kind]) + for kind, records in classified.items() + } + # Per kind and record width, the column each position resolved to (None where the surviving + # layouts disagreed and the cell was left to the destination default). + report["inferred_layouts"] = { + kind: {str(width): list(layout) for width, layout in by_width.items()} + for kind, by_width in layouts.items() if by_width + } + + # Pass 2: insert. Records whose width resolved to a layout are mapped by column name (#101409); + # the rest take the historical positional prefix, audited by the recovery verifier's plausibility gate. + for kind, records in classified.items(): + columns, defaults = targets[kind] + for lf_rowid, nfield, cells in records: + layout = layouts[kind].get(len(cells)) legacy_minimal = kind == "sessions" and nfield == SESSIONS_LEGACY_MINIMAL_NFIELD if layout is None and not legacy_minimal: - # No known layout produced these cells: the positional prefix below is a guess, so count - # it — the recovery verifier's plausibility gate keeps such a salvage from being "verified". report["unrecognized_layout_rows"] += 1 try: if layout is not None: - # Map cell to column by NAME (#101409): zipping onto the destination's declared order - # shifts every field of a store upgraded via ALTER TABLE ADD COLUMN. + # messages.id is a rowid alias: NULL in the record, carried by the lost_and_found row id. inserted = _insert_named_row( - dest, kind, layout, cells, columns, - {columns[index]: value for index, value in defaults.items() if index < len(columns)}, + dest, kind, layout, cells, columns, defaults, {"id": lf_rowid} if kind == "messages" else None, ) report["mapped_by_layout"] += int(inserted) elif legacy_minimal: - # Pre-modern layout with unknown column order: salvage identity + timing only. + # A 14-field record matching no known layout (torn cells, or a pre-history store): + # salvage identity + timing rather than guessing 14 positional meanings. row_values = ( cells[0], cells[1] if _looks_like_source(cells[1]) else "recovered", _heuristic_started_at(cells), @@ -582,7 +706,6 @@ def map_lost_and_found_rows(lf_conn: sqlite3.Connection, dest: sqlite3.Connectio ).rowcount == 1 report["legacy_minimal_sessions"] += int(inserted) else: - # messages: the rowid-alias PK is NULL in the record; use the lost_and_found rowid. values = list(cells[:len(columns)]) if kind == "messages": values[0] = lf_rowid diff --git a/hermes_cli/session_recovery.py b/hermes_cli/session_recovery.py index 7b09f11901..3d1f6ec208 100644 --- a/hermes_cli/session_recovery.py +++ b/hermes_cli/session_recovery.py @@ -1025,6 +1025,18 @@ def _recover_via_lost_and_found( plausibility_errors = _lost_and_found_plausibility_errors(plausibility_conn) finally: plausibility_conn.close() + # Records whose width matched no known physical layout were inserted + # positionally as a guess. Once the recognised rows map correctly the + # all-rows timestamp gate above no longer sees them, so they need their + # own tell: the guessed rows may be shifted while the report otherwise + # looks clean. + guessed = int(mapping.get("unrecognized_layout_rows") or 0) + if guessed: + plausibility_errors.append( + f"{guessed} salvaged row(s) matched no known physical column " + "layout and were mapped positionally; their fields may be " + "shifted. Inspect the affected sessions before trusting them." + ) if plausibility_errors: verification["errors"].extend(plausibility_errors) verification["healthy"] = False diff --git a/hermes_cli/session_schema_history.py b/hermes_cli/session_schema_history.py new file mode 100644 index 0000000000..a792eb0da4 --- /dev/null +++ b/hermes_cli/session_schema_history.py @@ -0,0 +1,254 @@ +"""Physical column history of the state.db tables the page-level salvage lane maps. + +``_reconcile_columns()`` (hermes_state_schema.py) upgrades a live store with +``ALTER TABLE ADD COLUMN``, which APPENDS each newly declared column. A store +therefore keeps its columns in the order they were *added*, which diverges +from the order ``SCHEMA_SQL`` declares them whenever a later release inserts a +column mid-definition (#101409). SQLite never rewrites existing rows on ADD +COLUMN either, so a row written when the table had ``k`` columns carries +exactly the first ``k`` physical names. + +A ``lost_and_found`` record carries no schema, so the salvage lane has to +recognise the physical layout that produced it. This module is the single +source of truth for that: the declared order of every table as first shipped +(``base``) and, per release that changed it, the edits made to the +declaration (``events``). Replaying the events reproduces every historical +declared order, and every physical layout a real store can have is some +prefix chain over those snapshots (created at snapshot ``i``, then each later +upgrade appending the columns it had not seen yet). + +``tests/hermes_cli/test_session_schema_history.py`` asserts the replay ends +at the current ``SCHEMA_SQL``. When that test fails you added or moved a +column: append an event at the END, labelled with the next sequence number, +describing the edit (``("+", column, after)`` / ``("-", column)``) — do NOT +rewrite or reorder older events, real stores were shaped by them. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Callable, Iterator, Optional, Sequence + + +Edit = tuple # ("+", column, previous_column_or_None) | ("-", column) + + +@dataclass(frozen=True) +class _TableHistory: + base: tuple[str, ...] + # (label, edits) in replay order. Labels are " + # " of the main commit that shipped the edit; the sequence number + # is what the ordering test checks, so an event appended out of order + # (or inserted mid-list "to keep dates sorted") fails loudly. + events: tuple[tuple[str, tuple[Edit, ...]], ...] + + +def _apply(columns: list[str], edits: Sequence[Edit]) -> None: + for edit in edits: + if edit[0] == "-": + columns.remove(edit[1]) + continue + _, column, after = edit + columns.insert(0 if after is None else columns.index(after) + 1, column) + + +def declared_snapshots(table: str) -> list[tuple[str, ...]]: + """Every declared column order the table has shipped with, oldest first.""" + + history = SCHEMA_HISTORY[table] + columns = list(history.base) + snapshots = [tuple(columns)] + for _date, edits in history.events: + _apply(columns, edits) + snapshots.append(tuple(columns)) + return snapshots + + +def current_declared_columns(table: str) -> tuple[str, ...]: + return declared_snapshots(table)[-1] + + +def reachable_physical_layouts( + table: str, + accept: Optional[Callable[[tuple[str, ...], int], bool]] = None, +) -> Iterator[tuple[str, ...]]: + """Yield every physical layout an upgraded store of ``table`` can have. + + A store created at snapshot ``i`` and later opened by releases + ``j1 < j2 < ...`` appends, at each step, the snapshot's columns it does + not have yet. Columns declared and later removed stay physically present + (``_reconcile_columns`` never drops), so they appear in layouts too. + + ``accept(layout, first_new_index)`` lets the caller prune: it is called + for every new layout with the index where it starts to differ from its + parent, and a False return stops extending that branch. The graph is + large without pruning (~230k sessions layouts) but salvage always + prunes against real cells, which keeps it in the low thousands. + """ + + snapshots = declared_snapshots(table) + seen: dict[tuple[str, ...], int] = {} + frontier: list[tuple[tuple[str, ...], int]] = [] + for index, snapshot in enumerate(snapshots): + if snapshot in seen: + continue + if accept is not None and not accept(snapshot, 0): + continue + seen[snapshot] = index + frontier.append((snapshot, index)) + yield snapshot + while frontier: + next_frontier: list[tuple[tuple[str, ...], int]] = [] + for layout, index in frontier: + have = set(layout) + for later in range(index + 1, len(snapshots)): + added = tuple(c for c in snapshots[later] if c not in have) + if not added: + continue + candidate = layout + added + if candidate in seen and seen[candidate] <= later: + continue + if accept is not None and not accept(candidate, len(layout)): + continue + seen[candidate] = later + next_frontier.append((candidate, later)) + yield candidate + frontier = next_frontier + + +SCHEMA_HISTORY: dict[str, _TableHistory] = { + "sessions": _TableHistory( + base=( + 'id', 'source', 'user_id', 'model', 'model_config', + 'system_prompt', 'parent_session_id', 'started_at', 'ended_at', + 'end_reason', 'message_count', 'tool_call_count', 'input_tokens', + 'output_tokens', + ), + events=( + ('01 2026-03-08T23:32Z c5e8166c8b', (('+', 'title', 'output_tokens'),)), + ('02 2026-03-17T10:44Z d417ba2a48', ( + ('+', 'cache_read_tokens', 'output_tokens'), + ('+', 'cache_write_tokens', 'cache_read_tokens'), + ('+', 'reasoning_tokens', 'cache_write_tokens'), + ('+', 'billing_provider', 'reasoning_tokens'), + ('+', 'billing_base_url', 'billing_provider'), + ('+', 'billing_mode', 'billing_base_url'), + ('+', 'estimated_cost_usd', 'billing_mode'), + ('+', 'actual_cost_usd', 'estimated_cost_usd'), + ('+', 'cost_status', 'actual_cost_usd'), + ('+', 'cost_source', 'cost_status'), + ('+', 'pricing_version', 'cost_source'), + )), + ('03 2026-04-22T12:51Z 5fb143169b', (('+', 'api_call_count', 'title'),)), + ('04 2026-05-10T20:06Z 878611a79d', ( + ('+', 'handoff_pending', 'api_call_count'), + ('+', 'handoff_platform', 'handoff_pending'), + )), + ('05 2026-05-10T20:06Z 00ce5f04d9', ( + ('-', 'handoff_pending'), + ('+', 'handoff_state', 'api_call_count'), + ('+', 'handoff_error', 'handoff_platform'), + )), + ('06 2026-05-31T22:46Z 51c68d4ab1', (('+', 'cwd', 'reasoning_tokens'),)), + ('07 2026-06-01T08:22Z 3e59be0c41', (('+', 'rewind_count', 'handoff_error'),)), + ('08 2026-06-02T01:41Z 85b65e29f0', (('+', 'archived', 'rewind_count'),)), + ('09 2026-06-25T22:49Z ffa3d3c811', ( + ('+', 'git_branch', 'cwd'), + ('+', 'git_repo_root', 'git_branch'), + )), + ('10 2026-06-28T22:10Z 86e64900b9', ( + ('+', 'session_key', 'user_id'), + ('+', 'chat_id', 'session_key'), + ('+', 'chat_type', 'chat_id'), + ('+', 'thread_id', 'chat_type'), + )), + ('11 2026-06-30T08:06Z f2ccb2859f', ( + ('+', 'compression_failure_cooldown_until', 'handoff_error'), + ('+', 'compression_failure_error', 'compression_failure_cooldown_until'), + )), + ('12 2026-07-05T21:01Z 747386ecfa', ( + ('+', 'display_name', 'thread_id'), + ('+', 'origin_json', 'display_name'), + ('+', 'expiry_finalized', 'origin_json'), + )), + ('13 2026-07-13T20:49Z af7dceaf77', ( + ('+', 'compression_fallback_streak', 'compression_failure_error'), + )), + ('14 2026-07-15T16:50Z e8b7ce8c19', (('+', 'profile_name', 'compression_fallback_streak'),)), + ('15 2026-07-23T15:08Z ec5835ab8b', ( + ('+', 'compression_ineffective_count', 'compression_fallback_streak'), + )), + ('16 2026-07-24T16:15Z 951d606730', (('+', 'pinned', 'archived'),)), + ('17 2026-07-27T19:14Z cfb206fe2e', ( + ('+', 'last_activity_at', 'title'), + ('+', 'last_activity_description', 'last_activity_at'), + ('+', 'last_activity_provenance', 'last_activity_description'), + )), + ('18 2026-07-27T19:22Z 5646fed97e', ( + ('-', 'last_activity_at'), + ('-', 'last_activity_description'), + ('-', 'last_activity_provenance'), + )), + ('19 2026-08-02T23:16Z c2088efe9e', ( + ('+', 'last_activity_at', 'title'), + ('+', 'last_activity_description', 'last_activity_at'), + ('+', 'last_activity_provenance', 'last_activity_description'), + )), + ('20 2026-08-03T15:07Z 7d066c3c56', (('+', 'system_prompt_hash', 'system_prompt'),)), + ('21 2026-08-04T19:20Z d98287fe3c', (('+', 'last_read_at', 'pinned'),)), + ('22 2026-08-08T22:17Z fe42097865', (('+', 'title_source', 'title'),)), + ('23 2026-08-15T07:31Z fbaea9bddc', (('+', 'hidden', 'pinned'),)), + ('24 2026-08-15T07:33Z e89532d97e', (('+', 'git_metadata_generation', 'git_repo_root'),)), + ('25 2026-09-02T11:14Z 238b6c1ab9', ( + ('+', 'compression_recovery_deadline', 'compression_ineffective_count'), + )), + ('26 2026-09-02T14:22Z 8e4366d358', (('+', 'tool_names', 'last_read_at'),)), + ), + ), + "messages": _TableHistory( + base=( + 'id', 'session_id', 'role', 'content', 'tool_call_id', + 'tool_calls', 'tool_name', 'timestamp', 'token_count', + ), + events=( + ('01 2026-02-21T08:05Z b33ed9176f', (('+', 'finish_reason', 'token_count'),)), + ('02 2026-03-25T16:47Z 42fec19151', ( + ('+', 'reasoning', 'finish_reason'), + ('+', 'reasoning_details', 'reasoning'), + ('+', 'codex_reasoning_items', 'reasoning_details'), + )), + ('03 2026-04-22T11:31Z a7d78d3bfd', (('+', 'reasoning_content', 'reasoning'),)), + ('04 2026-04-26T01:22Z 81e01f6ee9', (('+', 'codex_message_items', 'codex_reasoning_items'),)), + ('05 2026-05-20T20:00Z 31a0100104', (('+', 'platform_message_id', 'codex_message_items'),)), + ('06 2026-05-23T08:33Z 4a91e36495', (('+', 'observed', 'platform_message_id'),)), + ('07 2026-06-01T08:22Z 3e59be0c41', (('+', 'active', 'observed'),)), + ('08 2026-06-11T03:45Z aaccaada28', (('+', 'anthropic_content_blocks', 'reasoning_details'),)), + ('09 2026-06-11T03:45Z efcbbde48c', (('-', 'anthropic_content_blocks'),)), + ('10 2026-06-20T17:57Z 854d75723f', (('+', 'compacted', 'active'),)), + ('11 2026-07-11T12:41Z a0a6cd80f5', (('+', 'effect_disposition', 'tool_name'),)), + ('12 2026-07-19T02:55Z 7b3dcee928', (('+', 'api_content', 'compacted'),)), + ('13 2026-07-23T18:46Z a4bc1ca502', ( + ('+', 'display_kind', 'api_content'), + ('+', 'display_metadata', 'display_kind'), + )), + ('14 2026-08-25T10:55Z 1104ffe0b9', (('+', '_compressed_summary', 'observed'),)), + ), + ), + "session_model_usage": _TableHistory( + base=( + 'session_id', 'model', 'billing_provider', 'billing_base_url', + 'api_call_count', 'input_tokens', 'output_tokens', + 'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens', + 'estimated_cost_usd', 'first_seen', 'last_seen', + ), + events=( + ('01 2026-07-11T12:59Z 0d63c23f36', ( + ('+', 'billing_mode', 'billing_base_url'), + ('+', 'actual_cost_usd', 'estimated_cost_usd'), + ('+', 'cost_status', 'actual_cost_usd'), + ('+', 'cost_source', 'cost_status'), + )), + ('02 2026-07-16T11:23Z eb6aa03609', (('+', 'task', 'billing_mode'),)), + ), + ), +} diff --git a/tests/hermes_cli/test_session_recovery_lost_and_found.py b/tests/hermes_cli/test_session_recovery_lost_and_found.py index fc6e22364e..fc34e55b87 100644 --- a/tests/hermes_cli/test_session_recovery_lost_and_found.py +++ b/tests/hermes_cli/test_session_recovery_lost_and_found.py @@ -16,6 +16,7 @@ import pytest from hermes_state import SessionDB from hermes_cli import session_recovery +from hermes_cli import session_schema_history from hermes_cli.session_lost_and_found import ( STUB_TITLE_PREFIX, classify_lost_and_found_row, @@ -623,14 +624,28 @@ def _map_salvage_rows( def session_row(session_id: str) -> list: # title is UNIQUE (idx_sessions_title_unique) — keep it distinct # per row so the probe isolates timestamp mis-mapping. + # Five populated cells cannot pin a 58-column layout by + # themselves; the discriminating cells a real store carries + # (session_key, model_config, cwd, ...) make the declared order + # the only surviving layout, so the probe below isolates the + # timestamp gate rather than layout inference. row = { "id": session_id, "source": "telegram", + "session_key": f"agent:main:telegram:dm:{session_id}", + "chat_type": "dm", + "model": "gpt-4.1", + "model_config": "{}", "started_at": None if blank_session_started_at else 1_754_000_000.0, + "ended_at": 1_754_000_600.0, + "end_reason": "completed", "message_count": 2, + "cwd": "/home/user/project", "title": f"mis-mapped probe {session_id}", + "title_source": "llm", + "api_call_count": 1, } return [row.get(column) for column in sessions_columns] @@ -759,7 +774,10 @@ def _rebuild_with_started_at_appended(conn: sqlite3.Connection) -> None: reordered = [r for r in info if r[1] != "started_at"] + [r for r in info if r[1] == "started_at"] cols = ", ".join(f'"{c}"' for c in declared) - conn.executescript("PRAGMA foreign_keys=OFF;") + # ``messages_fts_trigram_src`` joins sessions; SQLite refuses to rename a + # table a view references unless legacy_alter_table is on (the view's + # body is text, so it re-resolves ``sessions`` after the swap). + conn.executescript("PRAGMA foreign_keys=OFF; PRAGMA legacy_alter_table=ON;") conn.execute("CREATE TABLE sessions_new (" + ", ".join(coldef(r) for r in reordered) + ")") conn.execute(f"INSERT INTO sessions_new({cols}) SELECT {cols} FROM sessions") conn.executescript("DROP TABLE sessions; ALTER TABLE sessions_new RENAME TO sessions;") @@ -825,42 +843,6 @@ def test_lost_and_found_lane_refuses_to_verify_a_physically_shifted_source( out.close() -def test_plausibility_gate_ignores_stub_only_sessions(tmp_path: Path) -> None: - """Stub rows from ``stub_missing_parent_sessions`` legitimately carry - ``started_at = 0.0``; a salvage where only stubs survived is depleted, - not mis-mapped, and must not be flagged.""" - output = tmp_path / "stubs.db" - SessionDB(db_path=output).close() - conn = sqlite3.connect(str(output)) - try: - now = 1_750_000_000.0 - conn.execute( - "INSERT INTO sessions (id, source, started_at, title) VALUES (?, ?, ?, ?)", - ("20260812_140000_aaa000", "recovered", 0.0, "[best-effort recovered 1] session metadata was unreadable"), - ) - conn.execute( - "INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)", - ("20260812_140000_aaa000", "user", "hi", now), - ) - conn.commit() - assert session_recovery._lost_and_found_plausibility_errors(conn) == [] - # One genuinely mapped row with a real timestamp keeps it clean too... - conn.execute( - "INSERT INTO sessions (id, source, started_at, title) VALUES (?, ?, ?, ?)", - ("20260812_140001_aaa001", "cli", now, None), - ) - conn.commit() - assert session_recovery._lost_and_found_plausibility_errors(conn) == [] - # ...and a mapped row at 0.0 with a NULL title (the mis-mapped shape: - # blank titles) is still counted as mapped, not as a stub. - conn.execute("UPDATE sessions SET started_at = 0.0 WHERE id = '20260812_140001_aaa001'") - conn.commit() - errors = session_recovery._lost_and_found_plausibility_errors(conn) - assert len(errors) == 1 and "sessions.started_at" in errors[0] - finally: - conn.close() - - # The physical column order of the reporter's upgraded store in #101409: # every column ALTER TABLE ADD COLUMN appended, in add order, which is NOT # the order SCHEMA_SQL declares them in. Written out literally (rather than @@ -885,7 +867,6 @@ _UPGRADED_SESSIONS_PHYSICAL = ( "hidden", "last_read_at", ) - _UPGRADED_MESSAGES_PHYSICAL = ( "id", "session_id", "role", "content", "tool_call_id", "tool_calls", "tool_name", "timestamp", "token_count", "finish_reason", "reasoning", @@ -895,7 +876,6 @@ _UPGRADED_MESSAGES_PHYSICAL = ( "display_metadata", "_compressed_summary", ) - _UPGRADED_USAGE_PHYSICAL = ( "session_id", "model", "billing_provider", "billing_base_url", "api_call_count", "input_tokens", "output_tokens", "cache_read_tokens", @@ -947,7 +927,7 @@ def test_upgraded_physical_layout_maps_cells_by_name(tmp_path: Path) -> None: "input_tokens": 1_234, "output_tokens": 567, "title": "quarterly planning notes", - "title_source": "model", + "title_source": "llm", "cwd": "/home/user/project", "git_branch": "main", "last_activity_at": started_at + 900.0, @@ -1063,3 +1043,261 @@ def test_upgraded_physical_layout_maps_cells_by_name(tmp_path: Path) -> None: finally: lf_conn.close() dest.close() + + +def test_plausibility_gate_ignores_stub_only_sessions(tmp_path: Path) -> None: + """Stub rows from ``stub_missing_parent_sessions`` legitimately carry + ``started_at = 0.0``; a salvage where only stubs survived is depleted, + not mis-mapped, and must not be flagged.""" + output = tmp_path / "stubs.db" + SessionDB(db_path=output).close() + conn = sqlite3.connect(str(output)) + try: + now = 1_750_000_000.0 + conn.execute( + "INSERT INTO sessions (id, source, started_at, title) VALUES (?, ?, ?, ?)", + ("20260812_140000_aaa000", "recovered", 0.0, "[best-effort recovered 1] session metadata was unreadable"), + ) + conn.execute( + "INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)", + ("20260812_140000_aaa000", "user", "hi", now), + ) + conn.commit() + assert session_recovery._lost_and_found_plausibility_errors(conn) == [] + # One genuinely mapped row with a real timestamp keeps it clean too... + conn.execute( + "INSERT INTO sessions (id, source, started_at, title) VALUES (?, ?, ?, ?)", + ("20260812_140001_aaa001", "cli", now, None), + ) + conn.commit() + assert session_recovery._lost_and_found_plausibility_errors(conn) == [] + # ...and a mapped row at 0.0 with a NULL title (the mis-mapped shape: + # blank titles) is still counted as mapped, not as a stub. + conn.execute("UPDATE sessions SET started_at = 0.0 WHERE id = '20260812_140001_aaa001'") + conn.commit() + errors = session_recovery._lost_and_found_plausibility_errors(conn) + assert len(errors) == 1 and "sessions.started_at" in errors[0] + finally: + conn.close() + + +def _upgraded_store_layout(table: str, created_at: int, upgrades: tuple[int, ...]) -> tuple[str, ...]: + """Physical order of a store created at snapshot ``created_at`` and later + opened by the releases at ``upgrades`` (each appends the columns it had + not seen), exactly as ``_reconcile_columns`` does.""" + snapshots = session_schema_history.declared_snapshots(table) + columns = list(snapshots[created_at]) + for index in upgrades: + columns.extend(c for c in snapshots[index] if c not in columns) + return tuple(columns) + + +def _write_lost_and_found(lf_path: Path, records: list[tuple[int, tuple[str, ...], dict]]) -> None: + width = max(len(layout) for _, layout, _ in records) + conn = sqlite3.connect(str(lf_path), isolation_level=None) + try: + columns = ", ".join(f"c{index}" for index in range(width)) + conn.execute( + "CREATE TABLE lost_and_found (rootpgno INTEGER, pgno INTEGER, " + "nfield INTEGER, id INTEGER, " + columns + ")" + ) + for rowid, layout, values in records: + cells = [values.get(name) for name in layout] + cells += [None] * (width - len(cells)) + placeholders = ", ".join("?" for _ in range(4 + width)) + conn.execute( + "INSERT INTO lost_and_found VALUES (" + placeholders + ")", + [2, 5, len(layout), rowid, *cells], + ) + finally: + conn.close() + + +# (creation snapshot, later upgrade snapshots) — a spread of real histories: +# a Feb-2026 v1 store upgraded monthly, a May store upgraded once to current, +# a July store, and one created at the current schema. +_UPGRADE_PATHS = [ + (0, (2, 5, 9, 12, 16, 20, 26)), + (5, (26,)), + (12, (18, 26)), + (20, (23, 26)), + (26, ()), +] + + +@pytest.mark.parametrize("created_at,upgrades", _UPGRADE_PATHS) +def test_any_upgrade_history_maps_cells_by_name( + tmp_path: Path, created_at: int, upgrades: tuple[int, ...] +) -> None: + """#101409 generalised: whatever release a store was created at and + however it was upgraded since, salvaged cells land on the columns they + were written from. The layout is inferred from the schema history plus + the salvaged values, not looked up in a hardcoded table.""" + + sessions_layout = _upgraded_store_layout("sessions", created_at, upgrades) + # messages/usage histories are shorter; pick the snapshot by date parity. + n_messages = len(session_schema_history.declared_snapshots("messages")) + n_usage = len(session_schema_history.declared_snapshots("session_model_usage")) + messages_layout = _upgraded_store_layout( + "messages", min(created_at // 2, n_messages - 1), + tuple(min(u // 2, n_messages - 1) for u in upgrades), + ) + usage_layout = _upgraded_store_layout( + "session_model_usage", min(created_at // 10, n_usage - 1), + tuple(min(u // 10, n_usage - 1) for u in upgrades), + ) + + output = tmp_path / "mapped.db" + SessionDB(db_path=output).close() + declared = sqlite3.connect(str(output)) + try: + sessions_declared = [r[1] for r in declared.execute("PRAGMA table_info(sessions)")] + finally: + declared.close() + shifted = sessions_declared[: len(sessions_layout)] != list(sessions_layout) + + started = 1_754_000_000.0 + records = [] + for index in range(3): + sid = f"2026070{index + 1}_101010_abc00{index}" + records.append((index + 1, sessions_layout, { + "id": sid, "source": "telegram", "model": "gpt-4.1", + "started_at": started + index, "ended_at": started + 600 + index, + "end_reason": "completed", "message_count": 4, "tool_call_count": 1, + "input_tokens": 100 + index, "output_tokens": 50, + "title": f"planning notes {index}", "cwd": "/home/user/project", + "archived": 0, "pinned": 0, "rewind_count": 0, "hidden": 0, + "api_call_count": 2, "expiry_finalized": 0, + })) + for m in range(2): + records.append((100 + index * 2 + m, messages_layout, { + "id": None, "session_id": sid, "role": "user" if m == 0 else "assistant", + "content": f"payload {index} {m}", "timestamp": started + 10 + m, + "token_count": 12, "finish_reason": "stop" if m else None, + "observed": 1, "active": 1, "compacted": 0, "_compressed_summary": 0, + })) + records.append((200 + index, usage_layout, { + "session_id": sid, "model": "gpt-4.1", "billing_provider": "openai", + "billing_base_url": "https://api.openai.com/v1", "billing_mode": "api", + "task": "", "api_call_count": 2, "input_tokens": 100 + index, + "output_tokens": 50, "cache_read_tokens": 0, "cache_write_tokens": 0, + "reasoning_tokens": 0, "estimated_cost_usd": 0.01, "actual_cost_usd": 0.0, + "first_seen": started, "last_seen": started + 600, + })) + lf_path = tmp_path / "lost_and_found.db" + _write_lost_and_found(lf_path, records) + + lf_conn = sqlite3.connect(str(lf_path), isolation_level=None) + dest = sqlite3.connect(str(output), isolation_level=None) + try: + dest.execute("PRAGMA foreign_keys=OFF") + report = map_lost_and_found_rows(lf_conn, dest) + assert report["mapped"] == {"sessions": 3, "messages": 6, "session_model_usage": 3} + assert report["unrecognized_layout_rows"] == 0 + rows = dest.execute( + "SELECT id, source, model, started_at, ended_at, message_count, title, cwd " + "FROM sessions ORDER BY id" + ).fetchall() + for index, row in enumerate(rows): + assert row == ( + f"2026070{index + 1}_101010_abc00{index}", "telegram", "gpt-4.1", + started + index, started + 600 + index, 4, + f"planning notes {index}", "/home/user/project", + ), (shifted, sessions_layout) + messages = dest.execute( + "SELECT role, content, timestamp, token_count, effect_disposition " + "FROM messages ORDER BY id" + ).fetchall() + assert [m[0] for m in messages] == ["user", "assistant"] * 3 + assert all(m[2] >= started for m in messages) + assert all(m[3] == 12 and m[4] is None for m in messages) + usage = dest.execute( + "SELECT model, billing_mode, task, api_call_count, input_tokens " + "FROM session_model_usage ORDER BY session_id" + ).fetchall() + assert usage == [("gpt-4.1", "api", "", 2, 100 + i) for i in range(3)] + assert session_recovery._lost_and_found_plausibility_errors(dest) == [] + finally: + lf_conn.close() + dest.close() + + +def test_unknown_layout_rows_fall_back_positionally_and_are_counted(tmp_path: Path) -> None: + """Records no known history produced (here: a sessions row whose sentinel + cells contradict every chain) take the positional guess and are counted + so the verifier can refuse to call the salvage verified.""" + + output = tmp_path / "mapped.db" + SessionDB(db_path=output).close() + declared = sqlite3.connect(str(output)) + try: + sessions_declared = tuple(r[1] for r in declared.execute("PRAGMA table_info(sessions)")) + finally: + declared.close() + # A 40-wide record with a text value where EVERY chain state of width 40 + # has a numeric column: no layout fits. + bogus = list(sessions_declared[:40]) + values = {"id": "20260701_101010_abc000", "source": "cli", "started_at": 1_754_000_000.0} + for name in bogus[2:]: + values[name] = "not-a-number" + lf_path = tmp_path / "lost_and_found.db" + _write_lost_and_found(lf_path, [(1, tuple(bogus), values)]) + + lf_conn = sqlite3.connect(str(lf_path), isolation_level=None) + dest = sqlite3.connect(str(output), isolation_level=None) + try: + dest.execute("PRAGMA foreign_keys=OFF") + report = map_lost_and_found_rows(lf_conn, dest) + finally: + lf_conn.close() + dest.close() + assert report["unrecognized_layout_rows"] == 1 + assert report["mapped_by_layout"] == 0 + assert report["inferred_layouts"] == {} + + +@pytest.mark.skipif( + not HAVE_SQLITE3_CLI, + reason="sqlite3 CLI not on PATH; .recover is a shell-only feature", +) +def test_recovery_lane_refuses_to_verify_when_rows_matched_no_layout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Wiring: ``unrecognized_layout_rows`` from the mapper must reach the + verifier — once the recognised rows map correctly, the all-rows + timestamp gate cannot see a few positionally guessed ones.""" + import hermes_cli.session_lost_and_found as lf_module + + real = lf_module.map_lost_and_found_rows + + def counting(lf_conn, dest): + report = real(lf_conn, dest) + report["unrecognized_layout_rows"] += 2 + return report + + monkeypatch.setattr(lf_module, "map_lost_and_found_rows", counting) + + source = tmp_path / "source.db" + output = tmp_path / "recovered.db" + db = SessionDB(db_path=source) + try: + sid = "20260812_140000_def000" + db.create_session(sid, "cli", cwd="/tmp/x") + db.append_message(sid, "user", "payload") + finally: + db.close() + conn = sqlite3.connect(str(source), isolation_level=None) + try: + conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") + conn.execute("PRAGMA journal_mode=DELETE") + conn.execute("VACUUM") + finally: + conn.close() + with open(source, "r+b") as fh: + fh.write(b"\0" * _page_size(source.read_bytes())) + + report = recover_session_database(source, output, work_dir=tmp_path, allow_partial=True) + assert report["mode"] == "lost_and_found_salvage" + assert report["lost_and_found"]["unrecognized_layout_rows"] == 2 + assert report["verified"] is False + assert any("matched no known physical column layout" in e for e in report["verification"]["errors"]) diff --git a/tests/hermes_cli/test_session_schema_history.py b/tests/hermes_cli/test_session_schema_history.py new file mode 100644 index 0000000000..7c4562ba20 --- /dev/null +++ b/tests/hermes_cli/test_session_schema_history.py @@ -0,0 +1,123 @@ +"""``hermes_cli.session_schema_history`` must track SCHEMA_SQL. + +The page-level salvage lane infers a salvaged store's physical column order +from this history. If a column is added to SCHEMA_SQL without an event here, +the newest rows of every upgraded store map to nothing (their width matches +no chain state) and silently take the positional fallback. +""" + +from __future__ import annotations + +import sqlite3 + +import pytest + +from hermes_cli import session_schema_history as history +from hermes_state_common import SCHEMA_SQL + + +def _declared_now(table: str) -> tuple[str, ...]: + conn = sqlite3.connect(":memory:") + try: + conn.executescript(SCHEMA_SQL) + return tuple(str(row[1]) for row in conn.execute(f'PRAGMA table_info("{table}")')) + finally: + conn.close() + + +@pytest.mark.parametrize("table", sorted(history.SCHEMA_HISTORY)) +def test_replayed_history_ends_at_current_schema(table: str) -> None: + """Replaying every recorded edit must reproduce today's declared order. + + Failing here means SCHEMA_SQL changed for ``table``: append an event to + ``SCHEMA_HISTORY[table].events`` describing the edit (never rewrite + older events — real stores were shaped by them). + """ + + replayed = history.current_declared_columns(table) + declared = _declared_now(table) + missing = [c for c in declared if c not in replayed] + extra = [c for c in replayed if c not in declared] + hint = f"SCHEMA_HISTORY[{table!r}].events in hermes_cli/session_schema_history.py" + assert not missing, ( + f"SCHEMA_SQL declares {missing} for {table} but the replayed history does not: " + f"append ('+', , ) events to {hint}" + ) + assert not extra, ( + f"the replayed history declares {extra} for {table} but SCHEMA_SQL no longer does: " + f"append ('-', ) events to {hint}" + ) + assert replayed == declared, ( + f"{table} column order drifted at index " + f"{next(i for i, (a, b) in enumerate(zip(replayed, declared)) if a != b)}: " + f"replayed {replayed} vs SCHEMA_SQL {declared} — record the move as ('-', c) + ('+', c, after) in {hint}" + ) + + +@pytest.mark.parametrize("table", sorted(history.SCHEMA_HISTORY)) +def test_snapshots_are_distinct_and_replay_is_well_formed(table: str) -> None: + snapshots = history.declared_snapshots(table) + assert len(snapshots) == len(history.SCHEMA_HISTORY[table].events) + 1 + for snapshot in snapshots: + assert len(set(snapshot)) == len(snapshot), "duplicate column in a snapshot" + # Snapshots may repeat (a column was declared, reverted, then declared + # again) but consecutive ones must differ or the event was a no-op. + for before, after in zip(snapshots, snapshots[1:]): + assert before != after, "an event changed nothing" + sequence = [int(label.split()[0]) for label, _ in history.SCHEMA_HISTORY[table].events] + assert sequence == list(range(1, len(sequence) + 1)), ( + "event labels must be numbered 01, 02, ... in replay order: append new " + "events at the END with the next number, never insert mid-list" + ) + + +def test_reachable_layouts_include_the_upgraded_store_from_101409() -> None: + """The reporter's physical order (created ~May 2026, upgraded through + v27) is a chain over the recorded snapshots.""" + + reported = ( + "id", "source", "user_id", "model", "model_config", "system_prompt", + "parent_session_id", "started_at", "ended_at", "end_reason", + "message_count", "tool_call_count", "input_tokens", "output_tokens", + "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", + "billing_provider", "billing_base_url", "billing_mode", + "estimated_cost_usd", "actual_cost_usd", "cost_status", "cost_source", + "pricing_version", "title", "api_call_count", "handoff_state", + "handoff_platform", "handoff_error", "cwd", "rewind_count", "archived", + "session_key", "chat_id", "chat_type", "thread_id", "git_branch", + "git_repo_root", "compression_failure_cooldown_until", + "compression_failure_error", "display_name", "origin_json", + "expiry_finalized", "compression_fallback_streak", "profile_name", + "compression_ineffective_count", "pinned", "system_prompt_hash", + "last_activity_at", "last_activity_description", + "last_activity_provenance", "git_metadata_generation", "title_source", + "hidden", "last_read_at", + ) + + def accept(layout: tuple[str, ...], first_new: int) -> bool: + return layout[first_new:len(reported)] == reported[first_new:len(layout)] + + assert any( + layout[: len(reported)] == reported + for layout in history.reachable_physical_layouts("sessions", accept) + ) + + +def test_pruning_callback_stops_branches() -> None: + """``accept`` returning False must prune, not just filter the output.""" + + offered: list[tuple[tuple[str, ...], int]] = [] + + def accept(layout: tuple[str, ...], first_new: int) -> bool: + offered.append((layout, first_new)) + return len(layout) <= 10 + + layouts = list(history.reachable_physical_layouts("messages", accept)) + assert layouts and all(len(layout) <= 10 for layout in layouts) + # Every extension offered must grow from an ACCEPTED parent: its prefix + # up to first_new is a layout that passed. Seeds (first_new == 0) are + # always offered. + accepted = set(layouts) + for layout, first_new in offered: + if first_new: + assert layout[:first_new] in accepted, "a rejected layout was extended"