Skip to content

[Communication] PR3: Added Central Mailbox Component.#214

Open
Joseph0120 wants to merge 10 commits into
joseph/communication_delay_PR2from
joseph/communication_delay_PR3
Open

[Communication] PR3: Added Central Mailbox Component.#214
Joseph0120 wants to merge 10 commits into
joseph/communication_delay_PR2from
joseph/communication_delay_PR3

Conversation

@Joseph0120

Copy link
Copy Markdown
Collaborator

Files Created:

Mailbox.cs -> The centralized mailbox is what all agents use to send and receive delayed messages.

Descriptions:
There are 3 modes under "LatencyMode" for constructing the latency table. NoLatency sets mailbox to Ideal communication with zero latency (assume no latency); UniformLatency set all latency entries to one singular "_uniformLatency" value; IndividualLatency allows you to configure each "from->to" pair independently. "_latencyJitterStdSeconds" sets Latency jitter standard deviation in seconds.

Send(Message message) enqueue a message for delayed delivery. Message will be released when DeliverTime has reached.

DeliverDueMessages() repeatedly pop due messages off the queue. Apply PDR so only certain amount of messages pass through.

@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 introduces a centralized Mailbox component for handling delayed message delivery between agents, featuring configurable latency and Gaussian jitter. The review feedback identifies several areas for improvement, including optimizing the delivery loop to avoid per-frame allocations, addressing potential null reference exceptions due to initialization order, ensuring singleton persistence for manually placed components, and resolving a discrepancy regarding missing packet delivery ratio logic.

Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.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
📝 Walkthrough

Walkthrough

This PR adds a new Mailbox MonoBehaviour singleton that centralizes inter-agent message delivery with configurable latency, jitter, and packet delivery ratio. Messages are scheduled into a priority queue using deterministic simulation time and optional Gaussian jitter; DeliverMessages() dispatches due messages each Update after validating receiver liveness (null, destroyed, or terminated). Mailbox.Configure(...) rebuilds defaults and per-link overrides from Configs.CommunicationConfig; SimManager.StartSimulation now calls Mailbox.GetOrCreateInstance() to ensure the mailbox exists before simulation-start events fire. A new edit-mode test suite exercises delivery timing, queue reinitialization, PDR filtering, per-link overrides, batch delivery semantics, exception handling during callbacks, receiver termination/destruction, and configuration fallbacks. New TestAgent test stub implements IAgent interface for test scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PisterLab/micromissiles-unity#124: The new Mailbox directly depends on the sim-manager lifecycle events (OnSimulationStarted/OnSimulationEnded) and agent termination API (IAgent.IsTerminated/Terminate) introduced in this PR.
  • PisterLab/micromissiles-unity#212: The Mailbox implementation enqueues and delivers Message objects and depends on the messaging primitives (Message/IMessagePayload) added in this PR.
  • PisterLab/micromissiles-unity#222: The Mailbox.Configure(...) method and delivery logic depend on the Configs.CommunicationConfig protobuf types wired through the simulation configuration hierarchy in this PR.

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.12% 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 accurately describes the main change: adding a centralized Mailbox component for communication, which is the primary feature introduced in this PR.
Description check ✅ Passed The description provides relevant details about the Mailbox component's purpose and key functionality, covering the created file, latency modes, and message delivery methods.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch joseph/communication_delay_PR3

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: 5

