Skip to content

[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery#215

Open
Joseph0120 wants to merge 2 commits intojoseph/communication_delay_PR3from
joseph/communication_delay_PR4
Open

[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery#215
Joseph0120 wants to merge 2 commits intojoseph/communication_delay_PR3from
joseph/communication_delay_PR4

Conversation

@Joseph0120
Copy link
Copy Markdown
Collaborator

Files Modified:

AgentBase -> TryRegisterMailbox() when Start() or Awake(). Unsubscribe to mailbox when OnDestroy().
TryRegisterMailbox() subscribes to the mailbox, and prevents redundant registration.
HandleMailboxDelivery(IAgent receiver, Message message) Check if self is the right receiver, if so then handle the message. Because a popped message is broadcasted to all subscribed agents and it is the agent's responsibility to check if it is the recipient. (Mailbox sends mail to everyone, and only the right recipient has the "key" to unlock that message)

IAgent -> Added NodeType, which tells the mailbox what type of Agent it is reading from.

@stacklane-pr-stack-visualizer
Copy link
Copy Markdown

stacklane-pr-stack-visualizer bot commented Apr 1, 2026

🧱 Stack PR · Part of stack (9 PRs total)

Stack Structure:

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements a messaging system for agents by integrating AgentBase with a Mailbox service. It adds registration logic, message handling, and a new NodeType property to the IAgent interface. Feedback was provided regarding the performance of the broadcast-based message delivery and the need for a null check to handle destroyed Unity objects in the message handler.

Comment on lines +359 to +362
private void HandleMailboxDelivery(IAgent receiver, Message message) {
if (!ReferenceEquals(receiver, this)) { return; }
OnMessage(message);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current message delivery implementation uses a broadcast pattern where every agent receives every message and filters it locally. This results in $O(N)$ complexity per message delivery (where $N$ is the number of agents), which can become a performance bottleneck in simulations with many agents. Consider refactoring the Mailbox to use a more targeted delivery system (e.g., a Dictionary of subscribers) if performance becomes an issue.

Additionally, adding a check for this == null is recommended to ensure that messages are not processed by 'zombie' objects that have been destroyed but not yet unsubscribed from the event. In Unity, ReferenceEquals is preferred for identity checks on potentially destroyed objects to avoid the 'both are null' false positive of the overloaded == operator.

  private void HandleMailboxDelivery(IAgent receiver, Message message) {
    if (this == null || !ReferenceEquals(receiver, this)) { return; }
    OnMessage(message);
  }

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e7498582-4367-408e-b2f6-3b1eb4b37e53

📥 Commits

Reviewing files that changed from the base of the PR and between 6c361dc and f132eca.

📒 Files selected for processing (1)
  • Assets/Scripts/Agents/IAgent.cs

📝 Walkthrough

Walkthrough

Adds a read-only NodeType property to IAgent. Extends AgentBase with a virtual NodeType (defaulting to CommsNode.Interceptor), mailbox subscription tracking via a _mailboxRegistered flag, idempotent TryRegisterMailbox() calls from Awake() and Start(), a HandleMailboxDelivery(IAgent, Message) handler that invokes a new protected virtual OnMessage(Message) when the delivered receiver matches the agent, and unsubscription/reset in OnDestroy().

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: adding mailbox delivery support to IAgent and AgentBase interfaces/classes, which aligns with the changeset.
Description check ✅ Passed The description is directly related to the changeset, clearly explaining the modifications to AgentBase and IAgent, including mailbox registration, lifecycle management, and the new NodeType property.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch joseph/communication_delay_PR4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Assets/Scripts/Agents/AgentBase.cs`:
- Around line 358-362: HandleMailboxDelivery is currently invoked for every
subscriber causing O(n) broadcasts; change the Mailbox to dispatch directly to
the intended receiver instead of broadcasting: add a lookup (e.g.,
Dictionary<IAgent, Action<Message>> or Dictionary<IAgent, Queue<Message>>)
inside Mailbox and register agents when they subscribe, update the
Mailbox.Send/Deliver method to find the target IAgent via that dictionary and
call its registered handler (OnMessage) or enqueue the Message, and remove the
broadcast loop so HandleMailboxDelivery is no longer invoked for non-target
agents; ensure the dictionary uses thread-safe access (lock or
ConcurrentDictionary) and update subscription/unsubscription code to maintain
the map.
- Around line 222-225: The unsubscribe uses Mailbox.Instance but registration
used Mailbox.GetOrCreateInstance(), so store the mailbox reference when
registering (e.g., add a private field like _mailboxInstance and set it in
TryRegisterMailbox to Mailbox.GetOrCreateInstance()), use that stored
_mailboxInstance for adding/removing the HandleMailboxDelivery handler and for
null checks, set _mailboxRegistered = false and clear _mailboxInstance after
unsubscribing to avoid stale references and ensure consistent unsubscription.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7a15b87a-74af-4a86-a02b-7e725059abe0

📥 Commits

Reviewing files that changed from the base of the PR and between 66fd29c and 6c361dc.

📒 Files selected for processing (2)
  • Assets/Scripts/Agents/AgentBase.cs
  • Assets/Scripts/Agents/IAgent.cs

Comment on lines +222 to +225
if (_mailboxRegistered && Mailbox.Instance != null) {
Mailbox.Instance.OnMessageDelivered -= HandleMailboxDelivery;
_mailboxRegistered = false;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Minor inconsistency: Mailbox.Instance vs Mailbox.GetOrCreateInstance().

The subscription in TryRegisterMailbox() uses Mailbox.GetOrCreateInstance() and stores the handler on that instance, but the unsubscription uses Mailbox.Instance directly. If the Mailbox singleton were ever recreated between registration and destruction, the unsubscription would target a different object.

Given that Mailbox uses DontDestroyOnLoad, this is unlikely to cause issues in practice, but for consistency you could store a reference to the mailbox instance during registration:

♻️ Optional: Store mailbox reference for consistent unsubscription
  // Make sure the same agent does not subscribe to the mailbox event more than once (keeping track).
  private bool _mailboxRegistered = false;
+ private Mailbox _registeredMailbox = null;

  // In TryRegisterMailbox():
  protected void TryRegisterMailbox() {
    if (_mailboxRegistered) { return; }
    Mailbox mailbox = Mailbox.GetOrCreateInstance();
    if (mailbox == null) { return; }
    mailbox.OnMessageDelivered += HandleMailboxDelivery;
+   _registeredMailbox = mailbox;
    _mailboxRegistered = true;
  }

  // In OnDestroy():
- if (_mailboxRegistered && Mailbox.Instance != null) {
-   Mailbox.Instance.OnMessageDelivered -= HandleMailboxDelivery;
+ if (_mailboxRegistered && _registeredMailbox != null) {
+   _registeredMailbox.OnMessageDelivered -= HandleMailboxDelivery;
+   _registeredMailbox = null;
    _mailboxRegistered = false;
  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Assets/Scripts/Agents/AgentBase.cs` around lines 222 - 225, The unsubscribe
uses Mailbox.Instance but registration used Mailbox.GetOrCreateInstance(), so
store the mailbox reference when registering (e.g., add a private field like
_mailboxInstance and set it in TryRegisterMailbox to
Mailbox.GetOrCreateInstance()), use that stored _mailboxInstance for
adding/removing the HandleMailboxDelivery handler and for null checks, set
_mailboxRegistered = false and clear _mailboxInstance after unsubscribing to
avoid stale references and ensure consistent unsubscription.

Comment on lines +358 to +362
// Delivers a message to the right receiver. Check if self is the right receiver, if so then handle the message.
private void HandleMailboxDelivery(IAgent receiver, Message message) {
if (!ReferenceEquals(receiver, this)) { return; }
OnMessage(message);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider performance implications of broadcast pattern.

The HandleMailboxDelivery method correctly uses ReferenceEquals for identity comparison. However, per the design described in the PR, every message delivery invokes this handler on all subscribed agents, resulting in O(n) invocations per message.

This is acceptable for a small number of agents but may become a bottleneck with many agents. If message volume or agent count grows significantly, consider a dictionary-based lookup in the Mailbox to dispatch directly to the intended receiver rather than broadcasting.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Assets/Scripts/Agents/AgentBase.cs` around lines 358 - 362,
HandleMailboxDelivery is currently invoked for every subscriber causing O(n)
broadcasts; change the Mailbox to dispatch directly to the intended receiver
instead of broadcasting: add a lookup (e.g., Dictionary<IAgent, Action<Message>>
or Dictionary<IAgent, Queue<Message>>) inside Mailbox and register agents when
they subscribe, update the Mailbox.Send/Deliver method to find the target IAgent
via that dictionary and call its registered handler (OnMessage) or enqueue the
Message, and remove the broadcast loop so HandleMailboxDelivery is no longer
invoked for non-target agents; ensure the dictionary uses thread-safe access
(lock or ConcurrentDictionary) and update subscription/unsubscription code to
maintain the map.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant