Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(torii-sqlite): deleting entity #2961

Merged
merged 7 commits into from
Jan 29, 2025
Merged

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Jan 28, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Updated entity deletion logic to simplify the deletion process.
    • Enhanced handling of model associations during entity removal operations.
    • Improved test coverage for entity deletion, ensuring related entities are also removed.
    • Adjusted assertions in tests to verify broader entity deletions instead of specific records.
    • Ensured integrity of entity model relations post-deletion.

Copy link

coderabbitai bot commented Jan 28, 2025

Walkthrough

Ohayo, sensei! The pull request modifies the delete_entity method in the SQLite implementation by adjusting how the model_id is formatted and altering the SQL query execution. The deletion now only affects the entity table, as the cascading delete from the entity_model table has been removed. Additionally, the DeleteEntityQuery struct has been updated to include the model_id, allowing it to be tracked internally without being part of the executed SQL command.

Changes

File Change Summary
crates/torii/sqlite/src/lib.rs Updated delete_entity method to format model_id as a string and simplified SQL query to only delete from the entity table.
crates/torii/sqlite/src/executor/mod.rs Added model_id field to DeleteEntityQuery struct and modified deletion logic to include model_id in the SQL query for the entity_model table.
crates/torii/indexer/src/test.rs Modified test_load_from_remote_del function to assert the deletion of entity model relations and entities instead of player configuration records.

Suggested Reviewers

  • glihm

Possibly Related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7a1b4b and a0afbc5.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/test.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/indexer/src/test.rs

🪧 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.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

  • 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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd7e42d and 4990c54.

