Skip to content

Implement donation troops/gold between human players after forming an alliance - #2450

Merged
evanpelle merged 8 commits into
openfrontio:mainfrom
LoackyBit:implement-donation-troops/gold-between-human-players-after-forming-an-alliance
Nov 21, 2025
Merged

evanpelle merged 8 commits into
openfrontio:mainfrom
LoackyBit:implement-donation-troops/gold-between-human-players-after-forming-an-alliance

Conversation

@LoackyBit

@LoackyBit LoackyBit commented Nov 14, 2025 •

Copy link
Copy Markdown
Contributor

Resolves #2448

Hi team,

I've implemented and locally tested the alliance-related changes (including unit tests and some manual simulation with multiple browser profiles).
Unfortunately I wasn't able to perform full end-to-end testing on the live game server with two separate machines/accounts.

If someone on the team (or another contributor) can verify the alliance flow with two real players, that would be greatly appreciated before merging. Happy to hop on a call or provide any clarification needed.

Thanks!

Description:

Fixed a race condition bug where donations (troops/gold) between human players failed after forming an alliance. The issue was caused by a one-tick delay in AllianceRequestReplyExecution: the alliance acceptance logic ran in tick() instead of init(), meaning the alliance wasn't created until the tick after the execution was added. If a donation execution was added in the same turn as the alliance acceptance, it would fail the isFriendly() check because the alliance didn't exist yet.

Root cause: When human players formed alliances via reply, the execution model delayed alliance creation by one tick, while bots called accept() directly without this delay.

Solution: Moved alliance acceptance logic from tick() to init() in AllianceRequestReplyExecution.ts, ensuring immediate alliance creation and eliminating race conditions with donations.

Changes:

  • Modified src/core/execution/alliance/AllianceRequestReplyExecution.ts to process alliance replies in init() instead of tick()
  • Added comprehensive test suite tests/AllianceDonation.test.ts with 5 test cases covering donation scenarios after alliance formation (reply and mutual request flows)
  • All existing tests pass (323 total)

Please complete the following:

  • I have added screenshots for all UI updates (N/A - backend logic fix only)
  • I process any text displayed to the user through translateText() and I've added it to the en.json file (N/A - no user-facing text changes)
  • I have added relevant tests to the test directory
  • I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced

Discord: loacky
GitHub: @LoackyBit

@LoackyBit
LoackyBit requested a review from a team as a code owner November 14, 2025 12:59
@CLAassistant

CLAassistant commented Nov 14, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Nov 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Moves alliance-reply processing from the per-tick phase into the execution's init() so replies are handled immediately during initialization; tick() is replaced by a no-op. Adds tests validating alliance formation, donations, and same-tick donation race scenarios.

Changes

Cohort / File(s) Summary
Core Execution Logic
src/core/execution/alliance/AllianceRequestReplyExecution.ts
Processes alliance replies in init() instead of tick(), removes runtime null-checks in tick(), and makes tick() a no-op. Public signatures unchanged.
Alliance Donation Tests
tests/AllianceDonation.test.ts
Adds tests for direct requests, mutual auto-accept, reply-based acceptance, gold and troop donations, and same-tick donation race scenarios.
Manifest / Package (minor)
.../manifest_file, .../package.json
Minor manifest/package entries present in diff (no public API changes).

Sequence Diagram(s)

sequenceDiagram
    participant Init as Init()
    participant Exec as AllianceRequestReplyExecution
    participant Tick as Tick()
    participant Donate as DonateExecution

    rect rgb(220,235,255)
      Note over Init,Exec: New — reply processed immediately in init()
      Init->>Exec: processReply()
      Exec->>Exec: applyAllianceState()
    end

    rect rgb(220,255,220)
      Note over Tick,Donate: Subsequent tick/donate observe applied state
      Tick->>Donate: runDonate()
      Donate->>Exec: checkAlliance()
      Exec-->>Donate: allow/transfer
    end

    rect rgb(255,235,235)
      Note over Init,Tick: Old — reply deferred to tick (race possible)
      Init->>Tick: deferReply()
      Tick->>Exec: processReply()
      Tick->>Donate: runDonate() (may race)
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Review focus:
    • src/core/execution/alliance/AllianceRequestReplyExecution.ts — validate init-time side effects, ordering, and lack of new async races.
    • tests/AllianceDonation.test.ts — verify deterministic timing and coverage of same-tick donation race conditions.

