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.

perf(realtime): cut the delegate dead wait and move wiki extraction off the live call

Personal Jarvis Maintainerdd648a591705
diff --git a/jarvis/memory/wiki/voice_bridge.py b/jarvis/memory/wiki/voice_bridge.py
index 3f9235ec20..e35f1b7c3d 100644
--- a/jarvis/memory/wiki/voice_bridge.py
+++ b/jarvis/memory/wiki/voice_bridge.py
@@ -72,6 +72,16 @@ log = logging.getLogger(__name__)
# hash gate makes sure only one extraction fires per distinct turn text.
_SEEN_HASHES_MAX = 128
+# Per-turn extractions captured DURING a live realtime call are deferred and
+# run at session end: each extraction is an LLM round (provider call, 429
+# retry storms, Codex CLI subprocess spawns) on the same event loop that
+# paces the call's audio, and freshly journaled candidates additionally
+# trigger in-call consolidator judge rounds (live 2026-07-21 11:31: a
+# 10.9 s judge round mid-call; the loop-stall forensics measured 481 ms).
+# AP-9: awareness work stays off the voice hot path. Bounded so a session
+# that never ends cannot grow the queue without limit.
+_DEFERRED_MAX_PER_SESSION = 200
+
def _turn_hash(text: str) -> str:
"""Stable hash of a normalised turn text (case/whitespace-insensitive)."""
@@ -154,6 +164,12 @@ class VoiceFactBridge:
self._unsubs: list[Any] = []
self._inflight: set[asyncio.Task[Any]] = set()
self._session_inflight: dict[str, set[asyncio.Task[Any]]] = {}
+ # In-call extraction jobs held back until the session ends (AP-9).
+ # Keyed by session id; each entry is the full argument tuple of one
+ # already-deduped `_extract_safe` run.
+ self._deferred_extractions: dict[
+ str, list[tuple[_PendingTurn, str, str, str, str]]
+ ] = {}
self._realtime_sessions: dict[str, list[ConversationContextTurn]] = {}
self._realtime_turn_ids: dict[str, set[str]] = {}
self._started = False
@@ -234,6 +250,7 @@ class VoiceFactBridge:
self._session_inflight.clear()
self._realtime_sessions.clear()
self._realtime_turn_ids.clear()
+ self._deferred_extractions.clear()
self._started = False
return tasks
@@ -352,6 +369,29 @@ class VoiceFactBridge:
session_id = (getattr(event, "session_id", "") or "").strip()
turns = tuple(self._realtime_sessions.pop(session_id, ()))
self._realtime_turn_ids.pop(session_id, None)
+ deferred = tuple(self._deferred_extractions.pop(session_id, ()))
+ if deferred and self._extractor is not None:
+ # Registered under the session BEFORE the sweep task is created,
+ # so the sweep's inflight snapshot waits for these turn reviews
+ # exactly as it waited for their in-call predecessors.
+ flush = asyncio.create_task(
+ self._run_deferred_extractions(session_id, deferred),
+ name=f"wiki-realtime-deferred-extract-{session_id[:12]}",
+ )
+ self._inflight.add(flush)
+ flush.add_done_callback(self._inflight.discard)
+ session_tasks = self._session_inflight.setdefault(session_id, set())
+ session_tasks.add(flush)
+
+ def _discard_flush(done: asyncio.Task[Any]) -> None:
+ active = self._session_inflight.get(session_id)
+ if active is None:
+ return
+ active.discard(done)
+ if not active:
+ self._session_inflight.pop(session_id, None)
+
+ flush.add_done_callback(_discard_flush)
if self._extractor is None or not session_id or not turns:
return
task = asyncio.create_task(
@@ -460,6 +500,39 @@ class VoiceFactBridge:
)
return
+ if (
+ pending.origin == "realtime"
+ and pending.session_id
+ and pending.session_id in self._realtime_sessions
+ ):
+ # The call is still live: hold the LLM round back (AP-9). The
+ # turn is already deduped, so it is recorded as seen now — the
+ # queue append cannot fail the way create_task can.
+ queue = self._deferred_extractions.setdefault(
+ pending.session_id, []
+ )
+ if len(queue) >= _DEFERRED_MAX_PER_SESSION:
+ log.warning(
+ "VoiceFactBridge: deferred-extraction queue full for %s "
+ "— dropping turn (hash=%s)",
+ pending.session_id[:12],
+ review_key[-24:],
+ )
+ return
+ queue.append(
+ (pending, reply_raw, source_kind, turn_hash, review_key)
+ )
+ self._seen_hashes[review_key] = None
+ while len(self._seen_hashes) > _SEEN_HASHES_MAX:
+ self._seen_hashes.popitem(last=False)
+ log.debug(
+ "VoiceFactBridge[%s]: extraction deferred until session end "
+ "(%d queued)",
+ source_kind,
+ len(queue),
+ )
+ return
+
task = asyncio.create_task(
self._extract_safe(
pending,
@@ -545,6 +618,31 @@ class VoiceFactBridge:
source_kind,
)
+ async def _run_deferred_extractions(
+ self,
+ session_id: str,
+ jobs: tuple[tuple[_PendingTurn, str, str, str, str], ...],
+ ) -> None:
+ """Run the call's held-back per-turn extractions, one at a time.
+
+ Sequential on purpose: firing the whole backlog concurrently at
+ hangup would reproduce the in-call 429 retry storms this deferral
+ removes, just compressed into one burst.
+ """
+ log.info(
+ "VoiceFactBridge: running %d deferred extraction(s) for %s",
+ len(jobs),
+ session_id[:12],
+ )
+ for pending, reply_raw, source_kind, turn_hash, review_key in jobs:
+ await self._extract_safe(
+ pending,
+ reply_raw,
+ source_kind=source_kind,
+ turn_hash=turn_hash,
+ review_key=review_key,
+ )
+
async def _sweep_session_safe(
self,
session_id: str,
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index ff33dca130..fc97d89abc 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -98,10 +98,16 @@ _END_CALL_DECLARATION: dict[str, Any] = {
# the router turn itself offloads heavy work to background missions, so a
# turn that exceeds this is stuck, not busy.
_DELEGATE_TIMEOUT_S = 90.0
-_DELEGATE_INPUT_BOUNDARY_WAIT_S = 3.0
+# Stability window before a boundary-less dispatch: the surface's own
+# endpointing already closed the utterance before the delegate started, so
+# the old fixed 3.0 s wait round was pure added latency in front of EVERY
+# delegated turn whose provider never sends an input boundary (live
+# 2026-07-21 11:31: all four fallback turns of the morning paid it). The
+# window re-arms while the input transcript is still growing.
+_DELEGATE_INPUT_BOUNDARY_WAIT_S = 1.5
+_DELEGATE_INPUT_BOUNDARY_POLL_S = 0.25
# A provider that stays completely silent must never veto a delegated turn.
-# Each wait round re-arms only while the input transcript is still growing
-# (the user is audibly mid-utterance); a stable transcript dispatches.
+# The hard cap for a continuously growing transcript is WAIT_S x MAX_ROUNDS.
_DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS = 6
_DELEGATE_NATIVE_BOUNDARY_WAIT_S = 1.0
# Delivering a delegate result does not force the provider to render it:
@@ -4374,34 +4380,47 @@ class RealtimeVoiceSession:
transcript still growing re-arms the window: the user is audibly
mid-utterance, and dispatching would act on a partial request.
"""
- for _ in range(_DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS):
- transcript_before_wait = self._last_user_text
+ stability_s = _DELEGATE_INPUT_BOUNDARY_WAIT_S
+ poll_s = max(min(_DELEGATE_INPUT_BOUNDARY_POLL_S, stability_s / 2), 0.01)
+ deadline = (
+ time.monotonic() + stability_s * _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS
+ )
+ stable_since = time.monotonic()
+ last_transcript = self._last_user_text
+ while True:
try:
await asyncio.wait_for(
turn_state.input_boundary_ready.wait(),
- timeout=_DELEGATE_INPUT_BOUNDARY_WAIT_S,
+ timeout=poll_s,
)
+ return
except TimeoutError:
- if turn_state.input_final or (
- self._last_user_text == transcript_before_wait
- ):
- log.info(
- "realtime[%s] deterministic delegate: provider input "
- "boundary missing after %.1fs; dispatching on the "
- "stable local transcript",
- self.session_id,
- _DELEGATE_INPUT_BOUNDARY_WAIT_S,
- )
- return
- continue
- return
- log.warning(
- "realtime[%s] deterministic delegate: input transcript kept "
- "growing through %d wait rounds; dispatching on the newest "
- "snapshot",
- self.session_id,
- _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS,
- )
+ pass
+ now = time.monotonic()
+ if self._last_user_text != last_transcript:
+ last_transcript = self._last_user_text
+ stable_since = now
+ elif turn_state.input_final or now - stable_since >= stability_s:
+ # ``input_final`` is boundary evidence by construction (the
+ # provider already responded to this input), so it needs no
+ # further stability margin — only the poll granularity.
+ log.info(
+ "realtime[%s] deterministic delegate: provider input "
+ "boundary missing after %.2fs of stable local "
+ "transcript; dispatching",
+ self.session_id,
+ now - stable_since,
+ )
+ return
+ if now >= deadline:
+ log.warning(
+ "realtime[%s] deterministic delegate: input transcript "
+ "kept growing through the %.0fs wait cap; dispatching "
+ "on the newest snapshot",
+ self.session_id,
+ stability_s * _DELEGATE_INPUT_BOUNDARY_MAX_ROUNDS,
+ )
+ return
async def _run_deterministic_delegate(
self,
diff --git a/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py b/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
index b4213fcbaf..d70d48e9fa 100644
--- a/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
+++ b/tests/integration/memory/wiki/test_realtime_to_vault_e2e.py
@@ -18,7 +18,7 @@ from jarvis.core.config import (
MemoryConfig,
WikiMemoryConfig,
)
-from jarvis.core.events import VoiceTurnCompleted
+from jarvis.core.events import VoiceSessionEnded, VoiceTurnCompleted
from jarvis.core.protocols import BrainDelta, BrainRequest
from jarvis.memory.wiki.atomic_writer import AtomicWriter
from jarvis.memory.wiki.consolidator import Consolidator
@@ -35,22 +35,48 @@ from jarvis.memory.wiki.voice_bridge import VoiceFactBridge
class _ReviewBrain:
- """Script both review stages while keeping the production pipeline real."""
+ """Script both review stages while keeping the production pipeline real.
+
+ Responses are routed by REQUEST KIND, not by call order: per-turn
+ extraction is deferred to the session-end boundary (AP-9, 2026-07-21),
+ where the completeness sweep runs concurrently with the judge rounds
+ that freshly journaled candidates trigger — a strict call-order script
+ would race those two. Sweeps re-read already-reviewed turns and answer
+ with an empty candidate array.
+ """
name = "review-brain"
context_window = 100_000
supports_tools = False
supports_vision = False
- def __init__(self, responses: list[str]) -> None:
- self._responses = list(responses)
+ def __init__(self, extractions: list[str], judgements: list[str]) -> None:
+ self._extractions = list(extractions)
+ self._judgements = list(judgements)
self.calls = 0
self.requests: list[BrainRequest] = []
+ self.judge_requests: list[BrainRequest] = []
async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:
self.calls += 1
self.requests.append(request)
- yield BrainDelta(content=self._responses.pop(0))
+ text = "\n".join(
+ (
+ str(getattr(request, "system", "") or ""),
+ *(
+ str(getattr(message, "content", "") or "")
+ for message in request.messages
+ ),
+ )
+ )
+ if "completeness sweep" in text:
+ payload = "[]"
+ elif "Evidence user turn [" in text:
+ self.judge_requests.append(request)
+ payload = self._judgements.pop(0)
+ else:
+ payload = self._extractions.pop(0)
+ yield BrainDelta(content=payload)
yield BrainDelta(finish_reason="stop")
def estimate_cost(self, request: BrainRequest) -> float: # pragma: no cover
@@ -113,9 +139,10 @@ def _turn(
provider: str,
text: str,
assistant_text: str = "Thanks for telling me.",
+ session_id: str = "realtime-session",
) -> VoiceTurnCompleted:
return VoiceTurnCompleted(
- session_id="realtime-session",
+ session_id=session_id,
turn_id=turn_id,
user_text=text,
jarvis_text=assistant_text,
@@ -181,7 +208,7 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
"Ruben needs to use the bathroom right now.",
"Ruben owns an aircraft.",
]
- responses = [
+ extractions = [
json.dumps(
[
{
@@ -195,85 +222,87 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
json.dumps(
[
{
- "candidate_id": 1,
- "decision": "add",
- "target": "entities/lena.md",
- "new_body": _entity_page("lena", facts[0]),
- "reason": "new durable person fact",
+ "fact": facts[1],
+ "kind": "person",
+ "subjects": ["noah"],
+ "evidence_turn_id": "gemini-turn",
}
]
),
json.dumps(
[
{
- "fact": facts[1],
- "kind": "person",
- "subjects": ["noah"],
- "evidence_turn_id": "gemini-turn",
+ "fact": facts[2],
+ "kind": "asset",
+ "subjects": ["aurora"],
+ "evidence_turn_id": "short-asset-turn",
}
]
),
+ # Stage 1 may over-capture; Stage 2 remains the binding slop filter.
json.dumps(
[
{
- "candidate_id": 2,
- "decision": "add",
- "target": "entities/noah.md",
- "new_body": _entity_page("noah", facts[1]),
- "reason": "new durable person fact",
+ "fact": facts[3],
+ "kind": "other",
+ "subjects": ["ruben"],
+ "evidence_turn_id": "transient-turn",
}
]
),
+ # Hostile Stage 1 copies an assistant guess while citing the valid user
+ # turn. Stage 2 sees the user-only evidence and rejects the claim.
json.dumps(
[
{
- "fact": facts[2],
+ "fact": facts[4],
"kind": "asset",
- "subjects": ["aurora"],
- "evidence_turn_id": "short-asset-turn",
+ "subjects": ["ruben", "aircraft"],
+ "evidence_turn_id": "assistant-guess-turn",
}
]
),
+ ]
+ judgements = [
json.dumps(
[
{
- "candidate_id": 3,
+ "candidate_id": 1,
"decision": "add",
- "target": "entities/aurora.md",
- "new_body": _asset_page("aurora", facts[2], "ruben"),
- "reason": "durable owned asset and relationship",
+ "target": "entities/lena.md",
+ "new_body": _entity_page("lena", facts[0]),
+ "reason": "new durable person fact",
}
]
),
- # Stage 1 may over-capture; Stage 2 remains the binding slop filter.
json.dumps(
[
{
- "fact": facts[3],
- "kind": "other",
- "subjects": ["ruben"],
- "evidence_turn_id": "transient-turn",
+ "candidate_id": 2,
+ "decision": "add",
+ "target": "entities/noah.md",
+ "new_body": _entity_page("noah", facts[1]),
+ "reason": "new durable person fact",
}
]
),
json.dumps(
[
{
- "candidate_id": 4,
- "decision": "noop",
- "reason": "transient bodily need has no durable value",
+ "candidate_id": 3,
+ "decision": "add",
+ "target": "entities/aurora.md",
+ "new_body": _asset_page("aurora", facts[2], "ruben"),
+ "reason": "durable owned asset and relationship",
}
]
),
- # Hostile Stage 1 copies an assistant guess while citing the valid user
- # turn. Stage 2 sees the user-only evidence and rejects the claim.
json.dumps(
[
{
- "fact": facts[4],
- "kind": "asset",
- "subjects": ["ruben", "aircraft"],
- "evidence_turn_id": "assistant-guess-turn",
+ "candidate_id": 4,
+ "decision": "noop",
+ "reason": "transient bodily need has no durable value",
}
]
),
@@ -287,7 +316,7 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
]
),
]
- brain = _ReviewBrain(responses)
+ brain = _ReviewBrain(extractions, judgements)
registry = _Registry(brain)
repository = MarkdownPageRepository()
vault = VaultIndex(repo=repository)
@@ -334,48 +363,64 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
)
bridge.start()
- try:
+ async def _speak_and_hang_up(turn: VoiceTurnCompleted) -> None:
+ """One short call per fact: extraction is deferred to session end
+ (AP-9, 2026-07-21), so the turn only reaches the extractor once its
+ session closes."""
+ await bus.publish(turn)
await bus.publish(
+ VoiceSessionEnded(
+ session_id=turn.session_id, hangup_reason="hotkey"
+ )
+ )
+
+ try:
+ await _speak_and_hang_up(
_turn(
turn_id="openai-turn",
provider="openai-realtime",
text="My friend Lena moved to Hamburg last month and lives there now.",
+ session_id="call-1",
)
)
await _wait_for_page(vault_root / "entities" / "lena.md")
- await bus.publish(
+ await _speak_and_hang_up(
_turn(
turn_id="gemini-turn",
provider="gemini-live",
text="My colleague Noah works at the city library during the week.",
+ session_id="call-2",
)
)
await _wait_for_page(vault_root / "entities" / "noah.md")
- await bus.publish(
+ await _speak_and_hang_up(
_turn(
turn_id="short-asset-turn",
provider="openai-realtime",
text="I own a yacht named Aurora.",
+ session_id="call-3",
)
)
await _wait_for_page(vault_root / "entities" / "aurora.md")
- await bus.publish(
+ await _speak_and_hang_up(
_turn(
turn_id="transient-turn",
provider="gemini-live",
text="I need to use the bathroom right now.",
+ session_id="call-4",
)
)
- await _wait_for_idle(brain, journal, calls=8)
- await bus.publish(
+ await _wait_for_idle(brain, journal, calls=12)
+ await _speak_and_hang_up(
_turn(
turn_id="assistant-guess-turn",
provider="openai-realtime",
text="What do you think I own?",
assistant_text="Perhaps you own an aircraft.",
+ session_id="call-5",
)
)
- await _wait_for_idle(brain, journal, calls=10)
+ await _wait_for_idle(brain, journal, calls=15)
finally:
bridge.stop()
journal.close()
@@ -400,10 +445,11 @@ async def test_consecutive_realtime_reviews_write_to_selected_vault(
"aircraft" not in path.read_text(encoding="utf-8").lower()
for path in vault_root.rglob("*.md")
)
- final_judge_prompt = brain.requests[-1].messages[0].content
+ final_judge_prompt = brain.judge_requests[-1].messages[0].content
assert "user_evidence_excerpt=" in final_judge_prompt
assert "Evidence user turn [assistant-guess-turn]" in final_judge_prompt
assert "What do you think I own?" in final_judge_prompt
assert "Perhaps you own an aircraft." not in final_judge_prompt
- assert brain.calls == 10
+ # 5 deferred turn extractions + 5 judge rounds + 5 session sweeps.
+ assert brain.calls == 15
assert journal.backlog_count() == 0
diff --git a/tests/unit/memory/wiki/test_voice_bridge_realtime.py b/tests/unit/memory/wiki/test_voice_bridge_realtime.py
index d3b969a663..0851107f5a 100644
--- a/tests/unit/memory/wiki/test_voice_bridge_realtime.py
+++ b/tests/unit/memory/wiki/test_voice_bridge_realtime.py
@@ -17,6 +17,12 @@ the bridge's realtime ingest contract:
5. Empty user transcript -> no ingest; empty reply does NOT block the
aggressive path (the fact lives in the user text).
6. Aggressive ingests stay rate-limited across realtime turns.
+7. NOTHING extracts while the call is live (AP-9, 2026-07-21): per-turn
+ extraction jobs are deferred and run sequentially at session end,
+ before the completeness sweep — an in-call extraction is an LLM round
+ (plus 429 retries and Codex CLI spawns) on the loop that paces the
+ call's audio, and its journaled candidates trigger in-call
+ consolidator judge rounds on top.
"""
from __future__ import annotations
@@ -164,6 +170,22 @@ async def _drain(journal: CandidateJournal, *, timeout_s: float = 2.0) -> None:
await asyncio.sleep(0.02)
+async def _end_session(bus: EventBus, session_id: str = "rt-session") -> None:
+ """Close the live call — extraction is deferred until this boundary."""
+ await bus.publish(
+ VoiceSessionEnded(session_id=session_id, hangup_reason="hotkey")
+ )
+
+
+def _turn_rows(journal: CandidateJournal) -> list[Any]:
+ """Journal rows from per-turn extraction (the sweep rows filtered out)."""
+ return [
+ row
+ for row in journal.pending()
+ if not row.source_label.startswith("realtime-session-sweep")
+ ]
+
+
async def _wait_for_calls(brain: FakeBrain, count: int, *, timeout_s: float = 2.0) -> None:
deadline = time.monotonic() + timeout_s
while brain.call_count < count and time.monotonic() < deadline: # noqa: ASYNC110
@@ -172,9 +194,15 @@ async def _wait_for_calls(brain: FakeBrain, count: int, *, timeout_s: float = 2.
@pytest.mark.asyncio
async def test_realtime_turn_feeds_journal_via_aggressive_path(tmp_path: Path) -> None:
- bus, journal, curator, bridge, _brain = _stack(tmp_path)
+ bus, journal, curator, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay, will do!"))
+ # AP-9: while the call is live, NO extraction round may run — the
+ # job is deferred, not fired.
+ await asyncio.sleep(0.2)
+ assert brain.call_count == 0
+ assert journal.backlog_count() == 0
+ await _end_session(bus)
await _drain(journal)
finally:
bridge.stop()
@@ -191,6 +219,7 @@ async def test_realtime_ack_reply_uses_ack_path(tmp_path: Path) -> None:
bus, journal, _curator, bridge, _brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(SHORT_FACT, "Noted."))
+ await _end_session(bus)
await _drain(journal)
finally:
bridge.stop()
@@ -219,16 +248,20 @@ async def test_same_realtime_turn_delivered_twice_journaled_once(tmp_path: Path)
bus, journal, _curator, bridge, brain = _stack(tmp_path)
try:
# Ack path both times — the ack path has no rate limit, so the
- # second delivery is stopped by the turn-hash gate alone.
+ # second delivery is stopped by the turn-hash gate alone (recorded
+ # at defer time, before any extraction ran).
await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
- await _drain(journal)
await bus.publish(_realtime_turn(FACT_SENTENCE, "Noted."))
- await asyncio.sleep(0.2)
+ await _end_session(bus)
+ await _wait_for_calls(brain, 2) # one turn extraction + the sweep
+ await asyncio.sleep(0.1)
finally:
bridge.stop()
- assert journal.backlog_count() == 1, "duplicate realtime turn must be deduped by hash"
- assert brain.call_count == 1
+ assert len(_turn_rows(journal)) == 1, (
+ "duplicate realtime turn must be deduped by hash"
+ )
+ assert brain.call_count == 2
@pytest.mark.asyncio
@@ -251,6 +284,7 @@ async def test_empty_reply_does_not_block_aggressive_path(tmp_path: Path) -> Non
bus, journal, _curator, bridge, _brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, ""))
+ await _end_session(bus)
await _drain(journal)
finally:
bridge.stop()
@@ -269,7 +303,6 @@ async def test_aggressive_path_is_rate_limited_across_realtime_turns(tmp_path: P
)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay!"))
- await _drain(journal)
await bus.publish(
_realtime_turn(
"My favourite restaurant is the little place at the harbour.",
@@ -277,12 +310,16 @@ async def test_aggressive_path_is_rate_limited_across_realtime_turns(tmp_path: P
turn_id="rt-turn-2",
)
)
- await asyncio.sleep(0.2)
+ await _end_session(bus)
+ await _wait_for_calls(brain, 2) # one turn extraction + the sweep
+ await asyncio.sleep(0.1)
finally:
bridge.stop()
- assert journal.backlog_count() == 1, "second aggressive ingest within 60s must be skipped"
- assert brain.call_count == 1
+ assert len(_turn_rows(journal)) == 1, (
+ "second aggressive ingest within 60s must be skipped"
+ )
+ assert brain.call_count == 2
@pytest.mark.asyncio
@@ -291,7 +328,6 @@ async def test_default_reviews_consecutive_realtime_turns(tmp_path: Path) -> Non
bus, journal, _curator, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay!"))
- await _drain(journal)
await bus.publish(
_realtime_turn(
"My favourite restaurant is the little place at the harbour.",
@@ -299,14 +335,14 @@ async def test_default_reviews_consecutive_realtime_turns(tmp_path: Path) -> Non
turn_id="rt-turn-2",
)
)
- deadline = time.monotonic() + 2.0
- while journal.backlog_count() < 2 and time.monotonic() < deadline: # noqa: ASYNC110
- await asyncio.sleep(0.02)
+ await _end_session(bus)
+ await _wait_for_calls(brain, 3) # two turn extractions + the sweep
+ await asyncio.sleep(0.1)
finally:
bridge.stop()
- assert journal.backlog_count() == 2
- assert brain.call_count == 2
+ assert len(_turn_rows(journal)) == 2
+ assert brain.call_count == 3
@pytest.mark.asyncio
@@ -314,12 +350,14 @@ async def test_short_yacht_ownership_reaches_extractor_without_ack(tmp_path: Pat
bus, journal, _curator, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn("I own a yacht.", "That sounds exciting."))
- await _wait_for_calls(brain, 1)
+ await _end_session(bus)
+ await _wait_for_calls(brain, 2) # one turn extraction + the sweep
+ await asyncio.sleep(0.1)
finally:
bridge.stop()
- assert brain.call_count == 1
- assert journal.capture_summary()["candidates"] == 1
+ assert brain.call_count == 2
+ assert len(_turn_rows(journal)) == 1
@pytest.mark.asyncio
@@ -328,12 +366,14 @@ async def test_same_text_in_different_turns_is_reviewed_twice(tmp_path: Path) ->
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-b"))
- await _wait_for_calls(brain, 2)
+ await _end_session(bus)
+ await _wait_for_calls(brain, 3) # two turn extractions + the sweep
+ await asyncio.sleep(0.1)
finally:
bridge.stop()
- assert brain.call_count == 2
- assert journal.backlog_count() == 2
+ assert brain.call_count == 3
+ assert len(_turn_rows(journal)) == 2
@pytest.mark.asyncio
@@ -347,7 +387,6 @@ async def test_second_turn_receives_bounded_same_session_context(tmp_path: Path)
turn_id="turn-a",
)
)
- await _wait_for_calls(brain, 1)
await bus.publish(
_realtime_turn(
"It is currently moored in Kiel.",
@@ -355,6 +394,7 @@ async def test_second_turn_receives_bounded_same_session_context(tmp_path: Path)
turn_id="turn-b",
)
)
+ await _end_session(bus)
await _wait_for_calls(brain, 2)
finally:
bridge.stop()
@@ -371,7 +411,6 @@ async def test_session_end_runs_one_full_realtime_sweep(tmp_path: Path) -> None:
bus, journal, _curator, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
- await _wait_for_calls(brain, 1)
await bus.publish(
VoiceSessionEnded(session_id="rt-session", hangup_reason="hotkey")
)
@@ -397,7 +436,6 @@ async def test_duplicate_session_end_sweeps_only_once(tmp_path: Path) -> None:
bus, journal, _curator, bridge, brain = _stack(tmp_path)
try:
await bus.publish(_realtime_turn(FACT_SENTENCE, "Okay.", turn_id="turn-a"))
- await _wait_for_calls(brain, 1)
await bus.publish(
VoiceSessionEnded(session_id="rt-session", hangup_reason="hotkey")
)