🤖 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/Messaging/Mailbox.cs`:
- Around line 39-47: The IndividualLatency/default latency arrays are missing
two directed CommsNode pairs (IADS -> Interceptor and Interceptor -> IADS),
causing those routes to default to 0f; update the DefaultLatencyOverrides array
(and the second similar array around the other occurrence) to include
LatencyOverride entries for From = CommsNode.IADS, To = CommsNode.Interceptor,
Seconds = 0.2f and From = CommsNode.Interceptor, To = CommsNode.IADS, Seconds =
0.2f so all 9 directed pairs between CommsNode.IADS, CommsNode.Carrier, and
CommsNode.Interceptor are explicitly specified.
- Around line 87-94: Send() dereferences _latencyTable and _messageQueue which
can be null if ApplyLatencyOverrides() hasn't run; update Send(Message) to check
for null (e.g., if _latencyTable == null || _messageQueue == null) and return
early (or log a warning) before accessing them, so PendingMessage creation and
_latencyTable.Get(...) are protected; reference the Send method and
ApplyLatencyOverrides, and ensure any unit tests that call Send before
initialization still pass by handling the uninitialized mailbox state
gracefully.
- Around line 122-135: DeliverDueMessages is dequeuing all due PendingMessage
items and immediately invoking OnMessageDelivered for each, but it never applies
the Packet Delivery Rate (PDR) probabilistic filter; update DeliverDueMessages
to apply PDR per message before delivery: when iterating dueMessages, for each
PendingMessage use the configured PDR value (e.g., a float field or getter) to
perform a random check (System.Random or UnityEngine.Random.value) and only call
OnMessageDelivered(pending.Receiver, pending.Message) if the random check passes
and IsReceiverValid(pending.Receiver) returns true; ensure dropped messages are
simply not delivered (no further action) and preserve current receiver validity
check and any logging if desired so the rest of the queue logic (_messageQueue,
Peek/Dequeue, PendingMessage.DeliverAt, GetCurrentTime) remains unchanged.
- Around line 128-132: The code in Mailbox.Update is allocating a new
List<PendingMessage> (dueMessages) every frame; replace that per-frame
allocation by either processing messages inline as you Dequeue from
_messageQueue (iterate while !_messageQueue.IsEmpty() and handle each
PendingMessage immediately) or reuse a single preallocated List<PendingMessage>
field (e.g., _reusableDueMessages) that you Clear() each frame before adding;
reference the existing _messageQueue, PendingMessage, DeliverAt and the Update()
delivery loop when applying the change.
🪄 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: 4393003b-061f-4451-8a17-92ad61c4b9ac

📥 Commits

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

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

Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
Comment thread Assets/Scripts/Agents/Messaging/Mailbox.cs Outdated
@Joseph0120 Joseph0120 changed the title [Communication] Added Central Mailbox Component. [Communication] PR3 Added Central Mailbox Component. Apr 1, 2026
@Joseph0120 Joseph0120 changed the title [Communication] PR3 Added Central Mailbox Component. [Communication] PR3: Added Central Mailbox Component. Apr 1, 2026
@Joseph0120 Joseph0120 requested a review from tryuan99 April 1, 2026 06:17
@Joseph0120 Joseph0120 force-pushed the joseph/communication_delay_PR2 branch from b203cf9 to 735c1ae Compare April 28, 2026 18:08
@Joseph0120 Joseph0120 force-pushed the joseph/communication_delay_PR3 branch from 66fd29c to bc3780d Compare April 28, 2026 18: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.

♻️ Duplicate comments (2)
Assets/Scripts/Agents/Messaging/Mailbox.cs (2)

110-128: ⚠️ Potential issue | 🟠 Major

Send() can throw NullReferenceException if called before initialization.

_messageQueue is only initialized in ClearPendingMessages() (called by Configure()). If Send() is called before Configure() completes, line 127 will throw a NullReferenceException.

🐛 Proposed fix: Add defensive initialization
 public void Send(Message message) {
   if (message == null || message.Sender == null || message.Receiver == null) {
     return;
   }
+  if (_messageQueue == null) {
+    return;  // Mailbox not yet configured
+  }

   LinkRuntimeConfig linkConfig = GetEffectiveLinkConfig(message.Sender, message.Receiver);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Assets/Scripts/Agents/Messaging/Mailbox.cs` around lines 110 - 128, Send()
can NRE if _messageQueue is null because it's only set in
ClearPendingMessages()/Configure(); update Send() to defensively handle
uninitialized queue by either lazily initializing _messageQueue (create a new
priority queue when null) or early-return with a safe log if Configure() hasn't
run, ensuring you reference the _messageQueue field and avoid enqueuing into a
null object; modify Send(), and if choosing lazy init, ensure behavior matches
ClearPendingMessages() semantics so PendingMessage enqueuing uses the same queue
implementation.

137-140: 🧹 Nitpick | 🔵 Trivial

Avoid per-frame allocation in hot path.

Creating a new List<PendingMessage> every Update() generates unnecessary GC pressure. Messages can be processed inline during dequeue.

♻️ Proposed refactor: process inline
 private void DeliverDueMessages() {
   if (_messageQueue == null) {
     return;
   }

   float currentTime = GetCurrentTime();
-  var dueMessages = new List<PendingMessage>();
   while (!_messageQueue.IsEmpty() && currentTime >= _messageQueue.Peek().DeliverAt) {
-    dueMessages.Add(_messageQueue.Dequeue());
-  }
-  foreach (PendingMessage pending in dueMessages) {
+    PendingMessage pending = _messageQueue.Dequeue();
     if (!IsReceiverValid(pending.Receiver)) {
       continue;
     }
     OnMessageDelivered?.Invoke(pending.Receiver, pending.Message);
   }
 }

Note: If same-frame message isolation is intentional (preventing handlers from processing messages they send immediately), document this behavior explicitly.

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

