Files
roboco/tests/unit/gateway/test_flow_soup_guard.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

178 lines
6.0 KiB
Python

"""Anti-soup guard on the flow verbs (reason / notes / issues / title / desc).
Two layers are tested:
- the pure helpers ``_free_text_soup`` (skip empty/None, reject filler, walk
list items) and ``_soup_or_decision_env`` (soup first, then the spec
decision, else None);
- one end-to-end wiring test per emit style — ``i_am_blocked`` (folds soup into
the spec-gate return) — proving a soupy ``reason`` is rejected before any
state transition and a real reason passes through.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.services.gateway.choreographer import Choreographer, ChoreographerDeps
from roboco.services.gateway.choreographer._impl import Choreographer as _Impl
from roboco.services.gateway.envelope import Envelope
# --------------------------------------------------------------------------- #
# _free_text_soup
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("clean", ["a real substantive reason", "rate_limited"])
def test_free_text_soup_passes_substantive(clean: str) -> None:
assert _Impl._free_text_soup((("reason", clean, 8),)) is None
@pytest.mark.parametrize("skip", [None, "", " "])
def test_free_text_soup_skips_empty_and_none(skip: str | None) -> None:
# Empty / None means "not supplied" — presence is gated elsewhere.
assert _Impl._free_text_soup((("notes", skip, 8),)) is None
@pytest.mark.parametrize("soup", ["wip", "asdf", "tbd", "...", "x", "wip wip"])
def test_free_text_soup_rejects_filler(soup: str) -> None:
env = _Impl._free_text_soup((("reason", soup, 3),))
assert env is not None
assert env.error == "invalid_state"
def test_free_text_soup_walks_list_items() -> None:
# The second issue is filler — the list form must catch it.
env = _Impl._free_text_soup(
(("issues", ["a genuine actionable issue", "asdf"], 8),)
)
assert env is not None
assert env.error == "invalid_state"
assert "issues[1]" in (env.message or "")
def test_free_text_soup_clean_list_passes() -> None:
env = _Impl._free_text_soup(
(("issues", ["first real issue", "second real issue"], 8),)
)
assert env is None
# --------------------------------------------------------------------------- #
# _soup_or_decision_env
# --------------------------------------------------------------------------- #
def _allow() -> MagicMock:
return MagicMock(allowed=True)
def _deny() -> MagicMock:
return MagicMock(
allowed=False,
rejection_kind="invalid_state",
message="bad state",
remediate="do X",
)
def test_soup_or_decision_prefers_soup() -> None:
soup = Envelope.invalid_state(message="soup", remediate="fix", context_briefing={})
out = _Impl._soup_or_decision_env(soup, _deny(), {})
assert out is soup # soup wins even when the decision also rejects
def test_soup_or_decision_falls_back_to_decision() -> None:
out = _Impl._soup_or_decision_env(None, _deny(), {})
assert out is not None
assert out.error == "invalid_state"
assert out.message == "bad state"
def test_soup_or_decision_none_when_all_clean() -> None:
assert _Impl._soup_or_decision_env(None, _allow(), {}) is None
# --------------------------------------------------------------------------- #
# Wiring: i_am_blocked rejects a soupy reason before any transition
# --------------------------------------------------------------------------- #
def _make_deps(agent_id: object, task_id: object) -> ChoreographerDeps:
t = MagicMock(
id=task_id,
status="in_progress",
assigned_to=agent_id,
task_type="code",
team="backend",
dependency_ids=[],
acceptance_criteria=[],
)
task_svc = AsyncMock()
task_svc.get.return_value = t
task_svc.agent_for.return_value = MagicMock(
id=agent_id, role="developer", team="backend", slug="be-dev-1"
)
# VerbRunner uses task.session.begin_nested() as a savepoint context
# manager — an unconfigured AsyncMock's `begin_nested()` call returns a
# raw unawaited coroutine, which `async with` cannot use (real failure,
# not just a warning: it was silently turning into a masking
# "verb runner failed" invalid_state envelope instead of exercising the
# real block path below).
task_svc.session.begin_nested = MagicMock(
return_value=MagicMock(
__aenter__=AsyncMock(return_value=None),
__aexit__=AsyncMock(return_value=False),
)
)
evidence_repo = AsyncMock()
for m in (
"list_unread_a2a",
"list_unread_mentions",
"list_pending_notifications",
"task_metadata_gaps",
"recent_team_activity",
"blockers_in_lane",
"journal_highlights_for_task",
):
getattr(evidence_repo, m).return_value = []
return ChoreographerDeps(
task=task_svc,
work_session=AsyncMock(),
git=AsyncMock(),
a2a=AsyncMock(),
journal=AsyncMock(),
audit=AsyncMock(),
evidence_repo=evidence_repo,
)
async def test_i_am_blocked_rejects_soup_reason() -> None:
agent_id, task_id = uuid4(), uuid4()
deps = _make_deps(agent_id, task_id)
c = Choreographer(deps)
env = await c.i_am_blocked(agent_id, task_id, "wip")
assert env.error == "invalid_state"
# The block never happened — no struggle journal, no escalate.
deps.journal.write_struggle.assert_not_awaited()
deps.task.escalate.assert_not_awaited()
async def test_i_am_blocked_accepts_real_reason() -> None:
agent_id, task_id = uuid4(), uuid4()
deps = _make_deps(agent_id, task_id)
c = Choreographer(deps)
env = await c.i_am_blocked(
agent_id, task_id, "Waiting on the upstream auth schema migration."
)
# A substantive reason clears the soup guard (then proceeds to the spec
# gate / block path — which writes the struggle journal).
assert env.error != "invalid_state" or "placeholder" not in (env.message or "")
deps.journal.write_struggle.assert_awaited_once()