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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(society): coalesce review drains and keep a durable per-review attempt budget
rubenluetke10-beepeeeb69ed8037
diff --git a/docs/agent-society/self-learning.md b/docs/agent-society/self-learning.mdindex d128811234..e915282702 100644--- a/docs/agent-society/self-learning.md+++ b/docs/agent-society/self-learning.md@@ -11,9 +11,11 @@> **Seat rule (2026-09-30):** an agent's turn review and skill learning run> on exactly that agent's seat — the provider, model and auth mode its chat> uses (`jarvis/society/seat_brain.py`). No other provider, subscription or-> key is asked. A review whose seat keeps failing gets its first attempt plus-> three spaced retries and is then dropped (status `dropped`) with one log-> line.+> key is asked. A review whose seat keeps failing costs at most four seat+> calls in total, spaced by a jittered backoff, and is then dropped (status+> `dropped`) with one log line. The attempt count and next due time are+> stored on the review row, so neither a burst of turns nor a restart adds+> calls; concurrent drain requests are coalesced into one extra pass.Tier: **T3 capability**. Jarvis and every Society agent use the same portablelearning loop, with separate ownership, files, review locks and provider scopes.diff --git a/jarvis/society/conversation.py b/jarvis/society/conversation.pyindex f8d237f9a6..36ff4f85ee 100644--- a/jarvis/society/conversation.py+++ b/jarvis/society/conversation.py@@ -47,6 +47,7 @@ class ConversationArchive:session TEXT NOT NULL, turn_id TEXT NOT NULL, events TEXT NOT NULL,status TEXT NOT NULL DEFAULT 'pending', PRIMARY KEY(session,turn_id));""")+ self._migrate_reviews()try:self._db.execute("CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(text)")self.fts_available = True@@ -60,6 +61,23 @@ class ConversationArchive:)self._db.commit()+ def _migrate_reviews(self) -> None:+ """Idempotent column migrations for archives created by older builds.++ ``attempts`` and ``retry_after_ms`` make the review retry budget+ durable: a review's failed attempts survive a restart, so an app+ restart never hands a failing seat a fresh set of calls.+ """+ existing = {str(row[1]) for row in self._db.execute("PRAGMA table_info(reviews)")}+ if "attempts" not in existing:+ self._db.execute("ALTER TABLE reviews ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0")+ log.info("conversation archive: migration applied - added reviews.attempts")+ if "retry_after_ms" not in existing:+ self._db.execute(+ "ALTER TABLE reviews ADD COLUMN retry_after_ms INTEGER NOT NULL DEFAULT 0"+ )+ log.info("conversation archive: migration applied - added reviews.retry_after_ms")+def close(self) -> None:with self._lock:self._db.close()@@ -163,18 +181,48 @@ class ConversationArchive:return bool(cursor.rowcount)def pending_reviews(self) -> list[dict[str, Any]]:+ """Pending reviews, oldest first, with their durable retry state:+ ``attempts`` (failed attempts so far) and ``retry_after_ms`` (not due+ before this wall-clock time; 0 = due now)."""with self._lock:rows = self._db.execute(- "SELECT session,turn_id,events FROM reviews WHERE status='pending' ORDER BY rowid"+ "SELECT session,turn_id,events,attempts,retry_after_ms FROM reviews "+ "WHERE status='pending' ORDER BY rowid").fetchall()result = []for row in rows:stored = json.loads(row[2])if isinstance(stored, list):stored = {"events": stored, "direct_user": False}- result.append({"session": row[0], "turn_id": row[1], **stored})+ result.append(+ {+ "session": row[0],+ "turn_id": row[1],+ **stored,+ "attempts": int(row[3] or 0),+ "retry_after_ms": int(row[4] or 0),+ }+ )return result+ def fail_review(self, session: str, turn_id: str, *, retry_after_ms: int) -> int:+ """Count one failed attempt and hold the review until ``retry_after_ms``.++ Returns the review's failed attempts so far (0 when it is no longer+ pending, e.g. finished or dropped meanwhile).+ """+ with self._lock, self._db:+ self._db.execute(+ "UPDATE reviews SET attempts=attempts+1, retry_after_ms=? "+ "WHERE session=? AND turn_id=? AND status='pending'",+ (int(retry_after_ms), session, turn_id),+ )+ row = self._db.execute(+ "SELECT attempts FROM reviews WHERE session=? AND turn_id=? AND status='pending'",+ (session, turn_id),+ ).fetchone()+ return int(row[0]) if row is not None else 0+def finish_review(self, session: str, turn_id: str) -> None:with self._lock, self._db:self._db.execute(diff --git a/jarvis/society/review_queue.py b/jarvis/society/review_queue.pyindex e00bf04d23..96e6ed25d9 100644--- a/jarvis/society/review_queue.py+++ b/jarvis/society/review_queue.py@@ -1,10 +1,16 @@"""Bounded automatic retries for durable post-turn memory reviews.A review runs on the reviewed agent's own seat and nothing else-(``seat_brain``). When that seat keeps failing, the review gets its first-attempt plus ``MAX_RETRIES`` spaced retries and is then dropped with one log-line, instead of being retried on every later turn or answered by another-provider.+(``seat_brain``). When that seat keeps failing, a review gets at most+``MAX_ATTEMPTS`` seat calls in total, spaced by a jittered backoff, and is+then dropped with one log line. The budget is durable: the attempt count and+the next due time live on the review row, so neither a burst of turns nor an+app restart hands a failing seat extra calls.++Drains are coalesced: every finished turn asks for one, but while a drain+runs, further requests only mark that another pass is wanted. A drain only+calls the seat for reviews that are due; one wake-up is kept for the next+review that becomes due."""from __future__ import annotations@@ -14,70 +20,91 @@ import loggingimport randomfrom typing import Any, Final+from .events import now_msfrom .review import review_turnlog = logging.getLogger(__name__)-#: Spaced retries after the first attempt (45-60 s, doubled per round).-MAX_RETRIES: Final[int] = 3-#: Failed attempts after which a review is dropped: the first plus the retries.-MAX_ATTEMPTS: Final[int] = MAX_RETRIES + 1---def _failures(runtime: Any) -> dict[tuple[str, str], int]:- """Failed attempts per pending review in this process."""- failures = getattr(runtime, "_review_failures", None)- if failures is None:- failures = {}- runtime._review_failures = failures- return failures---async def drain_reviews(runtime: Any, *, retry: int = 0) -> None:- failures = _failures(runtime)- async with runtime._review_lock:- for pending in runtime.conversations.pending_reviews():- key = (pending["session"], pending["turn_id"])- try:- done = await review_turn(runtime, pending)- except Exception:- log.exception("society review remains pending for %s", pending["turn_id"])- done = False- if done:- runtime.conversations.finish_review(*key)- failures.pop(key, None)- continue- failures[key] = failures.get(key, 0) + 1- # Only the last round of a retry chain drops, so a burst of turns- # never uses up a review's attempts before the spaced retries ran.- if retry >= MAX_RETRIES and failures[key] >= MAX_ATTEMPTS:- runtime.conversations.drop_review(*key)- attempts = failures.pop(key)- log.warning(- "society review of turn %s (%s) dropped after %d failed attempts; "- "only the agent's own seat is ever asked",- pending["turn_id"],- pending["session"],- attempts,- )- if (- not runtime.conversations.pending_reviews()- or retry >= MAX_RETRIES- or getattr(runtime, "_closing", False)- ):- return- active = getattr(runtime, "_memory_review_retry", None)- if active is not None and not active.done():+#: Seat calls one review may cost before it is dropped: a first attempt plus+#: three spaced retries.+MAX_ATTEMPTS: Final[int] = 4+#: Pause after the n-th failed attempt: 45-60 s, doubled per attempt.+_BACKOFF_MIN_S: Final[float] = 45.0+_BACKOFF_MAX_S: Final[float] = 60.0+++def _backoff_ms(attempts: int) -> int:+ delay = random.uniform(_BACKOFF_MIN_S, _BACKOFF_MAX_S) # noqa: S311 — retry jitter, not a secret+ return int(delay * 2 ** max(0, attempts - 1) * 1000)+++async def drain_reviews(runtime: Any) -> None:+ """Review every due pending turn; coalesced with a drain already running."""+ if getattr(runtime, "_review_draining", False):+ # One drain at a time: the running one makes one more pass for this+ # request (a turn queued meanwhile is picked up there).+ runtime._review_rerun = Truereturn+ runtime._review_draining = True+ try:+ while True:+ runtime._review_rerun = False+ async with runtime._review_lock:+ await _drain_once(runtime)+ if not runtime._review_rerun or getattr(runtime, "_closing", False):+ break+ finally:+ runtime._review_draining = False+ _schedule_wake(runtime)+- async def later() -> None:+async def _drain_once(runtime: Any) -> None:+ archive = runtime.conversations+ for pending in archive.pending_reviews():+ if pending["retry_after_ms"] > now_ms():+ continue # Still waiting out its backoff: no seat call now.+ key = (pending["session"], pending["turn_id"])try:- delay = random.uniform(45, 60) * 2**retry # noqa: S311 — retry jitter, not a secret- await asyncio.sleep(delay)- runtime._memory_review_retry = None- await drain_reviews(runtime, retry=retry + 1)- finally:- if getattr(runtime, "_memory_review_retry", None) is asyncio.current_task():- runtime._memory_review_retry = None-- runtime._memory_review_retry = runtime.background(later())+ done = await review_turn(runtime, pending)+ except Exception:+ log.exception("society review remains pending for %s", pending["turn_id"])+ done = False+ if done:+ archive.finish_review(*key)+ continue+ attempts = archive.fail_review(+ *key, retry_after_ms=now_ms() + _backoff_ms(pending["attempts"] + 1)+ )+ if attempts >= MAX_ATTEMPTS:+ archive.drop_review(*key)+ log.warning(+ "society review of turn %s (%s) dropped after %d failed attempts; "+ "only the agent's own seat is ever asked",+ pending["turn_id"],+ pending["session"],+ attempts,+ )+++def _schedule_wake(runtime: Any) -> None:+ """Keep exactly one wake-up, for the earliest pending review's due time."""+ if getattr(runtime, "_closing", False):+ return+ pending = runtime.conversations.pending_reviews()+ if not pending:+ return+ due = min(item["retry_after_ms"] for item in pending)+ current = getattr(runtime, "_memory_review_retry", None)+ if current is not None and current is not asyncio.current_task() and not current.done():+ if getattr(runtime, "_memory_review_retry_at", 0) <= due:+ return # An earlier (or equal) wake-up is already armed.+ # Only a sleeping wake-up can be here: a draining one would have+ # coalesced this drain instead of letting it reach this point.+ current.cancel()+ runtime._memory_review_retry_at = due+ runtime._memory_review_retry = runtime.background(_wake(runtime, due))+++async def _wake(runtime: Any, due: int) -> None:+ await asyncio.sleep(max(0.0, (due - now_ms()) / 1000))+ await drain_reviews(runtime)diff --git a/tests/unit/society/test_seat_memory.py b/tests/unit/society/test_seat_memory.pyindex dcd4f67905..55a4ed92f6 100644--- a/tests/unit/society/test_seat_memory.py+++ b/tests/unit/society/test_seat_memory.py@@ -157,11 +157,13 @@ def _queue(rt, turn_id: str = "turn-1") -> None:async def _settle(rt) -> None:- for _ in range(10):- retry = rt._memory_review_retry- if retry is None:+ """Follow the armed wake-ups until none is left."""+ for _ in range(20):+ retry = getattr(rt, "_memory_review_retry", None)+ if retry is None or retry.done():returnawait asyncio.wait_for(retry, 5)+ raise AssertionError("the review queue kept waking up")async def test_a_seat_that_keeps_failing_drops_the_review_after_bounded_retries(@@ -189,19 +191,127 @@ async def test_a_seat_that_keeps_failing_drops_the_review_after_bounded_retries(assert len(attempts) == review_queue.MAX_ATTEMPTS-async def test_a_burst_of_turns_does_not_use_up_the_spaced_retries(rt, monkeypatch):+async def test_a_burst_of_turns_calls_the_seat_only_for_due_reviews(rt, monkeypatch):from jarvis.society import review_queue+ calls = []+async def seat_down(*args):+ calls.append(True)return Nonert.turn_reviewer = seat_down- # The retry chain waits; only turn-triggered drains run.+ # The backoff is long: only turn-triggered drains run during the test.monkeypatch.setattr(review_queue.random, "uniform", lambda *args: 3600)_queue(rt)- for _ in range(review_queue.MAX_ATTEMPTS + 2):+ for _ in range(10):await rt.recover_reviews()- assert rt.conversations.review_counts("scout") == {"pending": 1, "done": 0}+ assert len(calls) == 1 # The failed review waits out its backoff.+ [pending] = rt.conversations.pending_reviews()+ assert pending["attempts"] == 1+++async def test_concurrent_drain_requests_are_coalesced(rt, monkeypatch):+ from jarvis.society import review_queue++ started = asyncio.Event()+ release = asyncio.Event()+ calls = []++ async def slow_seat(*args):+ calls.append(True)+ started.set()+ await release.wait()+ return None++ rt.turn_reviewer = slow_seat+ monkeypatch.setattr(review_queue.random, "uniform", lambda *args: 3600)+ for index in range(3):+ _queue(rt, f"turn-{index}")+ first = asyncio.create_task(rt.recover_reviews())+ await asyncio.wait_for(started.wait(), 5)+ # Ten more finished turns while the seat is still thinking.+ await asyncio.gather(*(rt.recover_reviews() for _ in range(10)))+ release.set()+ await asyncio.wait_for(first, 5)+ # One call per review: the queued requests became one extra pass, and+ # that pass found every review waiting out its backoff.+ assert len(calls) == 3+ assert [p["attempts"] for p in rt.conversations.pending_reviews()] == [1, 1, 1]+++async def test_the_attempt_budget_survives_a_restart(tmp_path, monkeypatch):+ from jarvis.society import review_queue+ from jarvis.society.runtime import SocietyRuntime++ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))+ # A previous run: the agent exists and three attempts are already spent.+ first = SocietyRuntime(tmp_path, cfg=lambda: cfg, seed_starter_team=False)+ await first.ensure_started()+ try:+ await first.roster.create(name="Scout", description="Draft only.")+ _queue(first)+ for _ in range(review_queue.MAX_ATTEMPTS - 1):+ first.conversations.fail_review("society:scout", "turn-1", retry_after_ms=0)+ finally:+ await first.close()++ calls = []++ async def seat_down(*args):+ calls.append(True)+ return None++ monkeypatch.setattr(review_queue.random, "uniform", lambda *args: 0)+ runtime = SocietyRuntime(tmp_path, cfg=lambda: cfg, seed_starter_team=False)+ runtime.turn_reviewer = seat_down+ await runtime.ensure_started() # Its startup drain runs the review.+ try:+ await runtime.recover_reviews()+ for _ in range(100):+ if not runtime.conversations.pending_reviews():+ break+ await asyncio.sleep(0.02)+ await _settle(runtime)+ assert len(calls) == 1 # Only the last attempt of the budget was left.+ assert runtime.conversations.review_counts("scout") == {+ "pending": 0,+ "done": 0,+ "dropped": 1,+ }+ finally:+ await runtime.close()+++def test_an_old_archive_gains_the_retry_columns(tmp_path):+ import sqlite3++ from jarvis.society.conversation import ConversationArchive++ path = tmp_path / "society-conversations.db"+ with sqlite3.connect(path) as db:+ db.execute(+ "CREATE TABLE reviews (session TEXT NOT NULL, turn_id TEXT NOT NULL, "+ "events TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', "+ "PRIMARY KEY(session,turn_id))"+ )+ db.execute(+ "INSERT INTO reviews(session,turn_id,events) VALUES(?,?,?)",+ ("society:scout", "old-turn", json.dumps({"events": [], "direct_user": True})),+ )+ archive = ConversationArchive(path)+ try:+ [pending] = archive.pending_reviews()+ assert (pending["turn_id"], pending["attempts"], pending["retry_after_ms"]) == (+ "old-turn",+ 0,+ 0,+ )+ assert archive.fail_review("society:scout", "old-turn", retry_after_ms=5) == 1+ finally:+ archive.close()+ # Reopening is idempotent.+ ConversationArchive(path).close()# ── Society skill learning ──────────────────────────────────────────────────