Possibly related PRs

Suggested labels

Bug Fix, Feature - Simulation

Suggested reviewers

  • evanpelle
  • scottanderson

Poem

⚔️ At init the reply now wakes,
No tick-long pause, no tiny flakes.
Donations flow when bonds are made,
Tests catch races, none will fade. 🤝

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: implementing donation mechanics between human players after alliance formation, which directly relates to the core fix of moving alliance acceptance to init().
Description check ✅ Passed The description is well-related to the changeset, providing clear context about the race condition bug, root cause, solution, and changes made to AllianceRequestReplyExecution and new tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a4c58d and 61b43b5.

📒 Files selected for processing (1)
  • tests/AllianceDonation.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/AllianceDonation.test.ts

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/AllianceDonation.test.ts (2)

76-77: Consider checking isFriendly for consistency.

Test 1 (lines 55-56) verifies both isAlliedWith and isFriendly status, but this test only checks isAlliedWith. Consider adding isFriendly checks for consistency across tests.

Apply this diff if you want consistent assertions:

   expect(player1.isAlliedWith(player2)).toBeTruthy();
   expect(player2.isAlliedWith(player1)).toBeTruthy();
+  expect(player1.isFriendly(player2)).toBeTruthy();
+  expect(player2.isFriendly(player1)).toBeTruthy();

118-119: Consider checking isFriendly for consistency.

Same as the previous test - test 3 (lines 98-99) includes isFriendly checks, but this test omits them. Adding them would make the test suite more consistent.

Apply this diff if you want consistent assertions:

   expect(player1.isAlliedWith(player2)).toBeTruthy();
   expect(player2.isAlliedWith(player1)).toBeTruthy();
+  expect(player1.isFriendly(player2)).toBeTruthy();
+  expect(player2.isFriendly(player1)).toBeTruthy();
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8807c25 and 9fc2c41.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • src/core/execution/alliance/AllianceRequestReplyExecution.ts (2 hunks)
  • tests/AllianceDonation.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: scottanderson
Repo: openfrontio/OpenFrontIO PR: 1752
File: src/core/game/Game.ts:750-752
Timestamp: 2025-08-12T00:31:50.144Z
Learning: In the OpenFrontIO codebase, changes to the PlayerInteraction interface (like adding canDonateGold and canDonateTroops flags) do not require corresponding updates to src/core/Schemas.ts or server serialization code.
📚 Learning: 2025-08-12T00:31:50.144Z
Learnt from: scottanderson
Repo: openfrontio/OpenFrontIO PR: 1752
File: src/core/game/Game.ts:750-752
Timestamp: 2025-08-12T00:31:50.144Z
Learning: In the OpenFrontIO codebase, changes to the PlayerInteraction interface (like adding canDonateGold and canDonateTroops flags) do not require corresponding updates to src/core/Schemas.ts or server serialization code.

Applied to files:

  • tests/AllianceDonation.test.ts
📚 Learning: 2025-10-20T20:15:28.858Z
Learnt from: sambokai
Repo: openfrontio/OpenFrontIO PR: 2225
File: src/core/execution/FakeHumanExecution.ts:51-51
Timestamp: 2025-10-20T20:15:28.858Z
Learning: In src/core/execution/FakeHumanExecution.ts, game balance constants like MIRV_COOLDOWN_TICKS, MIRV_HESITATION_ODDS, VICTORY_DENIAL_TEAM_THRESHOLD, VICTORY_DENIAL_INDIVIDUAL_THRESHOLD, and STEAMROLL_CITY_GAP_MULTIPLIER are experimental tuning parameters subject to frequent change during balance testing. Do not flag changes to these values as issues or compare them against previous values.

Applied to files:

  • tests/AllianceDonation.test.ts
🧬 Code graph analysis (1)
tests/AllianceDonation.test.ts (5)
src/core/game/Game.ts (1)
  • Game (664-748)
