Skip to content

Fixes a race condition in trigger_trap() that allowed traps to be triggered multiple times simultaneously.#195

Merged
KevinMB0220 merged 3 commits intoSunsetLabs-Game:mainfrom
truthixify:fix-178
Aug 29, 2025
Merged

Fixes a race condition in trigger_trap() that allowed traps to be triggered multiple times simultaneously.#195
KevinMB0220 merged 3 commits intoSunsetLabs-Game:mainfrom
truthixify:fix-178

Conversation

@truthixify
Copy link
Contributor

@truthixify truthixify commented Aug 28, 2025

Changes

  • Implemented atomic read-modify-write for trap state
  • Added versioning/locking to prevent concurrent modifications
  • Ensured traps can only trigger once per activation
  • Added tests for concurrent trigger attempts

Closes #178

Summary by CodeRabbit

  • Bug Fixes
    • Improved trap triggering robustness under concurrent access, ensuring inactive traps don’t alter state and return no damage.
  • Documentation
    • Added clarifying comments explaining trap activation checks and deactivation behavior.
  • Tests
    • Introduced tests covering concurrent trap triggers and repeated triggers on inactive traps, validating expected outcomes.
  • Style
    • Minor formatting cleanup for readability.

No changes to public APIs.

@coderabbitai
Copy link

coderabbitai bot commented Aug 28, 2025

Walkthrough

Updates include formatting in enemy model, comment clarifications in trap implementation, altered control flow in store’s trigger_trap to handle zero-damage returns without writes, and new tests verifying concurrent-trigger handling and inactive-trap behavior. No public APIs changed.

Changes

Cohort / File(s) Summary of changes
Formatting-only (Enemy)
contract/src/models/enemy.cairo
Reformatted Ok path to multiline parenthesized struct construction; no logic changes.
Comment clarifications (Trap)
contract/src/models/trap.cairo
Added comments explaining is_active check and deactivation; behavior unchanged.
Concurrency-aware trap trigger (Store)
contract/src/store.cairo
Updated trigger_trap to branch on TrapImpl::trigger’s returned damage: early-return 0 without storage write if damage is 0; otherwise write updated inactive trap and return damage. Added explanatory comments.
Tests for concurrency/inactivity
contract/src/tests/test_store.cairo
Added tests covering concurrent access (one triggers, second returns 0) and re-triggering inactive trap; asserts final inactive state and expected panics.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant S as Store::trigger_trap
  participant T as TrapImpl::trigger
  participant ST as Storage

  C->>S: trigger_trap(trap_id, pos)
  S->>ST: load trap
  S->>S: validate active & in range
  S->>T: trigger(trap)
  T-->>S: damage (0 or >0), trap' (possibly deactivated)

  alt damage == 0 (already inactive)
    S-->>C: return 0 (no write)
  else damage > 0
    S->>ST: write trap' (inactive)
    S-->>C: return damage
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • KevinMB0220

Poem

I thump my paws in tidy delight,
Traps snap once—then yield to night.
One bang, no double bite—hooray!
Stores now know when not to write.
Enemy stands, just spaced “just right.”
Tests hop in, keep races tight.
🐇 Click—safe, and out of sight.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
contract/src/store.cairo (2)

293-314: Zero-damage path is effectively unreachable due to pre-check; remove the panic-on-inactive to match intended semantics.

You assert active on Line 295, which will panic before reaching the “damage == 0” branch for already-inactive traps. To implement the documented “return 0 when inactive” behavior (and support concurrent attempts), early-return on inactive and avoid panicking.

Apply within this hunk:

 fn trigger_trap(ref self: Store, trap_id: u32, enemy_pos: Vec2) -> u16 {
     let mut trap = self.read_trap(trap_id);
-    assert(trap.is_active == true, 'Trap not active');
-    assert(TrapImpl::check_trigger(@trap, enemy_pos) == true, 'Enemy not in range');
+    // If the trap is already inactive (e.g., another tx triggered it), do nothing.
+    if trap.is_active == false {
+        return 0;
+    }
+    // Still verify range before consuming.
+    assert(TrapImpl::check_trigger(@trap, enemy_pos) == true, 'Enemy not in range');
 
     // The TrapImpl::trigger function will set is_active to false and return the damage.
     // If it was already inactive (e.g., another transaction got there first), it returns 0.
     let damage = TrapImpl::trigger(ref trap);
 
     // If damage is 0, it means the trap was not active when TrapImpl::trigger was called.
     // This could happen if a concurrent transaction successfully triggered and updated
     // the global state to inactive before this transaction's TrapImpl::trigger was executed.
     // In this scenario, we just return 0, as no new damage should be dealt.
     if damage == 0 {
         return 0;
     }
 
     // This transaction successfully triggered the trap and received non-zero damage.
     // Write the now-inactive trap state back to the world.
     self.write_trap(@trap);
     damage
 }

