Skip to content

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

Open
Joseph0120 wants to merge 4 commits into
joseph/communication_delay_PR3from
joseph/communication_delay_PR4
Open

[Communication] PR4: IAgent and AgentBase Supports Mailbox Delivery#215
Joseph0120 wants to merge 4 commits into
joseph/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

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

Copy link
Copy Markdown

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

Copy link
Copy Markdown

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 thread Assets/Scripts/Agents/AgentBase.cs Outdated
@coderabbitai

coderabbitai Bot commented Apr 1, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2d41fbb6-a765-4ff7-880c-79effb278328

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce599b and 403d41f.

📒 Files selected for processing (3)
  • Assets/Scripts/Communication/Mailbox.cs
  • Assets/Tests/EditMode/AgentBaseTests.cs
  • Assets/Tests/EditMode/MailboxTests.cs

📝 Walkthrough

Walkthrough

Mailbox.GetOrCreateInstance() now conditionally applies DontDestroyOnLoad only when Application.isPlaying, preventing edit-mode test objects from being marked persistent. A new MailboxTests edit-mode test verifies GetOrCreateInstance() works after the singleton is destroyed and cleared. AgentBaseTests is updated with a MailboxAwareAgentBase test subclass, reflection helpers to inject Mailbox and SimManager singletons, and three new tests covering mailbox subscription idempotency, receiver filtering, and unsubscription via OnDestroy.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • tryuan99
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.03% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change by describing AgentBase and IAgent mailbox delivery support.
Description check ✅ Passed The description covers the mailbox registration, delivery handling, and unsubscribe changes reflected in the diff.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 thread Assets/Scripts/Agents/AgentBase.cs Outdated
Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Assets/Tests/EditMode/AgentBaseTests.cs`:
- Around line 256-257: Add a brief inline comment above the test lines calling
SetMailboxInstance(null) and _agent.InvokeOnDestroyForTest() explaining that the
test nulls the public MailboxInstance to ensure the agent's OnDestroy logic uses
its cached private _mailboxInstance for unsubscription (rather than re-querying
Mailbox.Instance), i.e., this verifies that the implementation unsubscribes from
the cached instance; reference SetMailboxInstance, MailboxInstance,
_mailboxInstance, Mailbox.Instance and InvokeOnDestroyForTest in the comment for
clarity.
🪄 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: 446e9387-893e-4b87-b923-258a3857cea3

📥 Commits

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

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

Comment thread Assets/Tests/EditMode/AgentBaseTests.cs
Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
if (_mailboxRegistered) {
return;
}
_mailboxInstance = Mailbox.GetOrCreateInstance();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There should always be an instance already, or am I missing something?

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
public class AgentBase : MonoBehaviour, IAgent {
// Make sure the same agent does not subscribe to the mailbox event more than once (keeping
// track).
private bool _mailboxRegistered = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

no need for this flag if you can check whether _mailbox is null?

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
// Make sure the same agent does not subscribe to the mailbox event more than once (keeping
// track).
private bool _mailboxRegistered = false;
private Mailbox _mailboxInstance;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
private Mailbox _mailboxInstance;
private Mailbox _mailbox;

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
// Start is called before the first frame update.
protected virtual void Start() {}
protected virtual void Start() {
TryRegisterMailbox();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why in Awake and Start? I think it should just be in Awake

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
Comment on lines +224 to +225
_mailboxRegistered = false;
_mailboxInstance = null;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

superfluous

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
Comment on lines +365 to +367
if (!ReferenceEquals(receiver, this)) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Idt you need this. Mailbox should have done the check already

Comment thread Assets/Scripts/Agents/AgentBase.cs Outdated
};
}

protected virtual void OnMessage(Message message) {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd rename this to be OnReceiveMessage to be precise

// Edit-mode tests can create a mailbox without entering play mode, where DontDestroyOnLoad is
// invalid.
if (Application.isPlaying) {
DontDestroyOnLoad(mailboxObject);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why is this necessary and not in the other singleton instances that use DontDestroyOnLoad(gameObject);?

}

private static void SetMailboxInstance(Mailbox mailbox) {
FieldInfo instanceField = typeof(Mailbox).GetField(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No, this is not the right approach. I think you might need to use play mode tests for time.

@Joseph0120 Joseph0120 force-pushed the joseph/communication_delay_PR3 branch 3 times, most recently from d09ba92 to 1274296 Compare June 23, 2026 04:43
@Joseph0120 Joseph0120 force-pushed the joseph/communication_delay_PR4 branch from 5ce599b to 403d41f Compare June 27, 2026 19:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Assets/Scripts/Communication/Mailbox.cs`:
- Around line 137-149: DeliverMessages currently leaves _messageBuffer uncleared
if pending.Receiver.Receive or OnMessageDelivered throws, which can cause
already-dequeued messages to be delivered again on later Update calls. Update
the DeliverMessages method in Mailbox so the buffered messages are always
cleared even when delivery fails, by wrapping the delivery loop in a try/finally
or equivalent cleanup around _messageBuffer.Clear().
- Around line 123-125: The packet drop check in Mailbox’s delivery logic uses
the wrong comparison, so a zero PacketDeliveryRatio can still let a packet
through when UnityEngine.Random.value is exactly 0. Update the condition in the
packet delivery path so the drop happens on greater-than-or-equal comparison,
keeping the behavior deterministic for “drop all packets” cases. Focus on the
check inside Mailbox’s delivery flow where linkConfig.PacketDeliveryRatio is
compared against UnityEngine.Random.value.

