autogen icon indicating copy to clipboard operation
autogen copied to clipboard

MessageFilterAgent orders filtered messages by per_source config order, not chronological order

Open ErenAta16 opened this issue 4 months ago • 3 comments

Describe the bug

MessageFilterAgent._apply_filter (python/packages/autogen-agentchat/src/autogen_agentchat/agents/_message_filter_agent.py, lines 154-167) hands the wrapped agent messages ordered by the position of each source in MessageFilterConfig.per_source, not by each message's actual chronological position:

def _apply_filter(self, messages: Sequence[BaseChatMessage]) -> Sequence[BaseChatMessage]:
    result: List[BaseChatMessage] = []

    for source_filter in self._filter.per_source:
        msgs = [m for m in messages if m.source == source_filter.source]

        if source_filter.position == "first" and source_filter.count:
            msgs = msgs[: source_filter.count]
        elif source_filter.position == "last" and source_filter.count:
            msgs = msgs[-source_filter.count :]

        result.extend(msgs)

    return result

result is built by iterating per_source and appending each source's matches in the order the filters happen to be listed, so the emitted sequence's order reflects filter-config order, not message timeline order.

This directly breaks the class's own documented example. The docstring describes a looping graph A → B → A → B → C where B is configured with per_source=[user-first(1), A-last(1), B-last(N)] specifically "to see the user message, last message from A, and its own prior responses (for reflection)". If A has spoken twice by the time B runs again (once before B's own prior turn, once after), the real chronological order is user → A(older) → B(own) → A(newer), but _apply_filter emits [user, A(newer), B(own)], placing A's newer message before B's own reply, even though B's own reply chronologically happened first. The wrapped LLM agent receives a scrambled timeline with no error or warning.

To Reproduce

import asyncio
from typing import Sequence

from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.agents._message_filter_agent import (
    MessageFilterAgent, MessageFilterConfig, PerSourceFilter,
)
from autogen_agentchat.base import Response
from autogen_agentchat.messages import BaseChatMessage, TextMessage
from autogen_core import CancellationToken


class RecordingAgent(BaseChatAgent):
    def __init__(self, name: str):
        super().__init__(name=name, description="records message order")
        self.received_order: list[str] = []

    @property
    def produced_message_types(self):
        return (TextMessage,)

    async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:
        self.received_order = [f"{m.source}:{m.content}" for m in messages]
        return Response(chat_message=TextMessage(content="ack", source=self.name))

    async def on_reset(self, cancellation_token: CancellationToken) -> None:
        pass


async def main():
    # Chronological transcript matching the class's own documented A->B->A->B->C example
    transcript = [
        TextMessage(content="please solve X", source="user"),   # t0
        TextMessage(content="A's first attempt", source="A"),    # t1
        TextMessage(content="B's first review", source="B"),     # t2
        TextMessage(content="A's second attempt", source="A"),   # t3, most recent A
    ]

    inner = RecordingAgent("B_inner")
    filtered_agent = MessageFilterAgent(
        name="B",
        wrapped_agent=inner,
        filter=MessageFilterConfig(per_source=[
            PerSourceFilter(source="user", position="first", count=1),
            PerSourceFilter(source="A", position="last", count=1),
            PerSourceFilter(source="B", position="last", count=10),
        ]),
    )

    await filtered_agent.on_messages(transcript, CancellationToken())
    print("received order:", inner.received_order)

asyncio.run(main())

Actual output:

received order: ["user:please solve X", "A:A's second attempt", "B:B's first review"]

Expected (chronologically ordered):

["user:please solve X", "B:B's first review", "A:A's second attempt"]

B's own prior response ("B's first review", which happened at t2) is placed after A's most recent message ("A's second attempt", from t3), even though it happened earlier. This inverts the actual conversation timeline as seen by the wrapped agent.

Expected Behavior

_apply_filter's output should preserve the original chronological order of messages, regardless of the order sources are listed in per_source.

Which package was this bug in?

Python AgentChat

Model used

N/A — reproducible with pure message-list logic, no LLM call needed.

Additional context

There's no dedicated test file for MessageFilterAgent, which likely explains why this went unnoticed; ordering isn't asserted anywhere.