293-314: Implement or remove “atomic RMW”/versioning: PR description references atomic read-modify-write and versioning/locking, but no version field or CAS/atomic operations exist on Trap (see contract/src/models/trap.cairo). Either add the intended optimistic-concurrency mechanism or update the description.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 38d6dd5 and ff69c0e.

📒 Files selected for processing (4)
  • contract/src/models/enemy.cairo (1 hunks)
  • contract/src/models/trap.cairo (1 hunks)
  • contract/src/store.cairo (1 hunks)
  • contract/src/tests/test_store.cairo (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build and Test
🔇 Additional comments (2)
contract/src/models/enemy.cairo (1)

71-84: LGTM: formatting-only change.

Struct construction reformatted; no semantic impact.

contract/src/models/trap.cairo (1)

62-64: Helpful inline docs; behavior remains idempotent.

Comments clearly state trigger() returns 0 when already inactive and deactivates otherwise. No code-path changes.

Also applies to: 68-70

Comment on lines +1478 to +1508
#[test]
#[should_panic(expected: 'Trap not active')]
fn test_store_trigger_trap_concurrent_access() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store_tx1: Store = StoreTrait::new(world.clone()); // Simulate transaction 1
let mut store_tx2: Store = StoreTrait::new(world.clone()); // Simulate transaction 2

let trap = create_sample_trap();
store_tx1.place_trap(trap); // Place trap using one store instance

let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius

// Scenario: Both transactions read the active trap, then try to trigger
// Transaction 1 triggers
let damage_tx1 = store_tx1.trigger_trap(1_u32, enemy_pos);

// Transaction 2 tries to trigger, but the trap is already inactive due to TX1
let damage_tx2 = store_tx2.trigger_trap(1_u32, enemy_pos);

// Assertions
assert(damage_tx1 == 50_u16, 'TX1 should deal 50 damage');
assert!(damage_tx2 == 0_u16, "TX2 should deal 0 damage due to race condition protection");

let final_trap_state = store_tx1.read_trap(1_u32);
assert!(final_trap_state.is_active == false, "Trap should be consumed after one trigger");

// Verify that the second store instance also reflects the inactive state
let final_trap_state_tx2 = store_tx2.read_trap(1_u32);
assert!(final_trap_state_tx2.is_active == false, "TX2 view should also show inactive trap");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Test mixes should_panic with follow-up assertions; unreachable assertions. Align with non-panicking “return 0” semantics.

If trigger_trap returns 0 on concurrent second trigger (recommended), drop the panic expectation.

-#[test]
-#[should_panic(expected: 'Trap not active')]
+#[test]
 fn test_store_trigger_trap_concurrent_access() {
@@
-    // Transaction 2 tries to trigger, but the trap is already inactive due to TX1
+    // Transaction 2 tries to trigger after TX1; should get 0 damage (inactive)
     let damage_tx2 = store_tx2.trigger_trap(1_u32, enemy_pos);
@@
-    // Verify that the second store instance also reflects the inactive state
+    // Verify that the second store instance also reflects the inactive state
📝 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.

Suggested change
#[test]
#[should_panic(expected: 'Trap not active')]
fn test_store_trigger_trap_concurrent_access() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store_tx1: Store = StoreTrait::new(world.clone()); // Simulate transaction 1
let mut store_tx2: Store = StoreTrait::new(world.clone()); // Simulate transaction 2
let trap = create_sample_trap();
store_tx1.place_trap(trap); // Place trap using one store instance
let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius
// Scenario: Both transactions read the active trap, then try to trigger
// Transaction 1 triggers
let damage_tx1 = store_tx1.trigger_trap(1_u32, enemy_pos);
// Transaction 2 tries to trigger, but the trap is already inactive due to TX1
let damage_tx2 = store_tx2.trigger_trap(1_u32, enemy_pos);
// Assertions
assert(damage_tx1 == 50_u16, 'TX1 should deal 50 damage');
assert!(damage_tx2 == 0_u16, "TX2 should deal 0 damage due to race condition protection");
let final_trap_state = store_tx1.read_trap(1_u32);
assert!(final_trap_state.is_active == false, "Trap should be consumed after one trigger");
// Verify that the second store instance also reflects the inactive state
let final_trap_state_tx2 = store_tx2.read_trap(1_u32);
assert!(final_trap_state_tx2.is_active == false, "TX2 view should also show inactive trap");
}
#[test]
fn test_store_trigger_trap_concurrent_access() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store_tx1: Store = StoreTrait::new(world.clone()); // Simulate transaction 1
let mut store_tx2: Store = StoreTrait::new(world.clone()); // Simulate transaction 2
let trap = create_sample_trap();
store_tx1.place_trap(trap); // Place trap using one store instance
let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius
// Scenario: Both transactions read the active trap, then try to trigger
// Transaction 1 triggers
let damage_tx1 = store_tx1.trigger_trap(1_u32, enemy_pos);
// Transaction 2 tries to trigger after TX1; should get 0 damage (inactive)
let damage_tx2 = store_tx2.trigger_trap(1_u32, enemy_pos);
// Assertions
assert(damage_tx1 == 50_u16, 'TX1 should deal 50 damage');
assert!(damage_tx2 == 0_u16, "TX2 should deal 0 damage due to race condition protection");
let final_trap_state = store_tx1.read_trap(1_u32);
assert!(final_trap_state.is_active == false, "Trap should be consumed after one trigger");
// Verify that the second store instance also reflects the inactive state
let final_trap_state_tx2 = store_tx2.read_trap(1_u32);
assert!(final_trap_state_tx2.is_active == false, "TX2 view should also show inactive trap");
}
🤖 Prompt for AI Agents
In contract/src/tests/test_store.cairo around lines 1478 to 1508, the test is
annotated with #[should_panic(expected: 'Trap not active')] but the body
contains follow-up assertions expecting the second trigger to return 0 and
verifying state, which makes those assertions unreachable; remove the
#[should_panic(...)] attribute and any panic expectation, treat the second
trigger as non-panicking returning 0, and keep/adjust the assertions to assert
damage_tx2 == 0 and final trap state checks so the test validates the intended
concurrent-access semantics.