📒 Files selected for processing (1)
  • crates/torii/sqlite/src/lib.rs (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/sqlite/src/lib.rs

[error] 449-453: Code formatting error: Vector arguments need to be formatted across multiple lines according to rustfmt style

🔇 Additional comments (1)
crates/torii/sqlite/src/lib.rs (1)

Line range hint 449-458: Implementation looks good!

The query correctly handles entity deletion by:

  1. Removing the entity from its model-specific table
  2. Cleaning up the entity-model mapping
  3. Using parameterized queries for security
🧰 Tools
🪛 GitHub Actions: ci

[error] 449-453: Code formatting error: Vector arguments need to be formatted across multiple lines according to rustfmt style

@@ -449,7 +449,7 @@ impl Sql {
WHERE entity_id = ? AND model_id = ?"
)
.to_string(),
vec![Argument::String(entity_id.clone()), Argument::String(format!("{:#x}", model_id))],
vec![Argument::String(entity_id.clone()), Argument::String(entity_id.clone()), Argument::String(format!("{:#x}", model_id))],
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ohayo sensei! Fix the formatting issue.

The vector arguments need to be formatted across multiple lines according to rustfmt style.

Apply this diff to fix the formatting:

-            vec![Argument::String(entity_id.clone()), Argument::String(entity_id.clone()), Argument::String(format!("{:#x}", model_id))],
+            vec![
+                Argument::String(entity_id.clone()),
+                Argument::String(entity_id.clone()),
+                Argument::String(format!("{:#x}", model_id)),
+            ],
📝 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
vec![Argument::String(entity_id.clone()), Argument::String(entity_id.clone()), Argument::String(format!("{:#x}", model_id))],
vec![
Argument::String(entity_id.clone()),
Argument::String(entity_id.clone()),
Argument::String(format!("{:#x}", model_id)),
],

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

🧹 Nitpick comments (1)
crates/torii/sqlite/src/executor/mod.rs (1)

478-482: Consider adding transaction rollback handling.

Ohayo, sensei! While the deletion logic is correct, we should ensure atomicity between the entity_model and entities table operations. If the subsequent operations fail, we might want to rollback this deletion.

Consider wrapping the operations in a transaction block or ensuring the existing transaction handling covers this case:

+ // Ensure this operation is part of the transaction
  sqlx::query("DELETE FROM entity_model WHERE entity_id = ? AND model_id = ?")
      .bind(entity.entity_id.clone())
      .bind(entity.model_id)
      .execute(&mut **tx)
      .await?;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4990c54 and c26c2f4.

📒 Files selected for processing (2)
  • crates/torii/sqlite/src/executor/mod.rs (2 hunks)
  • crates/torii/sqlite/src/lib.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/sqlite/src/lib.rs
🔇 Additional comments (2)
crates/torii/sqlite/src/executor/mod.rs (2)

56-56: LGTM! Addition of model_id field.

The addition of the model_id field to DeleteEntityQuery is well-structured and aligns with the entity-model relationship requirements.


Line range hint 478-524: Verify cascading delete behavior.

The deletion logic appears to handle the entity-model relationship correctly, but we should verify the behavior when:

  1. Multiple models reference the same entity
  2. The last model for an entity is deleted
✅ Verification successful

Ohayo sensei! The cascading delete implementation is correct and safe

The code properly handles both scenarios:

  • Multiple models can reference the same entity (ensured by the schema's unique constraint)
  • Entity deletion occurs only when its last model is removed (verified by the count check)

The implementation is protected by proper foreign key constraints and transaction boundaries, preventing any inconsistent states.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential orphaned entities or inconsistent states
ast-grep --pattern 'DELETE FROM entities WHERE id = $_'
rg -A 5 'DELETE FROM entity_model'

Length of output: 592


Script:

#!/bin/bash
# Check schema and other SQL operations
echo "=== Schema ==="
rg -A 10 'CREATE TABLE entities'
rg -A 10 'CREATE TABLE entity_model'

echo "=== Transaction handling ==="
ast-grep --pattern 'transaction|BEGIN|COMMIT|ROLLBACK'

echo "=== All operations on these tables ==="
rg -B 2 -A 2 'FROM entities|FROM entity_model'

Length of output: 6729

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

🔭 Outside diff range comments (1)
crates/torii/indexer/src/test.rs (1)

Ohayo sensei! The test flakiness is caused by a race condition between the executor task and database verification.

The issue occurs because:

  • The executor task runs independently via tokio::spawn
  • Database verification happens immediately after transaction completion
  • No synchronization exists between event processing and database state

To fix:

  • Add explicit synchronization between the executor and database verification
  • Consider using a channel to signal when event processing is complete
  • Add retry mechanism for database state verification
🔗 Analysis chain

Line range hint 1-1: Investigate and fix the flaky test behavior.

The test is marked as flaky with an #[ignore] attribute. Let's verify the potential race conditions or timing issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze the test execution patterns to identify flaky behavior.

# Search for async operations and potential race conditions
rg -A 5 "async|await|spawn|send|execute" crates/torii/indexer/src/test.rs

# Look for timing-related code
rg "sleep|timeout|delay" crates/torii/indexer/src/test.rs

# Check for similar patterns in related files
rg "test_load_from_remote" crates/torii/

Length of output: 14439


Script:

#!/bin/bash
# Compare the structure and patterns between the working and flaky tests

# Check for error handling patterns
rg "unwrap|expect|Error" crates/torii/indexer/src/test.rs

# Look for transaction retry or validation mechanisms
rg "retry|validate|confirm" crates/torii/indexer/src/

# Check the Executor implementation for race condition handling
ast-grep --pattern 'struct Executor {
  $$$
}'

# Look for similar test patterns in other files
rg "katana_runner::test.*async fn test" crates/torii/

Length of output: 7958


Script:

#!/bin/bash
# Examine Executor and event processing implementation

# Check Executor implementation
rg -A 10 "struct Executor" crates/torii/indexer/src/

# Look for event processing logic
rg -A 5 "process_range|process_event" crates/torii/indexer/src/

# Check for any synchronization mechanisms
rg "Mutex|RwLock|channel|sync" crates/torii/indexer/src/

# Look for transaction processing logic
rg -A 5 "TransactionWaiter" crates/torii/

Length of output: 19887

🧹 Nitpick comments (1)
crates/torii/indexer/src/test.rs (1)

308-309: Let's address the TODO comment about chronological testing.

The TODO comment suggests improving test chronology with Torii re-syncing. Consider implementing a test helper that allows controlling the sync process step by step.

Would you like me to help create a test helper that provides better control over the Torii syncing process?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c26c2f4 and 708c44d.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/test.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: docs
  • GitHub Check: ensure-wasm
  • GitHub Check: clippy
🔇 Additional comments (1)
crates/torii/indexer/src/test.rs (1)

303-306: Ohayo! The assertions look good, sensei!

The updated assertions correctly verify the entity deletion behavior by checking both the entity model relation and the entity itself.

Copy link

codecov bot commented Jan 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 57.19%. Comparing base (dd7e42d) to head (a0afbc5).
Report is 9 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2961      +/-   ##
==========================================
+ Coverage   56.71%   57.19%   +0.48%     
==========================================
  Files         420      423       +3     
  Lines       55557    56125     +568     
==========================================
+ Hits        31507    32100     +593     
+ Misses      24050    24025      -25     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@glihm glihm enabled auto-merge (squash) January 29, 2025 04:42
@glihm glihm disabled auto-merge January 29, 2025 04:45
@glihm glihm merged commit bc88734 into dojoengine:main Jan 29, 2025
15 checks passed
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