In `@Assets/Tests/EditMode/AgentBaseTests.cs`:
- Around line 258-262: The test in AgentBaseTests is checking unsubscription
indirectly through Mailbox.Send()/Update, which can be influenced by direct
receiver delivery instead of the OnDestroy unsubscribe path. Update the
assertion to verify the mailbox’s OnMessageDelivered subscription list no longer
contains the agent handler after InvokeOnDestroyForTest(), or add a test seam
that explicitly broadcasts OnMessageDelivered and confirms the handler is
removed. Use the existing AgentBaseTests, Mailbox.DeliverMessages, and
InvokeOnDestroyForTest references to locate the test setup.
🪄 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: 2d41fbb6-a765-4ff7-880c-79effb278328

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce599b and 403d41f.

📒 Files selected for processing (3)
  • Assets/Scripts/Communication/Mailbox.cs
  • Assets/Tests/EditMode/AgentBaseTests.cs
  • Assets/Tests/EditMode/MailboxTests.cs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Assets/Scripts/Communication/Mailbox.cs`:
- Around line 137-149: DeliverMessages currently leaves _messageBuffer uncleared
if pending.Receiver.Receive or OnMessageDelivered throws, which can cause
already-dequeued messages to be delivered again on later Update calls. Update
the DeliverMessages method in Mailbox so the buffered messages are always
cleared even when delivery fails, by wrapping the delivery loop in a try/finally
or equivalent cleanup around _messageBuffer.Clear().
- Around line 123-125: The packet drop check in Mailbox’s delivery logic uses
the wrong comparison, so a zero PacketDeliveryRatio can still let a packet
through when UnityEngine.Random.value is exactly 0. Update the condition in the
packet delivery path so the drop happens on greater-than-or-equal comparison,
keeping the behavior deterministic for “drop all packets” cases. Focus on the
check inside Mailbox’s delivery flow where linkConfig.PacketDeliveryRatio is
compared against UnityEngine.Random.value.

In `@Assets/Tests/EditMode/AgentBaseTests.cs`:
- Around line 258-262: The test in AgentBaseTests is checking unsubscription
indirectly through Mailbox.Send()/Update, which can be influenced by direct
receiver delivery instead of the OnDestroy unsubscribe path. Update the
assertion to verify the mailbox’s OnMessageDelivered subscription list no longer
contains the agent handler after InvokeOnDestroyForTest(), or add a test seam
that explicitly broadcasts OnMessageDelivered and confirms the handler is
removed. Use the existing AgentBaseTests, Mailbox.DeliverMessages, and
InvokeOnDestroyForTest references to locate the test setup.
🪄 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: 2d41fbb6-a765-4ff7-880c-79effb278328

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce599b and 403d41f.

📒 Files selected for processing (3)
  • Assets/Scripts/Communication/Mailbox.cs
  • Assets/Tests/EditMode/AgentBaseTests.cs
  • Assets/Tests/EditMode/MailboxTests.cs
🛑 Comments failed to post (3)
Assets/Scripts/Communication/Mailbox.cs (2)

123-125: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use >= for the drop check.

With the current > comparison, a PacketDeliveryRatio of 0f still delivers when Random.value is exactly 0. That makes “drop all packets” nondeterministically leak messages.

Proposed fix
-    if (UnityEngine.Random.value > linkConfig.PacketDeliveryRatio) {
+    if (UnityEngine.Random.value >= linkConfig.PacketDeliveryRatio) {
       return;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    // Applies packet delivery ratio (PDR). This is done before sending into PQ.
    if (UnityEngine.Random.value >= linkConfig.PacketDeliveryRatio) {
      return;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Assets/Scripts/Communication/Mailbox.cs` around lines 123 - 125, The packet