Comment on lines +1510 to +1533
#[test]
#[should_panic(expected: 'Trap not active')]
fn test_store_trigger_trap_already_inactive_returns_zero() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store: Store = StoreTrait::new(world);

let mut trap = create_sample_trap();
store.place_trap(trap);

let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius

// First trigger works
let damage1 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage1 == 50_u16, "First trigger should deal damage");

// Second trigger (trap is already inactive) should return 0, no panic
let damage2 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage2 == 0_u16, "Second trigger on inactive trap should return 0");

let final_trap = store.read_trap(1_u32);
assert(final_trap.is_active == false, 'Trap should remain inactive');
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Same issue: drop should_panic; assert zero-damage instead.

Matches the intended idempotent trigger behavior.

-#[test]
-#[should_panic(expected: 'Trap not active')]
+#[test]
 fn test_store_trigger_trap_already_inactive_returns_zero() {
@@
-// Second trigger (trap is already inactive) should return 0, no panic
+// Second trigger (trap is already inactive) should return 0, no panic
📝 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.

Suggested change
#[test]
#[should_panic(expected: 'Trap not active')]
fn test_store_trigger_trap_already_inactive_returns_zero() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store: Store = StoreTrait::new(world);
let mut trap = create_sample_trap();
store.place_trap(trap);
let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius
// First trigger works
let damage1 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage1 == 50_u16, "First trigger should deal damage");
// Second trigger (trap is already inactive) should return 0, no panic
let damage2 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage2 == 0_u16, "Second trigger on inactive trap should return 0");
let final_trap = store.read_trap(1_u32);
assert(final_trap.is_active == false, 'Trap should remain inactive');
}
}
#[test]
fn test_store_trigger_trap_already_inactive_returns_zero() {
let player_system_contract_address = create_test_player_system();
let world = create_test_world(player_system_contract_address);
let mut store: Store = StoreTrait::new(world);
let mut trap = create_sample_trap();
store.place_trap(trap);
let enemy_pos = Vec2 { x: 12_u32, y: 16_u32 }; // Within radius
// First trigger works
let damage1 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage1 == 50_u16, "First trigger should deal damage");
// Second trigger (trap is already inactive) should return 0, no panic
let damage2 = store.trigger_trap(1_u32, enemy_pos);
assert!(damage2 == 0_u16, "Second trigger on inactive trap should return 0");
let final_trap = store.read_trap(1_u32);
assert(final_trap.is_active == false, "Trap should remain inactive");
}
}
🤖 Prompt for AI Agents
In contract/src/tests/test_store.cairo around lines 1510-1533, the test is
annotated with #[should_panic(expected: 'Trap not active')] but the intended
behavior is idempotent (second trigger returns 0, no panic); remove the
#[should_panic(...)] attribute, ensure the second call to store.trigger_trap
asserts == 0_u16, and keep the final assert that the trap remains inactive;
update any assertion string quotes to the file's convention if needed.

@KevinMB0220 KevinMB0220 merged commit 7ee738e into SunsetLabs-Game:main Aug 29, 2025
2 checks passed
@KevinMB0220 KevinMB0220 self-requested a review August 29, 2025 17:36
@truthixify truthixify deleted the fix-178 branch September 1, 2025 03:30
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.

feat: Race Condition in Trap Triggering System Allows Double-Triggering

2 participants

Comments