diff --git a/docs/reference/agent-wait-patterns.md b/docs/reference/agent-wait-patterns.md index 93800c7f0a..f277235998 100644 --- a/docs/reference/agent-wait-patterns.md +++ b/docs/reference/agent-wait-patterns.md @@ -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 ` 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 diff --git a/orchestrator/message_store.py b/orchestrator/message_store.py index c15dbe5ab8..9ae3b3a88b 100644 --- a/orchestrator/message_store.py +++ b/orchestrator/message_store.py @@ -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. @@ -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 branch: since_id is guaranteed unset here (guard + # above ensures mutual exclusion). + 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 :] @@ -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)] diff --git a/orchestrator/redis_message_store.py b/orchestrator/redis_message_store.py index 0402842c6a..659e7c62b6 100644 --- a/orchestrator/redis_message_store.py +++ b/orchestrator/redis_message_store.py @@ -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. @@ -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 AND ``wait > 0``, + 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 diff --git a/orchestrator/routes/messages.py b/orchestrator/routes/messages.py index eba3ac7522..5b5c329b88 100644 --- a/orchestrator/routes/messages.py +++ b/orchestrator/routes/messages.py @@ -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, @@ -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() diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 5531015b90..1f4fcdcf17 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -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 `. " + "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, " @@ -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 `. 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 " @@ -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 `. 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, " diff --git a/orchestrator/tests/test_message_store.py b/orchestrator/tests/test_message_store.py index de88756b65..68713037fa 100644 --- a/orchestrator/tests/test_message_store.py +++ b/orchestrator/tests/test_message_store.py @@ -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 diff --git a/orchestrator/tests/test_messages.py b/orchestrator/tests/test_messages.py index 47670efe7d..1123f44ccc 100644 --- a/orchestrator/tests/test_messages.py +++ b/orchestrator/tests/test_messages.py @@ -1052,16 +1052,30 @@ def test_wait_missing_for_returns_400(self, client, app): assert "for" in data["message"].lower() def test_wait_returns_matched_message(self, client, app): + """A matching message added *after* the wait starts unblocks it. + + Issue #1925: the wait endpoint now starts from the stream tip, + so pre-existing messages do NOT satisfy a cursor-less wait. This + test uses a background thread to inject the match while the + endpoint is blocking. + """ + import threading + import time as _t + store = MessageStore() - store.add_message( - Message( - pipeline_id="test-pipeline", - from_role="coder", - to_role="all", - message_type=MessageType.CONSENSUS_CONFIRMED, - subject="done", + + def _add_after_delay() -> None: + _t.sleep(0.15) + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject="done", + ) ) - ) + with app.test_request_context(): with ( patch("routes.messages.get_message_store", return_value=store), @@ -1073,10 +1087,15 @@ def test_wait_returns_matched_message(self, client, app): MagicMock(), _make_pipeline_mock(), ) - resp = client.get( - "/api/v1/pipelines/test-pipeline/messages/wait" - "?for=CONSENSUS_CONFIRMED&timeout=2" - ) + t = threading.Thread(target=_add_after_delay) + t.start() + try: + resp = client.get( + "/api/v1/pipelines/test-pipeline/messages/wait" + "?for=CONSENSUS_CONFIRMED&timeout=3" + ) + finally: + t.join(timeout=2) assert resp.status_code == 200 data = json.loads(resp.data) assert data["data"]["count"] == 1 @@ -1085,16 +1104,23 @@ def test_wait_returns_matched_message(self, client, app): def test_wait_repeatable_for_param(self, client, app): """Multiple --for types act as an OR filter.""" + import threading + import time as _t + store = MessageStore() - store.add_message( - Message( - pipeline_id="test-pipeline", - from_role="coder", - to_role="all", - message_type=MessageType.CONSENSUS_RE_REVIEW, - subject="re-review", + + def _add_after_delay() -> None: + _t.sleep(0.15) + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.CONSENSUS_RE_REVIEW, + subject="re-review", + ) ) - ) + with app.test_request_context(): with ( patch("routes.messages.get_message_store", return_value=store), @@ -1106,11 +1132,16 @@ def test_wait_repeatable_for_param(self, client, app): MagicMock(), _make_pipeline_mock(), ) - resp = client.get( - "/api/v1/pipelines/test-pipeline/messages/wait" - "?for=CONSENSUS_CONFIRMED&for=CONSENSUS_RE_REVIEW" - "&timeout=2" - ) + t = threading.Thread(target=_add_after_delay) + t.start() + try: + resp = client.get( + "/api/v1/pipelines/test-pipeline/messages/wait" + "?for=CONSENSUS_CONFIRMED&for=CONSENSUS_RE_REVIEW" + "&timeout=3" + ) + finally: + t.join(timeout=2) assert resp.status_code == 200 data = json.loads(resp.data) assert data["data"]["count"] == 1 @@ -1142,6 +1173,68 @@ def test_wait_times_out_with_empty_result(self, client, app): def test_wait_from_filter(self, client, app): """`from=ROLE` drops messages from other senders.""" + import threading + import time as _t + + store = MessageStore() + + def _add_after_delay() -> None: + _t.sleep(0.15) + # Wrong-sender message first — must NOT unblock the wait. + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="documenter", + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject="docs confirmed", + ) + ) + _t.sleep(0.1) + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject="coder confirmed", + ) + ) + + with app.test_request_context(): + with ( + patch("routes.messages.get_message_store", return_value=store), + patch( + "routes.messages.get_state_store_for_pipeline" + ) as mock_get_store_for_pipeline, + ): + mock_get_store_for_pipeline.return_value = ( + MagicMock(), + _make_pipeline_mock(), + ) + t = threading.Thread(target=_add_after_delay) + t.start() + try: + resp = client.get( + "/api/v1/pipelines/test-pipeline/messages/wait" + "?for=CONSENSUS_CONFIRMED&from=coder&timeout=3" + ) + finally: + t.join(timeout=2) + assert resp.status_code == 200 + data = json.loads(resp.data) + assert data["data"]["count"] == 1 + assert data["data"]["messages"][0]["from_role"] == "coder" + + def test_wait_ignores_pre_existing_messages(self, client, app): + """Issue #1925 regression: a cursor-less wait must NOT return a + matching message that was added before the call started. + + Before the fix, repeated wait-loop invocations re-matched the same + already-seen CONSENSUS_CONFIRMED on every call because the store + scanned from stream tail = 0. After the fix, the wait endpoint + starts from the stream tip, so pre-existing messages are ignored. + """ store = MessageStore() store.add_message( Message( @@ -1149,16 +1242,55 @@ def test_wait_from_filter(self, client, app): from_role="documenter", to_role="all", message_type=MessageType.CONSENSUS_CONFIRMED, - subject="docs confirmed", + subject="already seen — must not match", + ) + ) + with app.test_request_context(): + with ( + patch("routes.messages.get_message_store", return_value=store), + patch( + "routes.messages.get_state_store_for_pipeline" + ) as mock_get_store_for_pipeline, + ): + mock_get_store_for_pipeline.return_value = ( + MagicMock(), + _make_pipeline_mock(), + ) + resp = client.get( + "/api/v1/pipelines/test-pipeline/messages/wait" + "?for=CONSENSUS_CONFIRMED&timeout=1" + ) + assert resp.status_code == 200 + data = json.loads(resp.data) + assert data["data"]["count"] == 0 + assert data["data"]["matched"] is False + + def test_wait_honors_explicit_since_id(self, client, app): + """Passing ``since_id=`` opts out of from_tip behavior and + returns matching messages added after that cursor. + + This is the race-safety pattern callers use when they've already + observed an event and want to wait for the NEXT event after it. + """ + store = MessageStore() + cursor = store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="documenter", + to_role="all", + message_type=MessageType.PROGRESS, + subject="cursor anchor", ) ) + # A matching message added AFTER the cursor but BEFORE the wait + # call — with since_id passed, this must still be returned. store.add_message( Message( pipeline_id="test-pipeline", from_role="coder", to_role="all", message_type=MessageType.CONSENSUS_CONFIRMED, - subject="coder confirmed", + subject="after cursor", ) ) with app.test_request_context(): @@ -1174,12 +1306,12 @@ def test_wait_from_filter(self, client, app): ) resp = client.get( "/api/v1/pipelines/test-pipeline/messages/wait" - "?for=CONSENSUS_CONFIRMED&from=coder&timeout=1" + f"?for=CONSENSUS_CONFIRMED&since_id={cursor.id}&timeout=1" ) assert resp.status_code == 200 data = json.loads(resp.data) assert data["data"]["count"] == 1 - assert data["data"]["messages"][0]["from_role"] == "coder" + assert data["data"]["messages"][0]["subject"] == "after cursor" def test_wait_invalid_pipeline_id_returns_400(self, client, app): with app.test_request_context(): diff --git a/orchestrator/tests/test_redis_message_store.py b/orchestrator/tests/test_redis_message_store.py index 97e2797629..67ea10589f 100644 --- a/orchestrator/tests/test_redis_message_store.py +++ b/orchestrator/tests/test_redis_message_store.py @@ -670,3 +670,92 @@ def test_wait_zero_with_filter_returns_empty(self, store): wait_for_types=[MessageType.CONSENSUS_CONFIRMED], ) assert messages == [] + + +class TestRedisFromTipSemantics: + """``from_tip=True`` uses Redis ``$`` so XREAD only matches entries + added after the call starts. + + Backs the ``/messages/wait`` endpoint fix for issue #1925. + """ + + def test_pre_existing_match_ignored_with_from_tip(self, store): + """A matching pre-existing entry must NOT satisfy a from_tip wait.""" + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject="already seen", + ) + ) + + # fakeredis's XREAD with $ is a no-op on streams with data — it + # returns empty immediately because no "later" entry exists. This + # is the correct behaviour contract even though real Redis would + # actually block for the timeout. + start = time.monotonic() + messages = store.get_messages( + "test-pipeline", + wait=1, + wait_for_types=[MessageType.CONSENSUS_CONFIRMED], + from_tip=True, + ) + elapsed = time.monotonic() - start + assert messages == [] + # Must not take longer than the wait budget. + assert elapsed < 2.0, f"from_tip wait over budget: {elapsed:.2f}s" + + def test_explicit_since_id_disables_from_tip(self, store): + """When both are set, since_id wins — the caller wants the + cursor-passing path, not the stream tip.""" + anchor = store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.PROGRESS, + subject="anchor", + ) + ) + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject="after", + ) + ) + + messages = store.get_messages( + "test-pipeline", + wait=1, + wait_for_types=[MessageType.CONSENSUS_CONFIRMED], + since_id=anchor.id, + from_tip=True, # should be ignored in favor of since_id + ) + assert len(messages) == 1 + assert messages[0].subject == "after" + + def test_from_tip_ignored_when_wait_zero(self, store): + """``wait=0`` + ``from_tip=True`` degrades to non-blocking read + from 0-0 (start_id = 0-0), not ``$`` — XRANGE doesn't accept ``$`` + and we avoid the footgun.""" + store.add_message( + Message( + pipeline_id="test-pipeline", + from_role="coder", + to_role="all", + message_type=MessageType.PROGRESS, + subject="p", + ) + ) + # Should not raise; returns the pre-existing message unfiltered. + messages = store.get_messages( + "test-pipeline", + wait=0, + from_tip=True, + ) + assert len(messages) == 1