Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/reference/agent-wait-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,41 @@ loop-forever semantic:
| 2 (transient) | Back off (≤ 2 s test mode, exponential in production) and continue |
| 3 (permanent) | Exit 1 so the agent fails fast |

### "New events only" default (issue #1925)

A cursor-less `wait` / `wait-loop` call starts at the **stream tip** —
it only matches events added **after** the call begins. Events that
already exist in the message stream (including the agent's own
just-sent `CONSENSUS_CONFIRMED`) are skipped.

Rationale: before #1925, a cursor-less wait scanned from the beginning
of the stream, so once the stream contained any matching event,
every subsequent `wait-loop` invocation returned instantly with the
same already-seen message instead of blocking for the next one. That
forced agents to either spin in foreground or manually construct a
`--since <last_seen_id>` on each call.

**Race: send → wait.** There is a small window between the agent
sending its own CONSENSUS_CONFIRMED and entering `wait-loop` during
which a peer event could arrive — with the default new-events-only
behaviour, that event would not unblock the wait. In practice this
window is milliseconds and the peer event case is rare at that
instant, but if you need zero-drop semantics capture an anchor
message ID before your send and pass it explicitly:

```bash
# zero-drop pattern — anchor BEFORE the send, wait from the anchor
anchor=$(egg-orch message poll --limit 1 --json | jq -r '.messages[0].id // empty')
egg-orch consensus confirmed
egg-orch message wait-loop \
--for CONSENSUS_CONFIRMED --for CONSENSUS_RE_REVIEW --for OVERSEER_ALERT \
${anchor:+--since "$anchor"}
```

With `--since`, the wait starts at the named ID (exclusive) and
includes any event — your own send, a peer's, or one that arrived
in the window — that arrived after the anchor.

## 4. `HEARTBEAT` Message Type

`HEARTBEAT` is a typed message agents emit on state transitions so the
Expand Down
19 changes: 18 additions & 1 deletion orchestrator/message_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ def get_messages(
wait: int = 0,
wait_for_types: Sequence[str] | None = None,
from_role: str | None = None,
from_tip: bool = False,
) -> list[Message]:
"""Get messages for a pipeline, optionally filtered.

Expand All @@ -210,17 +211,31 @@ def get_messages(
``from_role`` equals this value. Applied inside the blocking
loop so a message from the wrong sender does NOT unblock the
wait (prevents spinning — issue #1897 reviewer_code non-blocker).
from_tip: If True AND ``since_id`` is not set AND ``wait > 0``, snap
the starting cursor to ``len(messages)`` at call entry so only
messages added *after* this call starts can unblock the wait.
Required by the ``/messages/wait`` endpoint's event-driven
contract (issue #1925).

Returns:
List of matching messages, oldest first. Empty list on timeout.
"""
# Snapshot the tip index at call entry under the lock below so
# from_tip semantics are race-free against concurrent add_message
# calls.
tip_index: int | None = None
use_tip = from_tip and not since_id and wait > 0

def _filter(all_msgs: list[Message]) -> list[Message]:
msgs = list(all_msgs)
# from_tip takes precedence over since_id (since_id is unset
# when we enter the tip branch; guard above).
if use_tip and tip_index is not None:
msgs = msgs[tip_index:]
# Filter by since_id. If the cursor is unknown, degrade to
# "return all" instead of returning empty, so a stale cursor
# doesn't silently hide new messages from a polling agent.
if since_id:
elif since_id:
found_idx = next((i for i, m in enumerate(msgs) if m.id == since_id), None)
if found_idx is not None:
msgs = msgs[found_idx + 1 :]
Expand All @@ -246,6 +261,8 @@ def _filter(all_msgs: list[Message]) -> list[Message]:

# Fast path: check once under the lock.
with self._lock:
if use_tip:
tip_index = len(self._messages.get(pipeline_id, []))
matches = _filter(self._messages.get(pipeline_id, []))
if wait_for_types:
typed = [m for m in matches if m.message_type in set(wait_for_types)]
Expand Down
17 changes: 16 additions & 1 deletion orchestrator/redis_message_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def get_messages(
wait: int = 0,
wait_for_types: Sequence[str] | None = None,
from_role: str | None = None,
from_tip: bool = False,
) -> list[Message]:
"""Get messages from the Redis Stream.

Expand All @@ -188,12 +189,26 @@ def get_messages(
``from_role=...`` unconditionally, so a Redis backend
without this parameter raised ``TypeError`` in production
(reviewer_code blocker 1 on #1897 proposal v4).
from_tip: If True AND ``since_id`` is not set, start the read at
the stream tip (Redis ``$``) so only entries added *after*
the call starts can unblock the wait. Required by the
``/messages/wait`` endpoint's "event-driven" contract
(issue #1925) — without it, a repeated wait-loop call
returns the same already-seen event on every invocation.
"""
key = _stream_key(pipeline_id)

