Files
roboco/tests/unit/gateway/test_choreographer_briefing.py
T
93739a9dca fix(notifications): stop tick-wide row locks + poisoned-session swallows behind the PendingRollbackError 500s (#743)
* fix(notifications): release re-escalation row locks per row; stop swallowing DB errors in notify_get

The re-escalation sweep ran one tick-wide transaction, so each CAS
claim's row lock was held across every remaining delivery until the
single commit — a concurrent mark-read UPDATE on a claimed row starved
into the 60s lock_timeout. The sweep now commits per row (claim commit
releases the lock before delivery and makes the burned slot durable),
re-fetches each row by snapshotted id so one row's rollback can't
expire the rest of the tick, and savepoints each recipient's delivery.

notify_get's bare except swallowed the resulting LockNotAvailableError
into a false "notification not found" and returned a poisoned session
to the commit-at-send middleware, which blew up with
PendingRollbackError; it now catches only the two domain outcomes.

defer_after_commit's listeners fire on SAVEPOINT release too, which
would have drained deferred telegram/bus work before real durability —
they now skip savepoint boundaries via get_nested_transaction() (the
root get_transaction() is non-None inside the listener even at a real
commit). acknowledge_for_recipient's Redis dedup-clear moved before the
flush so the row lock never spans a Redis round-trip. The five
best-effort CEO-notify swallows that persist notification rows are
savepointed.

* fix(services): contain swallowed best-effort DB write failures instead of poisoning the session

Sweep of the same class as the notify_get incident: broad
except-Exception handlers that swallow a failure whose try-body writes
through the shared session leave the session rollback-pending, and the
verb/request then dies later with PendingRollbackError at
commit-at-send. Confirmed-dangerous sites now run the write inside a
savepoint (safe since defer_after_commit skips savepoint boundaries):
ceo_approve's verified-stamp, completion/pitch/postmortem-style CEO
notifies, _inherit_upstream_base, _link_commit_to_task (covers every
commit route), board-program LEARN records, the QA/PR-gate/PM-merge
verified-stamps, and the documenter->PM handoff.
_ack_pending_wake_notifications gets the same treatment so a wake-ack
failure can't fail the A2A read. telegram_inbound's per-update loop and
intake confirm roll back explicitly instead (their success paths commit
mid-flow, so a savepoint doesn't fit).

A swallowed savepoint rollback fully expires any ORM object mutated
inside the block, and the next attribute read raises MissingGreenlet —
strictly worse than the original bug. The two paths that keep using the
object after the swallow (doc handoff's envelope build, base
inheritance's claim continuation) refresh it in the except path;
regression tests run against a real session and were verified to fail
with the refresh reverted.

* test: shape mocked session.execute results so sync accessors stop leaking unawaited coroutines

An AsyncMock's auto-created children are themselves AsyncMock, so
production code that correctly awaits session.execute() and then calls
sync accessors (.scalars().all(), .scalar_one_or_none()) on the result
was silently collecting unawaited coroutines in 22 test files — 80
RuntimeWarnings per unit run, and in test_flow_soup_guard one mock
raised a real TypeError that a coincidentally-matching invalid_state
envelope masked. Each affected fixture now returns a plain MagicMock
shaped like a real Result. Zero AsyncMock warnings remain.

* docs: document per-row sweep commits and the savepoint/refresh containment pattern

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-30 16:35:42 +02:00

127 lines
5.6 KiB
Python

"""``institutional_memory_status`` sentinel reaches the briefing envelope.
The ``context_briefing["institutional_memory"]`` block carries a ``status``
field distinguishing the five underlying states so an agent can tell
"searched, nothing" (below_floor / empty) from "search broke" (error) from
"subsystem off" (disabled) from "lessons injected" (ok). Additive only —
lessons is empty unless status is ``ok``.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.services.gateway.choreographer import Choreographer
_FLOOR = 0.6
def _choreographer(
*,
similar_memory_out: dict[str, object] | Exception,
) -> tuple[Choreographer, AsyncMock]:
repo = AsyncMock()
repo.list_unread_a2a.return_value = []
repo.list_unread_mentions.return_value = []
repo.list_pending_notifications.return_value = []
repo.task_metadata_gaps.return_value = []
repo.recent_team_activity.return_value = []
repo.blockers_in_lane.return_value = []
repo.company_goals.return_value = None
repo.journal_highlights_for_task.return_value = []
if isinstance(similar_memory_out, Exception):
repo.similar_memory = AsyncMock(side_effect=similar_memory_out)
else:
repo.similar_memory = AsyncMock(return_value=similar_memory_out)
task_svc = AsyncMock()
task_svc.agent_for.return_value = MagicMock(role="developer")
# Findings-ledger reads (ReviewFindingsRepository.list_for_task) go
# through session.execute — an unconfigured AsyncMock's awaited result
# is itself an AsyncMock, so a plain sync `.scalars()` call on it leaks
# an unawaited coroutine. Empty scalars result (no findings).
task_svc.session.execute = AsyncMock(
return_value=MagicMock(
scalars=MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
)
)
choreo = object.__new__(Choreographer)
choreo._deps = MagicMock(evidence_repo=repo, task=task_svc)
return choreo, repo
def _task() -> MagicMock:
return MagicMock(
title="Add retry backoff",
task_type=MagicMock(value="code"),
)
class TestInstitutionalMemoryStatus:
@pytest.mark.asyncio
async def test_disabled_when_subsystem_off(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", False)
choreo, _ = _choreographer(similar_memory_out={"items": [], "status": "ok"})
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task(), full=True)
assert briefing["institutional_memory"]["status"] == "disabled"
assert briefing["institutional_memory"]["lessons"] == []
@pytest.mark.asyncio
async def test_error_when_search_raises(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", True)
# similar_memory itself swallows RAG errors and returns status=error;
# simulate that contract (the choreographer trusts the repo's status).
choreo, _ = _choreographer(similar_memory_out={"items": [], "status": "error"})
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task(), full=True)
assert briefing["institutional_memory"]["status"] == "error"
assert briefing["institutional_memory"]["lessons"] == []
@pytest.mark.asyncio
async def test_empty_when_search_yields_nothing(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", True)
choreo, _ = _choreographer(similar_memory_out={"items": [], "status": "empty"})
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task(), full=True)
assert briefing["institutional_memory"]["status"] == "empty"
assert briefing["institutional_memory"]["lessons"] == []
@pytest.mark.asyncio
async def test_below_floor_when_all_under_floor(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", True)
choreo, _ = _choreographer(
similar_memory_out={"items": [], "status": "below_floor"}
)
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task(), full=True)
assert briefing["institutional_memory"]["status"] == "below_floor"
assert briefing["institutional_memory"]["lessons"] == []
@pytest.mark.asyncio
async def test_ok_injects_lessons(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", True)
lesson = {"kind": "learning", "summary": "s", "source": "src", "score": 0.9}
choreo, _ = _choreographer(
similar_memory_out={"items": [lesson], "status": "ok"}
)
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task(), full=True)
assert briefing["institutional_memory"]["status"] == "ok"
assert briefing["institutional_memory"]["lessons"] == [lesson]
@pytest.mark.asyncio
async def test_slim_briefing_omits_block(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Slim (non-full) briefings don't run the heavy section, so the block
is absent — preserves the existing slim/full split."""
monkeypatch.setattr("roboco.config.settings.org_memory_enabled", True)
choreo, _ = _choreographer(similar_memory_out={"items": [], "status": "ok"})
briefing = await choreo._briefing_for(uuid4(), uuid4(), task=_task())
assert "institutional_memory" not in briefing