tests/util/Setup.ts (2)
  • setup (23-81)
  • playerInfo (83-85)
src/core/execution/alliance/AllianceRequestExecution.ts (1)
  • AllianceRequestExecution (9-72)
src/core/execution/alliance/AllianceRequestReplyExecution.ts (1)
  • AllianceRequestReplyExecution (3-57)
src/core/execution/DonateGoldExecution.ts (1)
  • DonateGoldExecution (4-51)
🔇 Additional comments (4)
tests/AllianceDonation.test.ts (2)

12-41: Test setup looks good.

The setup correctly initializes two players with different resource levels and enables donation flags. Good foundation for the test scenarios.


129-157: Excellent race condition test - validates the core fix.

This test directly validates the bug fix by adding both alliance acceptance and donation in the same turn. The two executeNextTick() calls ensure the alliance is created during initialization (first tick) before the donation executes (second tick), preventing the race condition.

src/core/execution/alliance/AllianceRequestReplyExecution.ts (2)

23-43: Clean fix - alliance creation now happens immediately.

Moving the alliance reply processing to init() ensures the alliance is created before any tick() calls in the same turn. This elegantly prevents the race condition where donations would check alliance status before it existed.

The logic remains unchanged, just relocated from tick() to init(). Well done keeping the fix minimal and focused.


46-48: Good practice to keep tick() as documented no-op.

Leaving tick() as an empty method with a clear comment is better than removing it entirely. The comment makes the intent obvious: this execution completes during initialization.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 14, 2025
Removed unnecessary comments and updated logic to process alliance replies immediately in init() to prevent race conditions.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fc2c41 and 32bd122.

📒 Files selected for processing (2)
  • src/core/execution/alliance/AllianceRequestReplyExecution.ts (1 hunks)
  • tests/AllianceDonation.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/AllianceDonation.test.ts
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: scottanderson
Repo: openfrontio/OpenFrontIO PR: 1752
File: src/core/game/Game.ts:750-752
Timestamp: 2025-08-12T00:31:50.144Z
Learning: In the OpenFrontIO codebase, changes to the PlayerInteraction interface (like adding canDonateGold and canDonateTroops flags) do not require corresponding updates to src/core/Schemas.ts or server serialization code.
🪛 GitHub Actions: 🧪 CI
src/core/execution/alliance/AllianceRequestReplyExecution.ts

[warning] 1-1: Code style issues found. Prettier reported formatting problems. Run 'npx prettier --write' to fix.

🔇 Additional comments (1)
src/core/execution/alliance/AllianceRequestReplyExecution.ts (1)

13-42: Good fix for the race condition.

Moving the alliance acceptance logic to init() ensures the alliance is created immediately when the execution is added, before other executions run their tick() methods in the same turn. This directly fixes the race condition where donations could fail when added in the same turn as alliance acceptance.

The logic is sound: proper null checks, early returns, and proper cleanup at the end.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/core/execution/alliance/AllianceRequestReplyExecution.ts (1)

44-45: Verify the Prettier formatting.

The previous review flagged a formatting issue here. Run npx prettier --write src/core/execution/alliance/AllianceRequestReplyExecution.ts to ensure the empty method conforms to the project's style.

🧹 Nitpick comments (1)
src/core/execution/alliance/AllianceRequestReplyExecution.ts (1)

13-42: Core fix looks good; the alliance now forms immediately.

Moving the acceptance logic to init() correctly addresses the race condition where donations could fail if executed in the same tick. The error handling is sound.