In `@Assets/Scripts/Agents/Messaging/Mailbox.cs` around lines 137 - 140, The
per-frame allocation of a new List<PendingMessage> inside Mailbox.Update()
causes GC pressure; instead process messages inline as you dequeue from
_messageQueue (use while (!_messageQueue.IsEmpty() && currentTime >=
_messageQueue.Peek().DeliverAt) { var msg = _messageQueue.Dequeue();
HandleMessage(msg); }) or reuse a private List<PendingMessage> field if batching
is required; if same-frame message isolation is intentional, add an explicit
comment on Mailbox.Update() explaining that handlers should not see messages
sent during the same frame.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@Assets/Scripts/Agents/Messaging/Mailbox.cs`:
- Around line 110-128: Send() can NRE if _messageQueue is null because it's only
set in ClearPendingMessages()/Configure(); update Send() to defensively handle
uninitialized queue by either lazily initializing _messageQueue (create a new
priority queue when null) or early-return with a safe log if Configure() hasn't
run, ensuring you reference the _messageQueue field and avoid enqueuing into a
null object; modify Send(), and if choosing lazy init, ensure behavior matches
ClearPendingMessages() semantics so PendingMessage enqueuing uses the same queue
implementation.
- Around line 137-140: The per-frame allocation of a new List<PendingMessage>
inside Mailbox.Update() causes GC pressure; instead process messages inline as
you dequeue from _messageQueue (use while (!_messageQueue.IsEmpty() &&
currentTime >= _messageQueue.Peek().DeliverAt) { var msg =
_messageQueue.Dequeue(); HandleMessage(msg); }) or reuse a private
List<PendingMessage> field if batching is required; if same-frame message
isolation is intentional, add an explicit comment on Mailbox.Update() explaining
that handlers should not see messages sent during the same frame.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 29fa05e8-6a71-4600-a171-3a9a4e3588fb

📥 Commits

Reviewing files that changed from the base of the PR and between 66fd29c and 276ab5d.

📒 Files selected for processing (2)
  • Assets/Scripts/Agents/Messaging/Mailbox.cs
  • Assets/Scripts/Managers/SimManager.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.

Actionable comments posted: 2

🤖 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 147-153: The delivery loop can throw and prevent
_dueMessages.Clear() from running; wrap the delivery logic in a try/finally so
_dueMessages.Clear() is executed regardless of exceptions: locate the foreach
over _dueMessages in Mailbox.Deliver (the block that calls IsReceiverValid and
OnMessageDelivered with PendingMessage), move the clear into a finally block,
and keep the existing receiver validation and delivery calls inside the try so
any thrown exception still allows _dueMessages to be cleared; optionally
consider iterating a snapshot (e.g., a copy of _dueMessages) if you want to
avoid concurrent modification concerns while delivering.
- Around line 121-127: The PDR check is currently performed inside Send() (the
UnityEngine.Random.value >= linkConfig.PacketDeliveryRatio early return) which
drops packets at enqueue time and breaks delayed-loss semantics; remove that
Random-based drop from Send() and instead apply the packet delivery ratio when
actually delivering queued items in DeliverDueMessages(): in the delivery loop
inside DeliverDueMessages() consult linkConfig.PacketDeliveryRatio and use
UnityEngine.Random to skip (drop) the packet at delivery time, preserving
enqueue/timestamp behavior and any delay semantics; update or add tests that
expect loss to occur at delivery rather than enqueue for
Mailbox.Send/DeliverDueMessages.
🪄 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: bec77c47-46e8-4885-bd4f-30de84b28a12

📥 Commits

Reviewing files that changed from the base of the PR and between 276ab5d and 9b184c7.

📒 Files selected for processing (5)
  • Assets/Scripts/Communication/Mailbox.cs
  • Assets/Scripts/Communication/Mailbox.cs.meta
  • Assets/Scripts/Managers/SimManager.cs
  • Assets/Tests/EditMode/MailboxTests.cs
  • Assets/Tests/EditMode/MailboxTests.cs.meta

Comment thread Assets/Scripts/Communication/Mailbox.cs
Comment thread Assets/Scripts/Communication/Mailbox.cs Outdated
Comment thread Assets/Tests/EditMode/IadsCommsAgentTests.cs.meta Outdated
Comment thread Assets/Scripts/Communication/Mailbox.cs
Comment thread Assets/Scripts/Communication/Mailbox.cs Outdated
Comment thread Assets/Scripts/Communication/Mailbox.cs Outdated
Comment thread Assets/Scripts/Communication/Mailbox.cs Outdated
Comment thread Assets/Scripts/Communication/Mailbox.cs
Comment thread Assets/Scripts/Communication/Mailbox.cs Outdated
Comment thread Assets/Scripts/Managers/SimManager.cs
Comment thread Assets/Tests/EditMode/MailboxTests.cs Outdated
Comment thread Assets/Tests/EditMode/MailboxTests.cs Outdated
@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 requested a review from tryuan99 June 24, 2026 01:46
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