drop check in Mailbox’s delivery logic uses the wrong comparison, so a zero
PacketDeliveryRatio can still let a packet through when UnityEngine.Random.value
is exactly 0. Update the condition in the packet delivery path so the drop
happens on greater-than-or-equal comparison, keeping the behavior deterministic
for “drop all packets” cases. Focus on the check inside Mailbox’s delivery flow
where linkConfig.PacketDeliveryRatio is compared against
UnityEngine.Random.value.

137-149: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Always clear _messageBuffer, even if delivery throws.

If pending.Receiver.Receive(...) or an OnMessageDelivered subscriber throws, _messageBuffer.Clear() is skipped. Those already-dequeued messages stay buffered and can be redelivered on subsequent Update() calls.

Proposed fix
   private void DeliverMessages() {
     float currentTime = SimManager.Instance.ElapsedTime;
     while (!_messageQueue.IsEmpty() && currentTime >= _messageQueue.Peek().DeliverAt) {
       _messageBuffer.Add(_messageQueue.Dequeue());
     }
-    foreach (PendingMessage pending in _messageBuffer) {
-      if (!IsReceiverValid(pending.Receiver)) {
-        continue;
-      }
-      pending.Receiver.Receive(pending.Message);
-      OnMessageDelivered?.Invoke(pending.Receiver, pending.Message);
+    try {
+      foreach (PendingMessage pending in _messageBuffer) {
+        if (!IsReceiverValid(pending.Receiver)) {
+          continue;
+        }
+        pending.Receiver.Receive(pending.Message);
+        OnMessageDelivered?.Invoke(pending.Receiver, pending.Message);
+      }
+    } finally {
+      _messageBuffer.Clear();
     }
-    _messageBuffer.Clear();
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  private void DeliverMessages() {
    float currentTime = SimManager.Instance.ElapsedTime;
    while (!_messageQueue.IsEmpty() && currentTime >= _messageQueue.Peek().DeliverAt) {
      _messageBuffer.Add(_messageQueue.Dequeue());
    }
    try {
      foreach (PendingMessage pending in _messageBuffer) {
        if (!IsReceiverValid(pending.Receiver)) {
          continue;
        }
        pending.Receiver.Receive(pending.Message);
        OnMessageDelivered?.Invoke(pending.Receiver, pending.Message);
      }
    } finally {
      _messageBuffer.Clear();
    }
  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Assets/Scripts/Communication/Mailbox.cs` around lines 137 - 149,
DeliverMessages currently leaves _messageBuffer uncleared if
pending.Receiver.Receive or OnMessageDelivered throws, which can cause
already-dequeued messages to be delivered again on later Update calls. Update
the DeliverMessages method in Mailbox so the buffered messages are always
cleared even when delivery fails, by wrapping the delivery loop in a try/finally
or equivalent cleanup around _messageBuffer.Clear().
Assets/Tests/EditMode/AgentBaseTests.cs (1)

258-262: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Don’t verify event unsubscription through Mailbox.Send() to the same agent.

Mailbox.DeliverMessages() directly calls pending.Receiver.Receive(...) before broadcasting OnMessageDelivered, so this assertion can pass or fail because of direct receiver delivery/validity rather than because OnDestroy() removed the mailbox event subscription. Prefer asserting the mailbox event invocation list no longer contains the agent handler, or add a test seam that broadcasts OnMessageDelivered directly after InvokeOnDestroyForTest().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Assets/Tests/EditMode/AgentBaseTests.cs` around lines 258 - 262, The test in
AgentBaseTests is checking unsubscription indirectly through
Mailbox.Send()/Update, which can be influenced by direct receiver delivery
instead of the OnDestroy unsubscribe path. Update the assertion to verify the
mailbox’s OnMessageDelivered subscription list no longer contains the agent
handler after InvokeOnDestroyForTest(), or add a test seam that explicitly
broadcasts OnMessageDelivered and confirms the handler is removed. Use the
existing AgentBaseTests, Mailbox.DeliverMessages, and InvokeOnDestroyForTest
references to locate the test setup.

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.

2 participants