Suggested fix direction: collect matches with their original indices, then sort the final result by original index before returning (or do a single pass over messages in original order, keeping each message only if it falls inside its source's requested first-N/last-N window), so the emitted subsequence always preserves the original chronological order.

ErenAta16 avatar Jul 17 '26 20:07 ErenAta16

Great catch. Grouping by per_source and concatenating directly causes the message timeline to reflect filter declaration order rather than actual conversational turn order, which completely breaks multi-agent reflection and turn-taking semantics.

Recommended Fix

Rather than appending subsets directly, we can collect the allowed indices per source into a set and perform a single-pass retention sweep over the original input list. This preserves the input sequence's strict chronological order in O(N):

def _apply_filter(self, messages: Sequence[BaseChatMessage]) -> Sequence[BaseChatMessage]:
    # 1. Map each source to its matching message indices in the original sequence
    source_indices: dict[str, list[int]] = {}
    for idx, msg in enumerate(messages):
        source_indices.setdefault(msg.source, []).append(idx)

    # 2. Identify which indices are selected according to per_source criteria
    selected_indices: set[int] = set()
    for source_filter in self._filter.per_source:
        matching = source_indices.get(source_filter.source, [])
        if not matching:
            continue

        if source_filter.position == "first" and source_filter.count:
            selected_indices.update(matching[: source_filter.count])
        elif source_filter.position == "last" and source_filter.count:
            selected_indices.update(matching[-source_filter.count :])
        else:
            selected_indices.update(matching)

    # 3. Emit messages preserving strict chronological order
    return [m for idx, m in enumerate(messages) if idx in selected_indices]

This guarantees:

  1. Every retained message stays in its exact original chronological slot.
  2. The A -> B -> A -> B -> C reflection loop receives correct turn causality.
  3. Zero overhead or mutation on the messages themselves.

amasen02 avatar Sep 04 '26 12:09 amasen02

@amasen02 the index-set approach is right and I ran it against the current implementation rather than reading both. On A B A B C with [B last 2, A first 2]:

current   ['b1', 'b2', 'a1', 'a2']     declaration order
proposed  ['a1', 'b1', 'a2', 'b2']     chronological

So it does what the issue asks. Two things came out of running it that are worth settling before anyone opens a PR, because neither is in the description.

Your version de-duplicates, and the current one does not. Two filters naming the same source with overlapping ranges:

[A first 2, A last 2]
current   ['a1', 'a2', 'a1', 'a2']
proposed  ['a1', 'a2']

A set union cannot repeat an index, so the same message can no longer appear twice. I think that is the right behaviour and not an accident of the data structure, since a filtered transcript that repeats a turn is not something anyone would ask for on purpose. But it is a second behaviour change riding along with the ordering fix, so it belongs in the PR description and ideally in a test, or someone will find it later and read it as a regression.

count=0 selects everything, in both versions. PerSourceFilter.count is Optional[int] with no validator, so count=0 is constructible, and source_filter.count is then falsy:

[A first 0]
current   ['a1', 'a2']
proposed  ['a1', 'a2']

"First zero messages from A" returns every message from A. Your rewrite keeps that, which I would leave alone here: it is older than this issue, it is a different defect, and folding it in would make the ordering change harder to review. Worth its own issue though, and the fix is either a validator that refuses non-positive counts or replacing the truthiness test with is not None.

One thing that makes the change cheaper than it looks: _apply_filter has exactly two callers, on_messages and on_messages_stream, and both go through it unchanged. So there is no second site to keep in step and no streaming variant to fix separately.

Thanks for picking this up with an actual implementation rather than a plus one.

ErenAta16 avatar Sep 10 '26 05:09 ErenAta16

Correcting something I said here yesterday. I flagged that count=0 selects every message from a source and suggested it deserved its own issue. It already has a fix: @nolanchic opened #7915 on 4 July, "MessageFilterAgent count=0 returns no messages instead of all", +105/-4 against the same file, and it has been sitting at mergeable_state=blocked since.

Its docstring draws exactly the distinction the current code is missing:

count (Optional[int]): The number of messages to keep when position is set. 0 means no messages; None means do not slice (all messages from this source are kept, regardless of position).

So that half should stay out of the ordering change, which is what I recommended anyway, but for a better reason than I gave: not "file it separately later", but "it is already filed and implemented, do not duplicate it".

The practical consequence for whoever writes the ordering fix: #7915 edits _message_filter_agent.py too, so the two will conflict textually even though they are independent defects. Landing #7915 first and rebasing the ordering change on top is the cheaper order, since #7915 is the older branch and already has tests.

@amasen02 worth knowing before you turn your snippet into a PR.

ErenAta16 avatar Sep 11 '26 07:09 ErenAta16