Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(transaction): add redo recovery toggle for session commits (#1934)

Jiahui Zhoub84f79820793
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 23996dbcb..89c2634cb 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -147,6 +147,7 @@ class OpenVikingService:
agfs=self._agfs_client,
lock_timeout=tx_cfg.lock_timeout,
lock_expire=tx_cfg.lock_expire,
+ redo_recovery_enabled=tx_cfg.redo_recovery_enabled,
)
@property
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 6b70cb5fc..e5bacb702 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -122,9 +122,7 @@ WM_UPDATE_TOOL: Dict[str, Any] = {
"type": "object",
"required": list(WM_SEVEN_SECTIONS),
"additionalProperties": False,
- "properties": {
- name: _WM_SECTION_OP_SCHEMA for name in WM_SEVEN_SECTIONS
- },
+ "properties": dict.fromkeys(WM_SEVEN_SECTIONS, _WM_SECTION_OP_SCHEMA),
}
},
},
@@ -384,9 +382,7 @@ class Session:
keep = max(0, int(self._meta.keep_recent_count or 0))
total = len(self._messages)
if keep <= 0:
- self._meta.pending_tokens = sum(
- int(m.estimated_tokens or 0) for m in self._messages
- )
+ self._meta.pending_tokens = sum(int(m.estimated_tokens or 0) for m in self._messages)
elif total > keep:
self._meta.pending_tokens = sum(
int(m.estimated_tokens or 0) for m in self._messages[: total - keep]
@@ -758,6 +754,9 @@ class Session:
telemetry = OperationTelemetry(operation="session_commit_phase2", enabled=True)
archive_index = self._archive_index_from_uri(archive_uri)
redo_task_id: Optional[str] = None
+ lock_manager = get_lock_manager()
+ redo_enabled = lock_manager.redo_recovery_enabled
+ redo_log = lock_manager.redo_log
try:
if not await self._wait_for_previous_archive_done(archive_index):
@@ -783,19 +782,19 @@ class Session:
try:
with bind_telemetry(telemetry):
# redo-log protection
- redo_task_id = str(uuid.uuid4())
- redo_log = get_lock_manager().redo_log
- redo_log.write_pending(
- redo_task_id,
- {
- "archive_uri": archive_uri,
- "session_uri": self._session_uri,
- "account_id": self.ctx.account_id,
- "user_id": self.ctx.user.user_id,
- "agent_id": self.ctx.user.agent_id,
- "role": self.ctx.role.value,
- },
- )
+ if redo_enabled:
+ redo_task_id = str(uuid.uuid4())
+ redo_log.write_pending(
+ redo_task_id,
+ {
+ "archive_uri": archive_uri,
+ "session_uri": self._session_uri,
+ "account_id": self.ctx.account_id,
+ "user_id": self.ctx.user.user_id,
+ "agent_id": self.ctx.user.agent_id,
+ "role": self.ctx.role.value,
+ },
+ )
latest_archive_overview = await self._get_latest_completed_archive_overview(
exclude_archive_uri=archive_uri
@@ -909,18 +908,21 @@ class Session:
if self._viking_fs:
for usage in usage_records:
try:
- await self._viking_fs.link(self._session_uri, usage.uri, ctx=self.ctx)
+ await self._viking_fs.link(
+ self._session_uri, usage.uri, ctx=self.ctx
+ )
except Exception as e:
logger.warning(f"Failed to create relation to {usage.uri}: {e}")
- redo_log.mark_done(redo_task_id)
+ if redo_enabled and redo_task_id:
+ redo_log.mark_done(redo_task_id)
# Update active_count (using snapshot, not self._usage_records)
if self._vikingdb_manager:
uris = [u.uri for u in usage_records if u.uri]
try:
- active_count_updated = await self._vikingdb_manager.increment_active_count(
- self.ctx, uris
+ active_count_updated = (
+ await self._vikingdb_manager.increment_active_count(self.ctx, uris)
)
except Exception as e:
logger.debug(f"Could not update active_count for usage URIs: {e}")
@@ -980,8 +982,8 @@ class Session:
)
logger.info(f"Session {self.session_id} memory extraction completed")
except Exception as e:
- if redo_task_id:
- get_lock_manager().redo_log.mark_done(redo_task_id)
+ if redo_enabled and redo_task_id:
+ redo_log.mark_done(redo_task_id)
await self._write_failed_marker(
archive_uri,
stage="memory_extraction",
@@ -1538,8 +1540,10 @@ class Session:
tool_call / JSON / schema anomaly, fall back to the creation
prompt so we never persist malformed output as WM.
"""
- _wm_debug(f"_generate_archive_summary_async called "
- f"messages={len(messages)} prior_wm={len(latest_archive_overview)}B")
+ _wm_debug(
+ f"_generate_archive_summary_async called "
+ f"messages={len(messages)} prior_wm={len(latest_archive_overview)}B"
+ )
if not messages:
return ""
@@ -1549,8 +1553,7 @@ class Session:
if not (vlm and vlm.is_available()):
turn_count = len([m for m in messages if m.role == "user"])
return (
- f"# Session Summary\n\n"
- f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
try:
@@ -1559,8 +1562,7 @@ class Session:
logger.warning(f"Prompt module unavailable: {e}")
turn_count = len([m for m in messages if m.role == "user"])
return (
- f"# Session Summary\n\n"
- f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
# -------- Detect WM v2 format --------
@@ -1577,7 +1579,10 @@ class Session:
try:
prompt = render_prompt(
"compression.ov_wm_v2",
- {"messages": formatted, "latest_archive_overview": latest_archive_overview or ""},
+ {
+ "messages": formatted,
+ "latest_archive_overview": latest_archive_overview or "",
+ },
)
return await vlm.get_completion_async(prompt)
except Exception as e:
@@ -1613,14 +1618,12 @@ class Session:
)
except Exception as e:
import traceback as _tb
- _wm_debug(
- f"tool_call raised: {type(e).__name__}: {e} "
- f"tb={_tb.format_exc()[-400:]}"
- )
- logger.warning(
- "WM update tool_call failed (%s); falling back to creation prompt", e
+
+ _wm_debug(f"tool_call raised: {type(e).__name__}: {e} tb={_tb.format_exc()[-400:]}")
+ logger.warning("WM update tool_call failed (%s); falling back to creation prompt", e)
+ return await self._fallback_generate_wm_creation(
+ formatted, messages, latest_archive_overview
)
- return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
has_tc = bool(getattr(resp, "has_tool_calls", False) and getattr(resp, "tool_calls", None))
_preview = (str(resp)[:200]).replace(chr(10), " ")
@@ -1632,17 +1635,14 @@ class Session:
)
if not has_tc:
- logger.warning(
- "WM update: LLM returned no tool_call; falling back to creation prompt"
+ logger.warning("WM update: LLM returned no tool_call; falling back to creation prompt")
+ return await self._fallback_generate_wm_creation(
+ formatted, messages, latest_archive_overview
)
- return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
try:
raw_args = resp.tool_calls[0].arguments
- _wm_debug(
- f"raw_args type={type(raw_args).__name__} "
- f"preview={str(raw_args)[:400]!r}"
- )
+ _wm_debug(f"raw_args type={type(raw_args).__name__} preview={str(raw_args)[:400]!r}")
args = raw_args
if isinstance(args, str):
args = json.loads(args)
@@ -1668,8 +1668,7 @@ class Session:
patched = raw_str.rstrip().rstrip(",") + ("}" * opens)
recovered = json.loads(patched)
_wm_debug(
- f"recovered by closing {opens} brace(s); "
- f"patched_len={len(patched)}"
+ f"recovered by closing {opens} brace(s); patched_len={len(patched)}"
)
except Exception as e2:
_wm_debug(f"brace-close recovery failed: {e2}")
@@ -1686,15 +1685,12 @@ class Session:
_wm_debug("args has section keys directly; accepting as ops")
ops = args
else:
- raise ValueError(
- f"tool_call arguments.sections missing; keys={list(args.keys())}"
- )
+ raise ValueError(f"tool_call arguments.sections missing; keys={list(args.keys())}")
if not isinstance(ops, dict):
raise ValueError("ops is not a dict")
except Exception as e:
_wm_debug(
- f"args parse failed: {type(e).__name__}: {e}; "
- f"attempting regex recovery from raw"
+ f"args parse failed: {type(e).__name__}: {e}; attempting regex recovery from raw"
)
# Regex salvage: when the LLM emits slightly-broken JSON (curly
# quote, unescaped newline, truncated string), OV's VLM backend
@@ -1727,15 +1723,15 @@ class Session:
len(WM_SEVEN_SECTIONS),
)
return self._merge_wm_sections(latest_archive_overview, salvaged)
- _wm_debug(
- "regex recovery salvaged 0 sections; falling back to creation prompt"
- )
+ _wm_debug("regex recovery salvaged 0 sections; falling back to creation prompt")
logger.warning(
"WM update: tool_call arguments parse failed (%s); "
"regex recovery found nothing; falling back to creation prompt",
e,
)
- return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
+ return await self._fallback_generate_wm_creation(
+ formatted, messages, latest_archive_overview
+ )
_wm_debug(
f"ops keys={list(ops.keys())[:7]} "
@@ -1770,8 +1766,7 @@ class Session:
logger.warning(f"WM creation fallback failed: {e}")
turn_count = len([m for m in messages if m.role == "user"])
return (
- f"# Session Summary\n\n"
- f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
@staticmethod
@@ -1843,9 +1838,11 @@ class Session:
return "<section_size_warnings>\n" + "\n\n".join(warnings) + "\n</section_size_warnings>"
# Sections where server enforces APPEND-only regardless of what the LLM emits.
- _WM_APPEND_ONLY_SECTIONS = frozenset({
- "Errors & Corrections",
- })
+ _WM_APPEND_ONLY_SECTIONS = frozenset(
+ {
+ "Errors & Corrections",
+ }
+ )
# Very loose path-like token regex used to detect file paths that existed
# in prior Files & Context and MUST NOT silently disappear after UPDATE.
@@ -1855,11 +1852,32 @@ class Session:
re.IGNORECASE,
)
- _WM_TITLE_STOPWORDS = frozenset({
- "the", "a", "an", "and", "or", "of", "to", "in", "on", "for",
- "with", "by", "at", "from", "session", "title", "working", "memory",
- "plan", "plans", "notes", "note",
- })
+ _WM_TITLE_STOPWORDS = frozenset(
+ {
+ "the",
+ "a",
+ "an",
+ "and",
+ "or",
+ "of",
+ "to",
+ "in",
+ "on",
+ "for",
+ "with",
+ "by",
+ "at",
+ "from",
+ "session",
+ "title",
+ "working",
+ "memory",
+ "plan",
+ "plans",
+ "notes",
+ "note",
+ }
+ )
@staticmethod
def _wm_recover_ops_from_raw(raw_str: str) -> Dict[str, Any]:
@@ -1884,9 +1902,7 @@ class Session:
names_alt = "|".join(re.escape(n) for n in WM_SEVEN_SECTIONS)
# --- KEEP: "Name": {"op": "KEEP"} ---
- keep_re = re.compile(
- rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"KEEP"\s*\}}'
- )
+ keep_re = re.compile(rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"KEEP"\s*\}}')
for m in keep_re.finditer(raw_str):
ops.setdefault(m.group(1), {"op": "KEEP"})
@@ -1916,7 +1932,7 @@ class Session:
# Tolerate truncated array (no closing ']').
append_re = re.compile(
rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"APPEND"\s*,\s*"items"\s*:\s*\['
- rf'([\s\S]*?)(?:\]|$)',
+ rf"([\s\S]*?)(?:\]|$)",
)
item_re = re.compile(r'"((?:[^"\\]|\\.)*)"', re.DOTALL)
for m in append_re.finditer(raw_str):
@@ -1957,9 +1973,7 @@ class Session:
return items
@staticmethod
- def _wm_enforce_append_only(
- header: str, op: Any, old_content: str
- ) -> Dict[str, Any]:
+ def _wm_enforce_append_only(header: str, op: Any, old_content: str) -> Dict[str, Any]:
"""Guard: force KEEP/APPEND semantics on APPEND-only sections.
- KEEP and APPEND pass through.
@@ -2015,22 +2029,117 @@ class Session:
r"\b(?:because|decided|chose|committed|agreed|resolved)\b",
re.IGNORECASE,
)
- _WM_ANCHOR_STOPWORDS = frozenset({
- "the", "a", "an", "and", "or", "of", "to", "in", "on", "for",
- "with", "by", "at", "from", "is", "are", "was", "were", "has",
- "have", "had", "been", "be", "will", "would", "could", "should",
- "may", "might", "shall", "this", "that", "these", "those",
- "not", "no", "but", "if", "then", "so", "as", "it", "its",
- "they", "their", "them", "she", "her", "he", "him", "his",
- "we", "our", "us", "you", "your", "who", "which", "what",
- "when", "where", "how", "why", "all", "each", "every",
- "both", "few", "more", "most", "other", "some", "such",
- "than", "too", "very", "also", "just", "about", "after",
- "before", "between", "into", "through", "during", "again",
- "further", "once", "here", "there", "over", "under", "out",
- "up", "down", "off", "own", "same", "only", "new", "old",
- "key", "facts", "decisions", "session", "working", "memory",
- })
+ _WM_ANCHOR_STOPWORDS = frozenset(
+ {
+ "the",
+ "a",
+ "an",
+ "and",
+ "or",
+ "of",
+ "to",
+ "in",
+ "on",
+ "for",
+ "with",
+ "by",
+ "at",
+ "from",
+ "is",
+ "are",
+ "was",
+ "were",
+ "has",
+ "have",
+ "had",
+ "been",
+ "be",
+ "will",
+ "would",
+ "could",
+ "should",
+ "may",
+ "might",
+ "shall",
+ "this",
+ "that",
+ "these",
+ "those",
+ "not",
+ "no",
+ "but",
+ "if",
+ "then",
+ "so",
+ "as",
+ "it",
+ "its",
+ "they",
+ "their",
+ "them",
+ "she",
+ "her",
+ "he",
+ "him",
+ "his",
+ "we",
+ "our",
+ "us",
+ "you",
+ "your",
+ "who",
+ "which",
+ "what",
+ "when",
+ "where",
+ "how",
+ "why",
+ "all",
+ "each",
+ "every",
+ "both",
+ "few",
+ "more",
+ "most",
+ "other",
+ "some",
+ "such",
+ "than",
+ "too",
+ "very",
+ "also",
+ "just",
+ "about",
+ "after",
+ "before",
+ "between",
+ "into",
+ "through",
+ "during",
+ "again",
+ "further",
+ "once",
+ "here",
+ "there",
+ "over",
+ "under",
+ "out",
+ "up",
+ "down",
+ "off",
+ "own",
+ "same",
+ "only",
+ "new",
+ "old",
+ "key",
+ "facts",
+ "decisions",
+ "session",
+ "working",
+ "memory",
+ }
+ )
@staticmethod
def _extract_lexical_anchors(text: str) -> set:
@@ -2063,16 +2172,12 @@ class Session:
if key and key not in old_lower:
fresh_items.append(it)
if fresh_items:
- _wm_debug(
- f"guard: salvaged {len(fresh_items)} new items from rejected UPDATE"
- )
+ _wm_debug(f"guard: salvaged {len(fresh_items)} new items from rejected UPDATE")
return {"op": "APPEND", "items": fresh_items}
return {"op": "KEEP"}
@staticmethod
- def _wm_enforce_key_facts_consolidation(
- op: Any, old_content: str
- ) -> Dict[str, Any]:
+ def _wm_enforce_key_facts_consolidation(op: Any, old_content: str) -> Dict[str, Any]:
"""Guard: allow controlled consolidation for Key Facts & Decisions.
Layer 1 — reject trivially small UPDATEs (< 15% bullet count).
@@ -2106,10 +2211,7 @@ class Session:
append_items = Session._wm_extract_bullet_items(raw)
append_items = [str(it) for it in append_items if it]
old_lower = (old_content or "").lower()
- fresh = [
- it for it in append_items
- if it.strip("_* `").lower() not in old_lower
- ]
+ fresh = [it for it in append_items if it.strip("_* `").lower() not in old_lower]
emergency = (
len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD * 2
or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD * 2
@@ -2166,13 +2268,9 @@ class Session:
f"new={len(new_items)} / old={len(old_items)} = "
f"{ratio:.2%} < {Session._WM_KEY_FACTS_MIN_BULLET_RATIO:.0%}"
)
- salvaged = Session._salvage_new_items_from_rejected_update(
- new_content, old_content
- )
+ salvaged = Session._salvage_new_items_from_rejected_update(new_content, old_content)
if is_emergency and salvaged.get("op") == "APPEND":
- _wm_debug(
- "guard: suppressing salvage APPEND (emergency level)"
- )
+ _wm_debug("guard: suppressing salvage APPEND (emergency level)")
return {"op": "KEEP"}
return salvaged
@@ -2189,13 +2287,9 @@ class Session:
f"({covered}/{len(old_anchors)}) < "
f"{Session._WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:.0%}"
)
- salvaged = Session._salvage_new_items_from_rejected_update(
- new_content, old_content
- )
+ salvaged = Session._salvage_new_items_from_rejected_update(new_content, old_content)
if is_emergency and salvaged.get("op") == "APPEND":
- _wm_debug(
- "guard: suppressing salvage APPEND (emergency level)"
- )
+ _wm_debug("guard: suppressing salvage APPEND (emergency level)")
return {"op": "KEEP"}
return salvaged
_wm_debug(
@@ -2236,7 +2330,7 @@ class Session:
added_paths = new_paths - old_paths
_wm_debug(
f"guard: 'Files & Context' UPDATE drops {len(missing)} paths "
- f"{sorted(list(missing))[:5]}; forcing KEEP (+ APPEND new paths="
+ f"{sorted(missing)[:5]}; forcing KEEP (+ APPEND new paths="
f"{len(added_paths)})"
)
if added_paths:
@@ -2273,10 +2367,7 @@ class Session:
def meaningful_words(text: str) -> set:
tokens = re.findall(r"[A-Za-z][A-Za-z0-9\.]{2,}|[\d\.]+", text or "")
- return {
- t.lower() for t in tokens
- if t.lower() not in Session._WM_TITLE_STOPWORDS
- }
+ return {t.lower() for t in tokens if t.lower() not in Session._WM_TITLE_STOPWORDS}
old_w = meaningful_words(old_content)
new_w = meaningful_words(new_content)
@@ -2326,9 +2417,7 @@ class Session:
f"guard: Open Issues UPDATE silently dropped {len(dropped)} "
f"items; restoring once (will not restore again if re-dropped)"
)
- restored = "\n".join(
- f"- [silently dropped, restored] {it}" for it in dropped
- )
+ restored = "\n".join(f"- [silently dropped, restored] {it}" for it in dropped)
merged = (new_content + ("\n" if new_content else "") + restored).strip()
return {"op": "UPDATE", "content": merged}
@@ -2402,7 +2491,9 @@ class Session:
if bad_items:
logger.warning(
"wm_v2: dropped %d non-string APPEND item(s) in section %r: %s",
- len(bad_items), header, [type(s).__name__ for s in bad_items],
+ len(bad_items),
+ header,
+ [type(s).__name__ for s in bad_items],
)
appended = "\n".join(
f"- {s.strip()}" for s in items if isinstance(s, str) and s.strip()
diff --git a/openviking/storage/transaction/lock_manager.py b/openviking/storage/transaction/lock_manager.py
index f6e9a15e1..282ad781c 100644
--- a/openviking/storage/transaction/lock_manager.py
+++ b/openviking/storage/transaction/lock_manager.py
@@ -26,10 +26,12 @@ class LockManager:
agfs: AGFSClient,
lock_timeout: float = 0.0,
lock_expire: float = 300.0,
+ redo_recovery_enabled: bool = True,
):
self._agfs = agfs
self._path_lock = PathLock(agfs, lock_expire=lock_expire)
self._lock_timeout = lock_timeout
+ self._redo_recovery_enabled = redo_recovery_enabled
self._redo_log = RedoLog(agfs)
self._handles: Dict[str, LockHandle] = {}
self._cleanup_task: Optional[asyncio.Task] = None
@@ -40,6 +42,10 @@ class LockManager:
def redo_log(self) -> RedoLog:
return self._redo_log
+ @property
+ def redo_recovery_enabled(self) -> bool:
+ return self._redo_recovery_enabled
+
def _mark_handle_active(self, handle: LockHandle) -> None:
handle.last_active_at = time.time()
@@ -55,7 +61,10 @@ class LockManager:
"""Start background cleanup and redo recovery."""
self._running = True
self._cleanup_task = asyncio.create_task(self._stale_cleanup_loop())
- self._redo_task = asyncio.create_task(self._recover_pending_redo())
+ if self._redo_recovery_enabled:
+ self._redo_task = asyncio.create_task(self._recover_pending_redo())
+ else:
+ logger.info("Redo recovery disabled by config; skipping pending redo recovery")
async def stop(self) -> None:
"""Stop cleanup and release all active locks."""
@@ -367,9 +376,15 @@ def init_lock_manager(
agfs: AGFSClient,
lock_timeout: float = 0.0,
lock_expire: float = 300.0,
+ redo_recovery_enabled: bool = True,
) -> LockManager:
global _lock_manager
- _lock_manager = LockManager(agfs=agfs, lock_timeout=lock_timeout, lock_expire=lock_expire)
+ _lock_manager = LockManager(
+ agfs=agfs,
+ lock_timeout=lock_timeout,
+ lock_expire=lock_expire,
+ redo_recovery_enabled=redo_recovery_enabled,
+ )
return _lock_manager
diff --git a/openviking_cli/utils/config/transaction_config.py b/openviking_cli/utils/config/transaction_config.py
index 3e394f7f9..449842f82 100644
--- a/openviking_cli/utils/config/transaction_config.py
+++ b/openviking_cli/utils/config/transaction_config.py
@@ -29,4 +29,12 @@ class TransactionConfig(BaseModel):
),
)
+ redo_recovery_enabled: bool = Field(
+ default=True,
+ description=(
+ "Enable session commit phase-2 crash-recovery redo. "
+ "When false, pending redo markers are not written and startup redo recovery is skipped."
+ ),
+ )
+
model_config = {"extra": "forbid"}
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 1951242e2..a71ee0a5c 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -5,6 +5,7 @@
import asyncio
import json
+from unittest.mock import MagicMock
import pytest
@@ -12,6 +13,7 @@ from openviking import AsyncOpenViking
from openviking.message import TextPart
from openviking.service.task_tracker import get_task_tracker
from openviking.session import Session
+from openviking.storage.transaction import get_lock_manager
from openviking_cli.exceptions import FailedPreconditionError
@@ -236,3 +238,20 @@ class TestCommit:
session.add_message("user", [TextPart("Second round message")])
with pytest.raises(FailedPreconditionError, match="unresolved failed archive"):
await session.commit_async()
+
+ async def test_commit_skips_redo_when_recovery_disabled(
+ self, session_with_messages: Session, monkeypatch: pytest.MonkeyPatch
+ ):
+ """Phase 2 should not write or clear redo markers when redo recovery is disabled."""
+
+ redo_log = MagicMock()
+ lock_manager = get_lock_manager()
+ monkeypatch.setattr(lock_manager, "_redo_recovery_enabled", False)
+ monkeypatch.setattr(lock_manager, "_redo_log", redo_log)
+
+ result = await session_with_messages.commit_async()
+ task_result = await _wait_for_task(result["task_id"])
+
+ assert task_result["status"] == "completed"
+ redo_log.write_pending.assert_not_called()
+ redo_log.mark_done.assert_not_called()
diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py
index ea0b7df05..bf148c340 100644
--- a/tests/test_config_loader.py
+++ b/tests/test_config_loader.py
@@ -198,6 +198,24 @@ def test_openviking_config_retrieval_hotness_alpha_defaults_to_zero(monkeypatch)
assert config.retrieval.hotness_alpha == 0.0
assert config.retrieval.score_propagation_alpha == 0.5
+ assert config.storage.transaction.redo_recovery_enabled is True
+
+ OpenVikingConfigSingleton.reset_instance()
+
+
+def test_openviking_config_transaction_redo_recovery_enabled_can_be_disabled(monkeypatch):
+ monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")
+
+ from openviking_cli.utils.config.open_viking_config import (
+ OpenVikingConfig,
+ OpenVikingConfigSingleton,
+ )
+
+ config = OpenVikingConfig.from_dict(
+ {"storage": {"transaction": {"redo_recovery_enabled": False}}}
+ )
+
+ assert config.storage.transaction.redo_recovery_enabled is False
OpenVikingConfigSingleton.reset_instance()
diff --git a/tests/transaction/test_lock_manager.py b/tests/transaction/test_lock_manager.py
index 88d14f062..c6147fc89 100644
--- a/tests/transaction/test_lock_manager.py
+++ b/tests/transaction/test_lock_manager.py
@@ -99,3 +99,20 @@ class TestLockManagerBasic:
await lm._recover_pending_redo()
lm._redo_log.mark_done.assert_not_called()
+
+ async def test_start_skips_redo_recovery_when_disabled(self, client):
+ lm_disabled = LockManager(
+ agfs=client._client.service._agfs_client,
+ lock_timeout=1.0,
+ lock_expire=1.0,
+ redo_recovery_enabled=False,
+ )
+ lm_disabled._recover_pending_redo = AsyncMock()
+
+ await lm_disabled.start()
+ await asyncio.sleep(0)
+
+ assert lm_disabled._redo_task is None
+ lm_disabled._recover_pending_redo.assert_not_called()
+
+ await lm_disabled.stop()