Optionally, consider flattening the nested structure with early returns for readability:

 init(mg: Game, ticks: number): void {
   if (!mg.hasPlayer(this.requestorID)) {
     console.warn(
       `AllianceRequestReplyExecution requester ${this.requestorID} not found`,
     );
     this.active = false;
     return;
   }
   this.requestor = mg.player(this.requestorID);

   if (this.requestor.isFriendly(this.recipient)) {
     console.warn("already allied");
+    this.active = false;
+    return;
-  } else {
-    const request = this.requestor
-      .outgoingAllianceRequests()
-      .find((ar) => ar.recipient() === this.recipient);
-    if (request === undefined) {
-      console.warn("no alliance request found");
-    } else {
-      if (this.accept) {
-        request.accept();
-        this.requestor.updateRelation(this.recipient, 100);
-        this.recipient.updateRelation(this.requestor, 100);
-      } else {
-        request.reject();
-      }
-    }
   }
+
+  const request = this.requestor
+    .outgoingAllianceRequests()
+    .find((ar) => ar.recipient() === this.recipient);
+  if (request === undefined) {
+    console.warn("no alliance request found");
+    this.active = false;
+    return;
+  }
+
+  if (this.accept) {
+    request.accept();
+    this.requestor.updateRelation(this.recipient, 100);
+    this.recipient.updateRelation(this.requestor, 100);
+  } else {
+    request.reject();
+  }
+
   this.active = false;
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32bd122 and 8a4c58d.

📒 Files selected for processing (1)
  • src/core/execution/alliance/AllianceRequestReplyExecution.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: scottanderson
Repo: openfrontio/OpenFrontIO PR: 1752
File: src/core/game/Game.ts:750-752
Timestamp: 2025-08-12T00:31:50.144Z
Learning: In the OpenFrontIO codebase, changes to the PlayerInteraction interface (like adding canDonateGold and canDonateTroops flags) do not require corresponding updates to src/core/Schemas.ts or server serialization code.
📚 Learning: 2025-10-18T17:54:01.311Z
Learnt from: sambokai
Repo: openfrontio/OpenFrontIO PR: 2225
File: src/core/execution/FakeHumanExecution.ts:172-173
Timestamp: 2025-10-18T17:54:01.311Z
Learning: In src/core/execution/FakeHumanExecution.ts, MIRVs and ground attacks should not be mutually exclusive. The considerMIRV() method should not short-circuit maybeAttack() - both actions can occur in the same tick.

Applied to files:

  • src/core/execution/alliance/AllianceRequestReplyExecution.ts

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 19, 2025
@evanpelle evanpelle added this to the v28 milestone Nov 20, 2025

@evanpelle evanpelle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

@evanpelle
evanpelle merged commit 0242853 into openfrontio:main Nov 21, 2025
2 checks passed
trajkovdimitar pushed a commit to trajkovdimitar/OpenFrontIO that referenced this pull request Dec 8, 2025
… alliance (openfrontio#2450)

Resolves openfrontio#2448 

Hi team,

I've implemented and locally tested the alliance-related changes
(including unit tests and some manual simulation with multiple browser
profiles).
Unfortunately I wasn't able to perform full end-to-end testing on the
live game server with two separate machines/accounts.

If someone on the team (or another contributor) can verify the alliance
flow with two real players, that would be greatly appreciated before
merging. Happy to hop on a call or provide any clarification needed.

Thanks!

## Description:

Fixed a race condition bug where donations (troops/gold) between human
players failed after forming an alliance. The issue was caused by a
one-tick delay in `AllianceRequestReplyExecution`: the alliance
acceptance logic ran in `tick()` instead of `init()`, meaning the
alliance wasn't created until the tick after the execution was added. If
a donation execution was added in the same turn as the alliance
acceptance, it would fail the `isFriendly()` check because the alliance
didn't exist yet.

**Root cause:** When human players formed alliances via reply, the
execution model delayed alliance creation by one tick, while bots called
`accept()` directly without this delay.

**Solution:** Moved alliance acceptance logic from `tick()` to `init()`
in `AllianceRequestReplyExecution.ts`, ensuring immediate alliance
creation and eliminating race conditions with donations.

**Changes:**
- Modified
`src/core/execution/alliance/AllianceRequestReplyExecution.ts` to
process alliance replies in `init()` instead of `tick()`
- Added comprehensive test suite `tests/AllianceDonation.test.ts` with 5
test cases covering donation scenarios after alliance formation (reply
and mutual request flows)
- All existing tests pass (323 total)

## Please complete the following:

- [x] I have added screenshots for all UI updates (N/A - backend logic
fix only)
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file (N/A - no user-facing text
changes)
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced


Discord: loacky
GitHub: @LoackyBit

---------

Co-authored-by: Evan <evanpelle@gmail.com>
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.

Unable to donate troops/gold between human players after forming an alliance

3 participants