Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(wiki): waiting never burns a save, probes stay off the loop, recaps never fall back to keys

rubenluetke10-beep138b7b2a6b7c
diff --git a/jarvis/agentic_ide/recap_engine.py b/jarvis/agentic_ide/recap_engine.py
index 62b179d4f8..a054f49cb7 100644
--- a/jarvis/agentic_ide/recap_engine.py
+++ b/jarvis/agentic_ide/recap_engine.py
@@ -807,9 +807,12 @@ def _resolve_brains() -> list[Any]:
"""The brains that could write the recap, best first. Empty when none can.
Resolution goes through ``jarvis.brain.resolver`` so this module never grows
- its own opinion about providers (AP-21/AP-22): whatever keys the user has
- are what write the recap, and an install with none gets an empty list and
- the deterministic floor. More than one candidate comes back because the
+ its own opinion about providers (AP-21/AP-22): a connected subscription
+ writes the recap; on an install that never connected one, whatever keys the
+ user has write it; an install in subscription mode whose subscription cannot
+ answer right now, or one with nothing at all, gets an empty list and the
+ deterministic floor (``background_policy``). More than one candidate comes
+ back because the
ordinary failure is CALL-time — a depleted key instantiates fine and only
429s when asked to write — and the retry must cross to a different family.
"""
@@ -825,6 +828,15 @@ def _resolve_brains() -> list[Any]:
subscription = _resolve_subscription(config)
if subscription is not None:
return [subscription]
+ if _subscription_install():
+ # A subscription is connected (or was, within the policy's
+ # memory) but cannot write right now: wait for it. The title
+ # floor covers the pane meanwhile; no key is instantiated.
+ logger.info(
+ "Agentic IDE recap: the subscription cannot write right now — "
+ "using the plain title instead of an API key"
+ )
+ return []
candidates: list[Any] = []
for brain in frontier_brain_candidates(config):
candidates.append(brain)
@@ -833,11 +845,34 @@ def _resolve_brains() -> list[Any]:
except Exception as exc: # noqa: BLE001 - no brain is an answer, not an error
logger.info("Agentic IDE recap: no brain reachable ({})", exc)
return []
- # Reached only with no subscription connected: the keyed families are
- # then the whole chain, so a single-key install still gets model recaps.
+ # Reached only on an install that never connected a subscription: the
+ # keyed families are then the whole chain, so a single-key install still
+ # gets model recaps.
return candidates
+def _subscription_install() -> bool:
+ """Whether recaps may only run on subscriptions (``background_policy``).
+
+ True while any subscription is signed in or was seen signed in within the
+ policy's memory window. Probes vendor CLIs, so it runs only from
+ :func:`_resolve_brains`, which is always called off the event loop. A
+ broken probe answers True: the plain title is a safe fallback, a paid key
+ is not.
+ """
+ try:
+ from jarvis.brain.background_policy import background_providers
+ from jarvis.brain.provider_registry import BrainProviderRegistry
+
+ names = sorted(BrainProviderRegistry().available())
+ return background_providers(names).subscription_mode
+ except Exception: # noqa: BLE001 - failing closed is the handling, logged here
+ logger.opt(exception=True).warning(
+ "Agentic IDE recap: background billing check failed — no API key is used"
+ )
+ return True
+
+
def _resolve_subscription(config: Any) -> Any | None:
"""A connected subscription brain as the recap's last resort, or None."""
try:
diff --git a/jarvis/memory/wiki/consolidator.py b/jarvis/memory/wiki/consolidator.py
index 8d4f599e70..e9eb0aa005 100644
--- a/jarvis/memory/wiki/consolidator.py
+++ b/jarvis/memory/wiki/consolidator.py
@@ -545,7 +545,10 @@ class Consolidator:
)
try:
- background = build_background_wiki_chain(
+ # Provider selection may run vendor login probes (seconds of subprocess):
+ # keep it off the event loop (AP-9).
+ background = await asyncio.to_thread(
+ build_background_wiki_chain,
registry=self._registry,
config=self._root_cfg,
primary=(
diff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.py
index 3e931e16a9..9d6d08edb4 100644
--- a/jarvis/memory/wiki/curator_llm.py
+++ b/jarvis/memory/wiki/curator_llm.py
@@ -543,7 +543,10 @@ class WikiCuratorLLM:
# bills only what background work may bill: once a subscription is
# connected, subscriptions and local models — never a key.
try:
- background = build_background_wiki_chain(
+ # Provider selection may run vendor login probes (seconds of subprocess):
+ # keep it off the event loop (AP-9).
+ background = await asyncio.to_thread(
+ build_background_wiki_chain,
registry=self._registry,
config=self._config,
primary=(self._cfg.provider.strip() or self._config.brain.primary),
diff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.py
index 9ee699b8f3..4fae7918a2 100644
--- a/jarvis/memory/wiki/extractor.py
+++ b/jarvis/memory/wiki/extractor.py
@@ -337,14 +337,18 @@ class ConversationFactExtractor:
must never notice the memory pipeline. The one exception is
:class:`BackgroundDeferred`: nothing background work may bill can take
the call right now, so the caller keeps the turn and retries later.
- It is raised BEFORE the review is claimed whenever that is known up
- front, so waiting never uses up a review attempt.
+ Waiting never uses up a review attempt: a wait known up front is
+ raised before the review is claimed, and a wait that starts mid-chain
+ (the subscription stops answering, the daily cap is reached) hands the
+ claimed attempt back (``CandidateJournal.release_capture``). A review
+ that cannot be claimed is logged with the reason — a WARNING when its
+ failure budget is spent — never dropped silently.
"""
text = (user_text or "").strip()
focus_turn_id = (turn_id or turn_hash).strip()
key = review_key or f"turn:v2:{turn_hash}"
background = (
- self._background_chain()
+ await self._background_chain()
if self._cfg.enabled and len(text) >= int(self._cfg.min_user_chars)
else None
)
@@ -356,6 +360,7 @@ class ConversationFactExtractor:
session_id=session_id,
turn_id=focus_turn_id,
):
+ await self._log_unclaimed(key, source_label=source_label)
return 0
if not self._cfg.enabled:
@@ -398,9 +403,9 @@ class ConversationFactExtractor:
raise
except BackgroundDeferred:
# The daily cap was reached or the subscription stopped answering
- # mid-chain: the review stays retryable and the caller keeps the
- # turn for a later attempt.
- await self._finish_review(key, status="failed", error_code="deferred")
+ # mid-chain: nothing was reviewed, so the attempt goes back and
+ # the caller keeps the turn for a later try.
+ await self._release_review(key)
raise
except Exception: # noqa: BLE001 - the conversation must never notice
log.exception("ConversationFactExtractor: unexpected extraction failure")
@@ -461,7 +466,7 @@ class ConversationFactExtractor:
background: WikiBackgroundChain | None = None
if self._cfg.enabled:
try:
- background = self._background_chain()
+ background = await self._background_chain()
except BackgroundDeferred as exc:
log.info(
"ConversationFactExtractor: session %s sweep paused at "
@@ -479,6 +484,7 @@ class ConversationFactExtractor:
session_id=session_id,
turn_id="",
):
+ await self._log_unclaimed(key, source_label=f"{source_label}:chunk:{index}")
continue
if background is None:
await self._finish_review(
@@ -506,7 +512,7 @@ class ConversationFactExtractor:
await self._finish_review(key, status="failed", error_code="cancelled")
raise
except BackgroundDeferred as exc:
- await self._finish_review(key, status="failed", error_code="deferred")
+ await self._release_review(key)
log.info(
"ConversationFactExtractor: session %s sweep paused at chunk %d — %s",
session_id,
@@ -802,6 +808,62 @@ class ConversationFactExtractor:
)
return True
+ async def _release_review(self, review_key: str) -> None:
+ """Hand a claimed review back: it waited, it did not fail."""
+ try:
+ released = await asyncio.to_thread(self._journal.release_capture, review_key)
+ except Exception: # noqa: BLE001 - reported below, the wait still propagates
+ log.warning(
+ "ConversationFactExtractor: could not release the waiting review %s",
+ review_key[-24:],
+ exc_info=True,
+ )
+ return
+ if not released:
+ log.warning(
+ "ConversationFactExtractor: waiting review %s was not in progress; "
+ "its attempt could not be handed back",
+ review_key[-24:],
+ )
+
+ async def _log_unclaimed(self, review_key: str, *, source_label: str) -> None:
+ """Say why a review was not started instead of returning 0 silently."""
+ try:
+ status = await asyncio.to_thread(self._journal.capture_status, review_key)
+ attempts = await asyncio.to_thread(self._journal.capture_attempts, review_key)
+ except Exception: # noqa: BLE001 - the unclaimed review itself is reported below
+ status, attempts = None, 0
+ log.debug(
+ "ConversationFactExtractor: capture status lookup failed", exc_info=True
+ )
+ if status == "failed":
+ log.warning(
+ "ConversationFactExtractor: %s is not reviewed again — it failed %d "
+ "time(s) and its retry budget is spent (review %s)",
+ source_label,
+ attempts,
+ review_key[-24:],
+ )
+ elif status == "started":
+ log.info(
+ "ConversationFactExtractor: %s is already being reviewed (review %s)",
+ source_label,
+ review_key[-24:],
+ )
+ elif status is None:
+ log.warning(
+ "ConversationFactExtractor: %s could not be claimed — the capture "
+ "journal is unavailable (review %s)",
+ source_label,
+ review_key[-24:],
+ )
+ else:
+ log.debug(
+ "ConversationFactExtractor: %s was already reviewed (%s)",
+ source_label,
+ status,
+ )
+
async def _finish_review(
self,
review_key: str,
@@ -885,13 +947,18 @@ class ConversationFactExtractor:
await self._maybe_trigger_consolidation()
return appended
- def _background_chain(self) -> WikiBackgroundChain:
+ async def _background_chain(self) -> WikiBackgroundChain:
"""The provider chain this extraction may bill, or raise to make it wait.
Checks the runaway guard (backoff window, daily cap) and the
background billing policy BEFORE any review is claimed, so an install
- waiting on its subscription never spends a retry attempt.
+ waiting on its subscription never spends a retry attempt. Provider
+ selection may shell out to vendor login probes for seconds, so it
+ runs on a worker thread, never on the voice event loop (AP-9).
"""
+ return await asyncio.to_thread(self._background_chain_blocking)
+
+ def _background_chain_blocking(self) -> WikiBackgroundChain:
from jarvis.memory.wiki.provider_chain import build_background_wiki_chain
background_guard.check_ready(self._root_cfg)
diff --git a/jarvis/memory/wiki/journal.py b/jarvis/memory/wiki/journal.py
index 8dd49a98e0..d00ed87bd1 100644
--- a/jarvis/memory/wiki/journal.py
+++ b/jarvis/memory/wiki/journal.py
@@ -61,7 +61,9 @@ _CAPTURE_FINISH_STATUSES = frozenset({"filtered", "empty", "candidates", "failed
_CAPTURE_STALE_AFTER_MS = 5 * 60 * 1000
# A review that keeps failing is retried at most this many times in total.
# Every retry is a paid model call; before the bound the periodic
-# auto-backfill re-claimed failed reviews forever.
+# auto-backfill re-claimed failed reviews forever. A review that only had to
+# WAIT (subscription not answering, daily cap) is released through
+# ``release_capture`` and never runs this budget down.
_MAX_CAPTURE_ATTEMPTS = 5
_MAX_FACT_CHARS = 2_000
_MAX_EVIDENCE_CHARS = 1_200
@@ -454,8 +456,12 @@ class CandidateJournal:
A new key is claimed immediately. ``failed`` rows and ``started`` rows
older than five minutes are retried with an incremented attempt count,
- up to :data:`_MAX_CAPTURE_ATTEMPTS` attempts in total. Fresh in-flight,
- terminal, or exhausted rows are left untouched and return ``False``.
+ up to :data:`_MAX_CAPTURE_ATTEMPTS` attempts in total. A review that
+ was only released because the work had to wait (``failed`` with
+ ``deferred``, see :meth:`release_capture`) is always claimable again
+ and re-claiming it does not count: waiting never spends the budget.
+ Fresh in-flight, terminal, or exhausted rows are left untouched and
+ return ``False``.
"""
key = _safe_identifier(review_key, allow_empty=False)
now_ms = self._now_ms()
@@ -483,14 +489,21 @@ class CandidateJournal:
provider = '',
duration_ms = 0,
error_code = '',
- attempts = wiki_extraction_audit.attempts + 1,
+ attempts = CASE
+ WHEN wiki_extraction_audit.status = 'failed'
+ AND wiki_extraction_audit.error_code = 'deferred'
+ THEN wiki_extraction_audit.attempts
+ ELSE wiki_extraction_audit.attempts + 1
+ END,
updated_ms = excluded.updated_ms,
started_ms = excluded.started_ms,
finished_ms = NULL
- WHERE wiki_extraction_audit.attempts < ?
- AND (wiki_extraction_audit.status = 'failed'
- OR (wiki_extraction_audit.status = 'started'
- AND wiki_extraction_audit.updated_ms <= ?))
+ WHERE (wiki_extraction_audit.status = 'failed'
+ AND (wiki_extraction_audit.error_code = 'deferred'
+ OR wiki_extraction_audit.attempts < ?))
+ OR (wiki_extraction_audit.status = 'started'
+ AND wiki_extraction_audit.attempts < ?
+ AND wiki_extraction_audit.updated_ms <= ?)
""",
(
key,
@@ -503,6 +516,7 @@ class CandidateJournal:
now_ms,
now_ms,
_MAX_CAPTURE_ATTEMPTS,
+ _MAX_CAPTURE_ATTEMPTS,
stale_before_ms,
),
)
@@ -553,6 +567,45 @@ class CandidateJournal:
conn.commit()
return cur.rowcount == 1
+ def release_capture(self, review_key: str) -> bool:
+ """Hand a claimed review back without spending one of its attempts.
+
+ For a review that never got an answer because the work had to WAIT —
+ the subscription was not answering, or the runaway guard's daily cap
+ was reached. The row becomes retryable (``failed`` / ``deferred``),
+ and :meth:`claim_capture` re-claims such a row without counting an
+ attempt, so an explicit "remember this" survives a long subscription
+ outage instead of running out of :data:`_MAX_CAPTURE_ATTEMPTS` while
+ nothing was ever tried.
+ """
+ key = _safe_identifier(review_key, allow_empty=False)
+ now_ms = self._now_ms()
+ with self._lock:
+ conn = self._connection()
+ if conn is None:
+ return False
+ cur = conn.execute(
+ "UPDATE wiki_extraction_audit SET status = 'failed', "
+ "error_code = 'deferred', updated_ms = ?, finished_ms = ? "
+ "WHERE review_key = ? AND status = 'started'",
+ (now_ms, now_ms, key),
+ )
+ conn.commit()
+ return cur.rowcount == 1
+
+ def capture_attempts(self, review_key: str) -> int:
+ """How many counted attempts a review has used (0 when unknown)."""
+ key = _safe_identifier(review_key, allow_empty=False)
+ with self._lock:
+ conn = self._connection()
+ if conn is None:
+ return 0
+ row = conn.execute(
+ "SELECT attempts FROM wiki_extraction_audit WHERE review_key = ?",
+ (key,),
+ ).fetchone()
+ return int(row[0]) if row else 0
+
def capture_seen(self, review_key: str) -> bool:
"""Return ``True`` only when a capture reached a terminal status."""
return self.capture_status(review_key) in _CAPTURE_TERMINAL_STATUSES
diff --git a/jarvis/memory/wiki/recurate.py b/jarvis/memory/wiki/recurate.py
index 184201e5b6..c605c5d317 100644
--- a/jarvis/memory/wiki/recurate.py
+++ b/jarvis/memory/wiki/recurate.py
@@ -22,6 +22,7 @@ FTS). Manual invocation only (``jarvis.memory.wiki.cli recurate-profile``)
"""
from __future__ import annotations
+import asyncio
import logging
import time
from dataclasses import dataclass, field
@@ -195,7 +196,10 @@ async def recurate_profile(
registry = BrainProviderRegistry()
try:
- background = build_background_wiki_chain(
+ # Provider selection may run vendor login probes (seconds of subprocess):
+ # keep it off the event loop (AP-9).
+ background = await asyncio.to_thread(
+ build_background_wiki_chain,
registry=registry,
config=config,
primary=(wiki_cfg.curator.provider.strip() or config.brain.primary),
diff --git a/jarvis/memory/wiki/search_aliases.py b/jarvis/memory/wiki/search_aliases.py
index 29ad9d0d42..0e8cf3061f 100644
--- a/jarvis/memory/wiki/search_aliases.py
+++ b/jarvis/memory/wiki/search_aliases.py
@@ -34,6 +34,7 @@ crosses to another family instead of bricking the feature (AP-22).
from __future__ import annotations
+import asyncio
import logging
import re
from typing import Any
@@ -281,11 +282,18 @@ async def generate_aliases(
# credential (AP-22 — never a single-provider brick) and may bill
# background work.
try:
+ if count_against_daily_cap:
+ # Background write-time call: no alias lookup inside the runaway
+ # guard's backoff window or past the daily cap.
+ guard.check_ready(cfg)
curator = getattr(getattr(getattr(cfg, "memory", None), "wiki", None), "curator", None)
primary = str(getattr(curator, "provider", "") or "").strip() or str(
getattr(getattr(cfg, "brain", None), "primary", "") or ""
)
- background = build_background_wiki_chain(
+ # Provider selection may run vendor login probes (seconds of subprocess):
+ # keep it off the event loop (AP-9).
+ background = await asyncio.to_thread(
+ build_background_wiki_chain,
registry=registry,
config=cfg,
primary=primary,
diff --git a/jarvis/memory/wiki/session_rollup.py b/jarvis/memory/wiki/session_rollup.py
index 975134738b..23b98f8392 100644
--- a/jarvis/memory/wiki/session_rollup.py
+++ b/jarvis/memory/wiki/session_rollup.py
@@ -449,18 +449,23 @@ class SessionRollupWorker:
from jarvis.memory.wiki.curator_llm import instantiate_curator_brain
from jarvis.memory.wiki.provider_chain import subscription_provider_options
- try:
+ def _billing_gate() -> dict[str, Any] | None:
guard.check_ready(self._config)
decision = background_providers([provider_name])
if not decision.permits(provider_name):
raise BackgroundDeferred(decision.reason)
guard.reserve_call(self._config, label="session-rollup")
- except BackgroundDeferred as exc:
+ return subscription_provider_options(decision, self._registry).get(
+ provider_name
+ )
+
+ try:
+ # The policy may run vendor login probes (seconds of subprocess):
+ # keep it off the event loop (AP-9).
+ pinned = await asyncio.to_thread(_billing_gate)
+ except BackgroundDeferred as exc: # the skip is logged right here
log.info("SessionRollupWorker: digest skipped — %s", exc)
return None
- pinned = subscription_provider_options(decision, self._registry).get(
- provider_name
- )
try:
async with self._brain_lock:
diff --git a/tests/unit/agentic_ide/test_recap_engine.py b/tests/unit/agentic_ide/test_recap_engine.py
index 7f6c1c8f5b..e67b363598 100644
--- a/tests/unit/agentic_ide/test_recap_engine.py
+++ b/tests/unit/agentic_ide/test_recap_engine.py
@@ -791,16 +791,56 @@ def test_a_connected_subscription_writes_recaps_without_any_key(monkeypatch) ->
assert recap_engine._resolve_brains() == [subscription] # noqa: SLF001
-def test_without_a_subscription_the_keyed_chain_writes_recaps(monkeypatch) -> None:
+def test_without_a_subscription_the_keyed_chain_writes_recaps(monkeypatch, tmp_path) -> None:
"""A single-key install keeps model recaps (AP-22)."""
from jarvis.brain import resolver
+ from tests.fakes.fake_background_billing import (
+ isolate_background_billing,
+ reset_background_billing,
+ )
- api = SimpleNamespace(model="only-key")
- monkeypatch.setattr(resolver, "frontier_brain_candidates", lambda cfg: iter([api]))
- monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg, **kwargs: None)
- monkeypatch.setattr("jarvis.core.config.load_config", lambda: SimpleNamespace())
+ isolate_background_billing(monkeypatch, tmp_path / "billing")
+ try:
+ api = SimpleNamespace(model="only-key")
+ monkeypatch.setattr(resolver, "frontier_brain_candidates", lambda cfg: iter([api]))
+ monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg, **kwargs: None)
+ monkeypatch.setattr("jarvis.core.config.load_config", lambda: SimpleNamespace())
+
+ assert recap_engine._resolve_brains() == [api] # noqa: SLF001
+ finally:
+ reset_background_billing()
+
+
+def test_an_unavailable_subscription_never_falls_back_to_a_key(
+ monkeypatch, tmp_path
+) -> None:
+ """Recaps are background work: once a subscription is connected, a
+ subscription that cannot answer means the plain title, never a paid key —
+ no keyed brain is even instantiated."""
+ from jarvis.brain import resolver
+ from tests.fakes.fake_background_billing import (
+ isolate_background_billing,
+ reset_background_billing,
+ )
+
+ billing = isolate_background_billing(monkeypatch, tmp_path / "billing")
+ try:
+ billing.remember_subscription("claude-cli")
+ billing.sign_out("claude-cli")
+ instantiated: list[str] = []
+
+ def _keyed_candidates(_cfg): # noqa: ANN001, ANN202
+ instantiated.append("keyed")
+ yield SimpleNamespace(model="paid-key")
+
+ monkeypatch.setattr(resolver, "frontier_brain_candidates", _keyed_candidates)
+ monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg, **kwargs: None)
+ monkeypatch.setattr("jarvis.core.config.load_config", lambda: SimpleNamespace())
- assert recap_engine._resolve_brains() == [api] # noqa: SLF001
+ assert recap_engine._resolve_brains() == [] # noqa: SLF001
+ assert instantiated == [], "no keyed provider may be instantiated"
+ finally:
+ reset_background_billing()
def test_a_failing_provider_leaves_the_previous_sentence_in_place() -> None:
diff --git a/tests/unit/memory/wiki/test_background_guard.py b/tests/unit/memory/wiki/test_background_guard.py
index 25e4a5b134..6b0ce9bbc5 100644
--- a/tests/unit/memory/wiki/test_background_guard.py
+++ b/tests/unit/memory/wiki/test_background_guard.py
@@ -446,3 +446,147 @@ async def test_search_aliases_respect_the_daily_cap(
assert aliases == []
assert registry.instantiated == []
+
+
+async def test_search_aliases_wait_out_the_backoff() -> None:
+ from jarvis.memory.wiki.search_aliases import generate_aliases
+
+ registry = _RecordingRegistry({"gemini"}, _ScriptedBrain(text="Hund"))
+ guard.note_failure("every wiki provider failed")
+
+ aliases = await generate_aliases(
+ title="Dog", body="The user's dog.", cfg=_config(), registry=registry,
+ )
+
+ assert aliases == []
+ assert registry.available_calls == 0, "no provider lookup inside the backoff"
+ assert registry.instantiated == []
+
+
+# --- review attempts ---------------------------------------------------------
+
+
+def _extractor(journal: CandidateJournal, registry: Any) -> Any:
+ from jarvis.memory.wiki.extractor import ConversationFactExtractor
+
+ return ConversationFactExtractor(config=_config(), journal=journal, registry=registry)
+
+
+def test_a_released_review_keeps_its_attempt_budget(tmp_path: Path) -> None:
+ journal = CandidateJournal(tmp_path / "jarvis.db")
+ key = "live:v2:voice:1:abc"
+ try:
+ for _ in range(12):
+ assert journal.claim_capture(key, "voice-fact:1", "voice-fact", "a" * 40)
+ assert journal.release_capture(key)
+ assert journal.capture_attempts(key) == 1, "waiting never counts an attempt"
+ assert journal.capture_status(key) == "failed"
+ # The full failure budget is still there for real failures.
+ failures = 0
+ while journal.claim_capture(key, "voice-fact:1", "voice-fact", "a" * 40):
+ journal.finish_capture(key, "failed", error_code="provider_timeout")
+ failures += 1
+ assert failures == 5 # the whole budget, none of it spent on waiting
+ finally:
+ journal.close()
+
+
+async def test_a_long_subscription_outage_never_burns_the_explicit_save(
+ tmp_path: Path, background_billing, # noqa: ANN001
+) -> None:
+ """Signed in but not answering for hours: every retry hands its attempt
+ back, so the save is still reviewed once the subscription answers."""
+ background_billing.sign_in("claude-cli")
+ registry = _RecordingRegistry({"claude-cli", "gemini"}, _ScriptedBrain(fail=True))
+ journal = CandidateJournal(tmp_path / "jarvis.db")
+ extractor = _extractor(journal, registry)
+ key = "live:v2:rt-session:turn-1"
+ try:
+ for _ in range(8): # well past the five-attempt failure budget
+ guard.note_progress() # the backoff window has passed
+ with pytest.raises(BackgroundDeferred):
+ await extractor.extract_and_journal(
+ "Lena lives in Hamburg.",
+ "Noted.",
+ source_label="realtime-fact:1",
+ turn_hash="turn-1",
+ review_key=key,
+ )
+ assert journal.capture_attempts(key) == 1, "eight waits spent no attempt"
+ assert set(registry.instantiated) == {"claude-cli"}, "never the keyed provider"
+
+ registry._brain = _ScriptedBrain(text="[]") # noqa: SLF001 - it answers again
+ guard.note_progress()
+ await extractor.extract_and_journal(
+ "Lena lives in Hamburg.",
+ "Noted.",
+ source_label="realtime-fact:1",
+ turn_hash="turn-1",
+ review_key=key,
+ )
+ assert journal.capture_status(key) == "empty"
+ assert journal.capture_attempts(key) == 1
+ finally:
+ journal.close()
+
+
+async def test_an_exhausted_review_is_reported_not_dropped_silently(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture,
+) -> None:
+ journal = CandidateJournal(tmp_path / "jarvis.db")
+ brain = _ScriptedBrain(text="[]")
+ extractor = _extractor(journal, _RecordingRegistry({"gemini"}, brain))
+ key = "live:v2:voice:2:def"
+ try:
+ while journal.claim_capture(key, "voice-fact:2", "voice-fact", "b" * 40):
+ journal.finish_capture(key, "failed", error_code="provider_timeout")
+ with caplog.at_level("WARNING", logger="jarvis.memory.wiki.extractor"):
+ count = await extractor.extract_and_journal(
+ "Lena lives in Hamburg.",
+ "Noted.",
+ source_label="voice-fact:2",
+ turn_hash="turn-2",
+ review_key=key,
+ )
+ finally:
+ journal.close()
+
+ assert count == 0
+ assert brain.calls == 0
+ assert any(
+ record.levelname == "WARNING" and "retry budget is spent" in record.getMessage()
+ for record in caplog.records
+ )
+
+
+# --- provider selection stays off the event loop ------------------------------
+
+
+async def test_provider_selection_runs_off_the_event_loop(
+ wiki, monkeypatch: pytest.MonkeyPatch, # noqa: ANN001
+) -> None:
+ import threading
+
+ import jarvis.memory.wiki.provider_chain as chain_module
+
+ real_build = chain_module.build_background_wiki_chain
+ on_main_thread: list[bool] = []
+
+ def _recording_build(**kwargs: Any) -> Any:
+ on_main_thread.append(threading.current_thread() is threading.main_thread())
+ return real_build(**kwargs)
+
+ monkeypatch.setattr(chain_module, "build_background_wiki_chain", _recording_build)
+ registry = _RecordingRegistry({"gemini"}, _ScriptedBrain(text="[]"))
+ consolidator = _consolidator(wiki, registry, config=_config())
+ _journal_facts(wiki[2], 1)
+ await consolidator.run_once()
+ guard.note_progress()
+ await _extractor(wiki[2], registry).extract_and_journal(
+ "Lena lives in Hamburg.",
+ "Noted.",
+ source_label="voice-fact:3",
+ turn_hash="turn-3",
+ )
+
+ assert on_main_thread == [False, False], "login probes must never block the loop"