Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions agent/turn_explainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,19 +120,23 @@
"pending_messages/pending-*.json."
),
"deleted_wal": (
"the turn was stopped because a live Hermes process held a retired "
"state.db-wal generation after its pathname was deleted or "
"Hermes paused saving this chat because another Hermes process replaced "
"its session database. Nothing is lost. Click Recover / run "
"`hermes {profile_arg}doctor --fix`.\n\n"
"Operator runbook: the turn was stopped because a live Hermes process held a "
"retired state.db-wal generation after its pathname was deleted or "
"replaced. Stop the gateway, dashboard, and cron writers; "
"do not overwrite the current state.db or delete its sidecars. "
"Check the logs for whether Hermes captured the retired generation, "
"then read the adjacent state.db.retired-wal-*/manifest.json. If "
"manifest.main.mode is `copied`, inspect that artifact with `hermes "
"sessions recover --source <state.db.retired-wal-*/state.db> "
"{profile_arg}sessions recover --source <state.db.retired-wal-*/state.db> "
"--inspect-only` before deciding whether its committed frames belong "
"on the current database. A `header_only` artifact is forensic and "
"does not contain a copied state.db to inspect. Unwritten messages "
"were diverted to sessions/<session_id>.jsonl and, on the gateway, "
"pending_messages/pending-*.json."
"pending_messages/pending-*.json.\n"
"Recovery guide: https://hermes.nousresearch.com/docs/user-guide/session-storage-recovery"
),
"corrupt": (
"the turn was stopped because the state database "
Expand Down Expand Up @@ -328,7 +332,7 @@ def _format_turn_completion_explanation(
body = _PERSISTENCE_CAUSE_EXPLANATIONS.get(
persistence_cause or "unknown", _PERSISTENCE_DEFAULT_EXPLANATION
)
if persistence_cause in ("corrupt", "fts_index"):
if persistence_cause in ("corrupt", "fts_index", "deleted_wal"):
# Copy-pasteable, so name the store that actually failed and pin the profile:
# a multi-profile backend (Desktop serve) hosts sessions whose state.db is NOT
# the process default, and a bare `hermes` follows active_profile (#105887).
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/api/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ export function getGhAuthStatus(refresh = false): Promise<{ available: boolean;
// getActionStatus().
// ---------------------------------------------------------------------------

export function runDoctor(): Promise<ActionResponse> {
return hermesApi<ActionResponse>({ path: '/api/ops/doctor', method: 'POST', body: {} })
export function runDoctor(fix = false): Promise<ActionResponse> {
return hermesApi<ActionResponse>({ path: '/api/ops/doctor', method: 'POST', body: { fix } })
}

export function runSecurityAudit(): Promise<ActionResponse> {
Expand Down
6 changes: 6 additions & 0 deletions apps/desktop/src/app/command-center/maintenance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@ export function MaintenancePanel() {
label={mm.doctor}
onRun={() => void launch(mm.doctor, runDoctor)}
/>
<OpRow
description="Health-check and auto-fix session storage conflicts, retired WAL holders, and repairable issues"
disabled={actionStatus?.running === true}
label="Run doctor --fix"
onRun={() => void launch('Doctor (--fix)', () => runDoctor(true))}
/>
<OpRow
description={mm.securityAuditDesc}
disabled={actionStatus?.running === true}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { BillingBlock } from '@hermes/shared'

import { runDoctor } from '@/api/system'
import { burstVibeHearts } from '@/components/chat/vibe-hearts'
import { reportFirstBuildTurnComplete } from '@/components/onboarding-chat/first-build'
import { translateNow } from '@/i18n'
Expand Down Expand Up @@ -367,6 +368,21 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
notify({ kind: 'warning', message: payload.warning })
}

// In-product recovery action for deleted-WAL persistence failure (#110054)
if (typeof payload?.failure_reason === 'string' && payload.failure_reason.includes('deleted_wal')) {
notify({
kind: 'error',
title: translateNow('common.error'),
message: 'Hermes paused saving this chat because another process replaced its session database.',
action: {
label: 'Recover',
onClick: () => {
void runDoctor(true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — pin recovery to the failed chat's owner, not the selection at click time. This closure retains neither connection nor profile. runDoctor omits profile scope, and hermesApi adds the ambient connection when invoked. A notification created for gateway-A/research, then clicked after switching to gateway-B, sends {connectionId: 'gateway-B', body: {fix: true}} with no profile. Carry the failure's explicit (connectionId, profile) through the helper/router/spawn boundary and refuse unresolved ownership. Cover background failures and switching before clicking the existing notification.

}
}
})
}

if (isActiveEvent) {
setTurnStartedAt(null)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,20 @@ describe('terminal error message.complete frames', () => {
expect(bubble?.error).toBe('kaput')
expect(bubble?.errorSurface).toBeUndefined()
})

it('handles terminal error with deleted_wal failure_reason and preserves failure state', async () => {
mountStream()
await start()
await delta('…')

await completeWithError({
text: 'Hermes paused saving this chat',
error: 'session storage could not be written',
failure_reason: 'session_persistence_failed:deleted_wal'
})

const bubble = lastAssistant()
expect(bubble?.error).toBe('session storage could not be written')
expect(getState().busy).toBe(false)
})
})
160 changes: 152 additions & 8 deletions hermes_cli/doctor_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

from __future__ import annotations

import os
import subprocess
import time
from pathlib import Path
from hermes_cli.doctor_report import (
Finding, _fail_and_issue, _section, check_bool, check_info, check_ok, check_warn, doctor_check, ensure_dir,
Expand Down Expand Up @@ -203,8 +205,131 @@ def _repair_state_db(f: Finding, should_fix: bool, state_db_path: Path, kind: st
f.fixed += 1


def _recover_retired_wal(f: Finding, should_fix: bool, state_db_path: Path, _DHH: str) -> bool:
"""Detect and remediate processes holding unlinked or retired WAL generations."""
from hermes_state_dbfile import iter_deleted_sqlite_sidecar_holders
from hermes_constants import profile_cli_selector

holders = iter_deleted_sqlite_sidecar_holders(state_db_path)
retired_dirs = sorted(state_db_path.parent.glob(f"{state_db_path.name}.retired-wal-*"))
profile_arg = profile_cli_selector()

if not holders:
if retired_dirs:
latest = retired_dirs[-1]
manifest_file = latest / "manifest.json"
mode = "unknown"
if manifest_file.exists():
import json
try:
m = json.loads(manifest_file.read_text(encoding="utf-8"))
mode = m.get("main", {}).get("mode", "unknown")
except Exception:
pass
check_info(
f"Retired WAL capture preserved at {latest.name} (mode: {mode}; "
f"inspect with 'hermes {profile_arg}sessions recover --source {latest / 'state.db'} --inspect-only')"
)
return False

pids = sorted({pid for pid, _ in holders if pid > 0})
pids_desc = ", ".join(f"PID {p}" for p in pids)
check_warn(
f"{_DHH}/state.db has {len(pids)} process(es) holding an unlinked or retired WAL generation",
f"({pids_desc})",
)

if not should_fix:
f.issues.append(
f"state.db has {len(pids)} process(es) holding a retired WAL generation ({pids_desc}) — "
f"run 'hermes {profile_arg}doctor --fix' to stop conflicting processes and reopen cleanly"
)
return True

from gateway.status import terminate_pid
from hermes_state_holders import _read_proc_argv

stopped_pids = []
failed_pids = []
for pid in pids:
argv = _read_proc_argv(pid)
cmd_desc = " ".join(argv)[:60] if argv else f"PID {pid}"
try:
terminate_pid(pid, force=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking — preserve the exact WAL generation before terminating its owner. iter_deleted_sqlite_sidecar_holders() proves that this PID has an orphaned sidecar, but it does not prove those committed frames were durably captured. The state layer intentionally keeps the descriptor open when capture_retired_wal_generation() fails because process exit is what destroys the last copy. Before this signal, require a manifest/digest/identity receipt for this holder's exact generation; otherwise fail closed and leave it alive. A pre-existing retired-wal-* directory from another incident is not that proof.

exited = False
for _ in range(20):
time.sleep(0.1)
try:
os.kill(pid, 0)
except OSError:
exited = True
break
if not exited:
terminate_pid(pid, force=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking — the escalation is not process-identity qualified. Between the initial /proc holder scan and this KILL, the original holder can exit and its PID can be reused. terminate_pid already accepts expected_start_time specifically to prevent recycled-PID kills (#89614), but this caller supplies none; on POSIX the forced kill is therefore still permitted against only the integer PID. Carry an immutable process fingerprint from observation through TERM and KILL and revalidate before each signal; identity unavailable/mismatched should become a manual-recovery refusal.

for _ in range(10):
time.sleep(0.1)
try:
os.kill(pid, 0)
except OSError:
exited = True
break
if exited:
stopped_pids.append((pid, cmd_desc))
else:
failed_pids.append((pid, cmd_desc))
except Exception as exc:
failed_pids.append((pid, f"{cmd_desc} ({exc})"))

if stopped_pids:
check_ok(
f"Stopped {len(stopped_pids)} process(es) holding retired WAL",
f"({', '.join(str(p) for p, _ in stopped_pids)})",
)
f.fixed += 1

if failed_pids:
check_warn(
f"Could not stop {len(failed_pids)} process(es) holding retired WAL",
f"({', '.join(f'{p}: {c}' for p, c in failed_pids)})",
)
f.manual_issues.append(
f"Could not automatically stop {len(failed_pids)} process(es) holding retired WAL: "
f"{', '.join(f'PID {p} ({c})' for p, c in failed_pids)} — stop them manually and reopen"
)

remaining = iter_deleted_sqlite_sidecar_holders(state_db_path)
if not remaining:
try:
check_ok(f"{_DHH}/state.db reopened successfully ({_session_count(state_db_path)} sessions)")
except Exception as e:
check_warn(f"{_DHH}/state.db reopened but health check reported: {e}")

if retired_dirs:
latest = retired_dirs[-1]
manifest_file = latest / "manifest.json"
mode = "unknown"
if manifest_file.exists():
import json
try:
m = json.loads(manifest_file.read_text(encoding="utf-8"))
mode = m.get("main", {}).get("mode", "unknown")
except Exception:
pass
check_info(
f"Retired WAL capture preserved at {latest.name} (mode: {mode}; "
f"inspect with 'hermes {profile_arg}sessions recover --source {latest / 'state.db'} --inspect-only')"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mode == "header_only" intentionally means there is no copied state.db in this artifact, but this always prints a sessions recover --source …/state.db command. The new chat explainer gets this distinction right. Mirror it here: only emit the inspect command for a verified copied main image; for header_only, report the manifest/header as forensic-only instead of pointing users at a nonexistent file.

)

return True


def _state_db_health(f: Finding, should_fix: bool, state_db_path: Path, _DHH: str) -> None:
"""Session count + FTS write-health probe; malformed-schema path when even COUNT(*) fails."""
from hermes_state_dbfile import iter_deleted_sqlite_sidecar_holders
if iter_deleted_sqlite_sidecar_holders(state_db_path):
_recover_retired_wal(f, should_fix, state_db_path, _DHH)
return

try:
check_ok(f"{_DHH}/state.db exists ({_session_count(state_db_path)} sessions)")
# COUNT(*) succeeds even when the FTS index is corrupt and every write fails through the triggers;
Expand All @@ -222,6 +347,10 @@ def _state_db_health(f: Finding, should_fix: bool, state_db_path: Path, _DHH: st
_repair_state_db(f, should_fix, state_db_path, "fts")
except Exception as e:
from hermes_state import is_malformed_db_error
from hermes_state_errors import DeletedWalGenerationError
if isinstance(e, DeletedWalGenerationError) or "deleted state.db-wal" in str(e):
_recover_retired_wal(f, should_fix, state_db_path, _DHH)
return
if not is_malformed_db_error(e):
return check_warn(f"{_DHH}/state.db exists but has issues: {e}")
# sqlite_master itself is malformed (e.g. duplicate messages_fts): every statement fails before it runs,
Expand Down Expand Up @@ -253,22 +382,37 @@ def _state_db_wal(f: Finding, should_fix: bool, state_db_path: Path) -> None:
with warn_on_error(""):
size = wal_size()
if size > 50 * 1024 * 1024: # 50 MB
check_warn(f"WAL file is large ({size // (1024*1024)} MB)", "(may indicate missed checkpoints)")
from hermes_state_holders import live_writer_holds_db
from hermes_state_repair import _connect_repair_durable
is_held = live_writer_holds_db(state_db_path, connect_repair_durable=_connect_repair_durable)
if not should_fix:
return f.issues.append("Large WAL file — run 'hermes doctor --fix' to checkpoint")
if is_held:
check_warn(
f"WAL file is large ({size // (1024*1024)} MB)",
"(normal while Desktop/gateway are running; only checkpoint with them stopped)",
)
return f.issues.append(
f"Large WAL file ({size // (1024*1024)} MB) — normal while Desktop/gateway are "
"running; stop them first before checkpointing with 'hermes doctor --fix'"
)
check_warn(
f"WAL file is large ({size // (1024*1024)} MB)",
"(may indicate missed checkpoints; only checkpoint with Desktop/gateway stopped)",
)
return f.issues.append(
"Large WAL file — run 'hermes doctor --fix' to checkpoint (ensure Desktop/gateway are stopped)"
)
# Checkpoint-lock premise (#40177): a bare connect runs WAL recovery and the checkpoint joins the
# live WAL — under a running gateway that second-writer handling corrupts state.db. Skip instead.
from hermes_state_holders import live_writer_holds_db
from hermes_state_repair import _connect_repair_durable
if live_writer_holds_db(state_db_path, connect_repair_durable=_connect_repair_durable):
if is_held:
# Honest disjunction (gate C1): a True here means "held OR
# unprovable" — the DatabaseError lane fires when SQLite
# cannot open the file at all, with nobody holding it. Never
# assert a live writer as fact.
check_warn("WAL checkpoint skipped: cannot prove state.db is quiet",
"(a live writer holds it, or it is unreadable — stop the profile's gateway "
"and re-run 'hermes doctor --fix')")
return f.issues.append("Large WAL file — cannot prove state.db is quiet (stop the profile's "
"(a live writer holds it, or it is unreadable — stop Desktop and the profile's gateway "
"first, then re-run 'hermes doctor --fix')")
return f.issues.append("Large WAL file — cannot prove state.db is quiet (stop Desktop and the profile's "
"gateway first, then re-run 'hermes doctor --fix' to checkpoint)")
import contextlib
import sqlite3
Expand Down
4 changes: 4 additions & 0 deletions hermes_cli/web_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
from pydantic import BaseModel, SecretStr, StrictBool, field_validator


class DoctorRequest(BaseModel):
fix: bool = False


class ConfigUpdate(BaseModel):
config: dict
profile: Optional[str] = None
Expand Down
9 changes: 6 additions & 3 deletions hermes_cli/web_routers/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from hermes_cli.web_server_gateway import _restart_gateway_after
from hermes_cli.web_server_memory import _normalize_memory_provider_name, _require_memory_provider_ready
from hermes_cli.web_models import (
BackupRequest, CredentialPoolAdd, HookCreate, HookDelete, ImportRequest, MemoryProviderSelect,
BackupRequest, CredentialPoolAdd, DoctorRequest, HookCreate, HookDelete, ImportRequest, MemoryProviderSelect,
MemoryReset, PairingApprove, PairingRevoke, WebhookCreate, WebhookEnabledToggle,
)
from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK, http_failure, spawn_profile_action
Expand Down Expand Up @@ -501,8 +501,11 @@ async def reset_memory(body: MemoryReset):


@router.post("/api/ops/doctor")
async def run_doctor():
return _spawn_action(["doctor"], "doctor", log_msg="Failed to spawn doctor", prefix="Failed to run doctor")
async def run_doctor(body: Optional[DoctorRequest] = None):
args = ["doctor"]
if body and body.fix:
args.append("--fix")
return _spawn_action(args, "doctor", log_msg="Failed to spawn doctor", prefix="Failed to run doctor")


@router.post("/api/ops/security-audit")
Expand Down
6 changes: 6 additions & 0 deletions tests/agent/test_turn_completion_explainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,18 @@ def test_deleted_wal_cause_is_enumerated_and_points_to_retired_capture():
"session_persistence_failed", "deleted_wal"
).lower()
assert "deleted_wal" in PERSISTENCE_ERROR_CAUSES
# First line (human-facing)
assert "hermes paused saving this chat because another hermes process replaced its session database" in out
assert "click recover / run" in out
assert "doctor --fix" in out
# Operator runbook and artifacts
assert "retired-wal-*/manifest.json" in out
assert "manifest.main.mode" in out
assert "sessions recover" in out and "--inspect-only" in out
assert "header_only" in out and "does not contain a copied state.db" in out
assert "check the logs for whether" in out
assert "restore the intended state.db" not in out
assert "session-storage-recovery" in out


def test_explanation_persistence_unknown_cause_is_neutral():
Expand Down
Loading