# Resolve since_id (message UUID) to Redis stream ID
start_id = "0-0"
if since_id:
if from_tip and not since_id and wait > 0:
# Redis XREAD treats ``$`` as "only entries with an ID greater
# than the greatest ID in the stream at call time" — i.e., a
# true event wait. Only safe on the blocking path (XREAD);
# XRANGE does not accept ``$``. Inner wait_for_types loop
# replaces ``$`` with a concrete ``last_sid`` after the first
# read, so subsequent cursor advancement uses real IDs.
start_id = "$"
elif since_id:
stream_id = self._resolve_stream_id(pipeline_id, since_id)
if stream_id:
start_id = stream_id
Expand Down
9 changes: 9 additions & 0 deletions orchestrator/routes/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,14 @@ def wait_messages(pipeline_id: str) -> tuple[Response, int]:
# from_role is applied INSIDE the blocking read (message_store
# level) so a message with a matching TYPE but the wrong
# sender does not unblock us — prevents client-side spin.
#
# from_tip is set when no since_id is supplied so only events
# arriving AFTER this call can unblock the wait. Without it,
# repeated wait-loop invocations all re-match the same
# already-seen event because the store starts scanning from
# "0-0" (issue #1925). Callers that want cursor-passing
# semantics pass ``since_id`` explicitly, which disables
# from_tip below.
messages = message_store.get_messages(
pipeline_id,
role=role,
Expand All @@ -411,6 +419,7 @@ def wait_messages(pipeline_id: str) -> tuple[Response, int]:
wait=timeout,
wait_for_types=wait_for_types,
from_role=from_role,
from_tip=since_id is None,
)
finally:
_track_long_poll_end()
Expand Down
26 changes: 19 additions & 7 deletions orchestrator/routes/pipelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -6292,10 +6292,14 @@ def _build_brc_preamble(
"--timeout 60` until the orchestrator stops you. "
"**Don't** wrap this in a shell `for i in 1..N` loop; "
"**don't** prefix it with `sleep N`. The wait-loop "
"blocks server-side and returns the moment a BRC "
"event arrives — exit code 0 means act on it, 1 means "
"the wrapper exhausted retries (surface it). See "
"docs/reference/agent-wait-patterns.md.",
"blocks server-side and returns the moment a NEW BRC "
"event arrives — events that predate the call (including "
"your own just-sent CONSENSUS_CONFIRMED) are skipped "
"(issue #1925). Exit code 0 means act on the returned "
"message, 1 means the wrapper exhausted retries (surface "
"it). If you need zero-drop semantics across a send→wait "
"boundary, capture your send's ID and pass `--since <id>`. "
"See docs/reference/agent-wait-patterns.md.",
"7. **HANDLE RE-REVIEW**: If you receive a `CONSENSUS_RE_REVIEW` message "
"while staying alive, you MUST act on it — failure to do so will stall "
"the entire pipeline. If you are a reviewer of the re-proposing producer, "
Expand Down Expand Up @@ -6365,7 +6369,11 @@ def _build_brc_preamble(
"orchestrator stops you. **Don't** wrap this in a "
"shell `for i in 1..N` loop; **don't** prefix it with "
"`sleep N`. The wait-loop blocks server-side and "
"returns the moment a BRC event arrives. See "
"returns the moment a NEW BRC event arrives — events "
"that predate the call are skipped (issue #1925). If "
"you need zero-drop semantics across a send→wait "
"boundary, capture the ID of your most recent send and "
"pass `--since <id>`. See "
"docs/reference/agent-wait-patterns.md.",
"8. **HANDLE RE-REVIEW**: If you receive a `CONSENSUS_RE_REVIEW` message "
"while staying alive, you MUST act on it — failure to do so will stall "
Expand Down Expand Up @@ -7437,9 +7445,13 @@ def _build_agent_prompt(
" --timeout 60",
"```",
"`wait-loop` blocks server-side and loops forever until a "
"matching BRC event arrives (exit 0) or a permanent error "
"NEW matching BRC event arrives (exit 0) or a permanent error "
"occurs (exit 1). There is no outer timeout — the wrapper "
"owns the 0/1 contract. See "
"owns the 0/1 contract. Events that predate the call "
"(including your own just-sent CONSENSUS_CONFIRMED) are "
"skipped (issue #1925); if you need zero-drop semantics "
"across a send→wait boundary, capture the ID of your "
"send and pass `--since <id>`. See "
"`docs/reference/agent-wait-patterns.md` for the full "
"exit-code contract and the four anti-patterns to avoid.",
"4. If `wait-loop` returns with a message that affects your work, "
Expand Down
90 changes: 90 additions & 0 deletions orchestrator/tests/test_message_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,3 +404,93 @@ def test_fresh_wait_after_clear_lazily_recreates_cv(self, store: MessageStore) -
assert 0.8 <= elapsed <= 2.0, (
f"Fresh wait after clear took {elapsed:.2f}s; expected ~1s (normal timeout path)"
)


class TestFromTipSemantics:
"""``from_tip=True`` snaps the starting cursor to the current length
so only messages added after the call unblock the wait.

Backs the ``/messages/wait`` endpoint fix for issue #1925: without
from_tip, repeated cursor-less wait-loop invocations re-matched the
same already-seen event and returned instantly instead of blocking.
"""

def test_pre_existing_matching_message_does_not_match(self, store: MessageStore) -> None:
"""A matching message added BEFORE the wait must be ignored."""
store.add_message(_make_message(message_type=MessageType.CONSENSUS_CONFIRMED))

start = time.monotonic()
msgs = store.get_messages(
"test-pipeline",
wait=1,
wait_for_types=[MessageType.CONSENSUS_CONFIRMED],
from_tip=True,
)
elapsed = time.monotonic() - start

assert msgs == []
# Must have actually blocked — ~1s not ~0s.
assert elapsed >= 0.5, (
f"from_tip=True returned in {elapsed:.2f}s; expected to block ~1s "
"because no NEW matching message arrived"
)

def test_post_call_message_unblocks_from_tip_wait(self, store: MessageStore) -> None:
"""A matching message added AFTER the wait begins unblocks it."""
# Seed a pre-existing matching message that from_tip must skip.
store.add_message(_make_message(message_type=MessageType.CONSENSUS_CONFIRMED))

got: list[list[Message]] = []

def _block() -> None:
got.append(
store.get_messages(
"test-pipeline",
wait=5,
wait_for_types=[MessageType.CONSENSUS_CONFIRMED],
from_tip=True,
)
)

t = threading.Thread(target=_block)
t.start()
time.sleep(0.2) # let the thread enter the blocking wait

store.add_message(
_make_message(message_type=MessageType.CONSENSUS_CONFIRMED, from_role="later")
)
t.join(timeout=2)

assert not t.is_alive()
assert len(got) == 1 and len(got[0]) == 1
# Returned the NEW message (from_role='later'), not the pre-seeded one.
assert got[0][0].from_role == "later"

def test_from_tip_ignored_when_wait_zero(self, store: MessageStore) -> None:
"""With ``wait=0`` there's nothing to block on; from_tip is a no-op
(prevents a footgun where from_tip + non-blocking would silently
return empty regardless of stream state)."""
store.add_message(_make_message(message_type=MessageType.CONSENSUS_CONFIRMED))

msgs = store.get_messages(
"test-pipeline",
wait=0,
from_tip=True,
)
# No wait_for_types + wait=0 + from_tip: same as plain non-blocking read.
assert len(msgs) == 1

def test_explicit_since_id_disables_from_tip(self, store: MessageStore) -> None:
"""When both are set, since_id wins and from_tip is ignored."""
anchor = store.add_message(_make_message(message_type=MessageType.PROGRESS))
store.add_message(_make_message(message_type=MessageType.CONSENSUS_CONFIRMED))

msgs = store.get_messages(
"test-pipeline",
wait=1,
wait_for_types=[MessageType.CONSENSUS_CONFIRMED],
since_id=anchor.id,
from_tip=True,
)
assert len(msgs) == 1
assert msgs[0].message_type == MessageType.CONSENSUS_CONFIRMED
Loading
Loading