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(sozo): model get not using prefixes #2867

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

emarc99
Copy link

@emarc99 emarc99 commented Jan 6, 2025

Description

Related issue

Closes #2835

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

  • New Features

    • Enhanced key input handling for model retrieval
    • Added support for short string key parsing with sstr: prefix
  • Bug Fixes

    • Improved input parsing for model keys
    • Added quote trimming for short string inputs
  • Improvements

    • More flexible and robust key specification process for model commands

Copy link

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request introduces improvements to the sozo model get command by enhancing key parsing capabilities. The changes focus on adding support for more flexible input formats, specifically introducing a new sstr: prefix for short string inputs. A custom key parser is implemented to handle different input types, including hexadecimal and short string representations, making the command more versatile and user-friendly.

Changes

File Change Summary
bin/sozo/src/commands/model.rs - Updated ModelCommand::Get to accept keys as a String instead of Vec<Felt>
- Added model_key_parser function to handle key parsing with prefix support
crates/dojo/world/src/config/calldata_decoder.rs - Modified decode_single_calldata to handle quoted short string inputs by trimming quotes

Assessment against linked issues

Objective Addressed Explanation
Support prefix parsing for sozo model get
Allow string input with sstr: prefix

Possibly related PRs

Suggested reviewers

  • glihm

Ohayo, sensei! I've reviewed the changes and they look like a solid solution to the prefix parsing challenge for the sozo model get command. The implementation provides a flexible approach to handling different input formats, addressing the specific issue raised in the linked bug report.


📜 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 018847f and 70a8da2.

📒 Files selected for processing (1)
  • crates/dojo/world/src/config/calldata_decoder.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/world/src/config/calldata_decoder.rs

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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: 0

🧹 Nitpick comments (2)
bin/sozo/src/commands/model.rs (2)

113-116: Ohayo sensei! Nice usage of multi-line help docs.
This enhanced help text clearly explains how to supply comma-separated values with various prefixes. The additional detail helps users form correct input on the command line.


214-215: Sensei, consider robust error handling.
You raise an error if decode_calldata fails. That's good. If you anticipate user mistakes frequently, you might provide a more descriptive error or usage example upon failure.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ddee9e and 69d83d0.

📒 Files selected for processing (3)
  • bin/sozo/src/commands/auth.rs (3 hunks)
  • bin/sozo/src/commands/mod.rs (1 hunks)
  • bin/sozo/src/commands/model.rs (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • bin/sozo/src/commands/mod.rs
🔇 Additional comments (8)
bin/sozo/src/commands/model.rs (4)

3-3: Ohayo sensei! Great addition for the decoder import.
The import of calldata_decoder sets the foundation for decoding user input with flexible prefixes. This is useful for supporting short-string notation and conventional felts.


117-117: Sensei, verify the impact of switching from Vec to String.
Swapping from Vec<Felt> to String is beneficial for user-friendly input, but ensure that usage sites (including tests and other commands) are updated accordingly.


126-128: Ohayo sensei! Thorough documentation for the block argument.
No issues spotted; the docstring clarifies the usage of a block number or a pending block. Looks good to merge.


233-264: Ohayo sensei! Impressive test coverage for short strings and hex validation.
Testing both short-string prefixes and hex-to-decimal conversions is crucial. The tests confirm that your new input format is working as intended.

bin/sozo/src/commands/auth.rs (4)

245-249: Sensei, good clarity in the resource filtering condition.
The explicit if checks improve readability compared to a one-liner.


258-262: Ohayo sensei! Consistent approach for filtering owners.
Following the same pattern for owners and writers helps maintain a uniform code style.


314-320: Sensei, verifying name resolution for external writers.
You map resource selectors to hex strings or “World” if they match WORLD. This is clear. Make sure there’s no confusion about which resources are truly global.


321-327: Ohayo sensei! Good consistency in naming for external owners.
Repeating the same logic for owners ensures symmetrical permission logic for resource tagging.

@emarc99 emarc99 marked this pull request as draft January 6, 2025 09:07
@emarc99 emarc99 marked this pull request as ready for review January 6, 2025 09:35
@emarc99 emarc99 marked this pull request as draft January 6, 2025 13:39
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thank you for taking the time on this @emarc99!

Some comments, please don't hesitate if you have any questions.

Comment on lines 113 to 116
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\",sstr:\"misty\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]
Copy link
Collaborator

Choose a reason for hiding this comment

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

In the case of the keys, only one felt long serialized type are supported (everything that can fit in one felt).

That's great you've only put the sstr which is the only one supported actually.

Suggested change
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\",sstr:\"misty\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]
#[arg(help = "Comma separated values e.g., \
0x12345,0x69420,sstr:\"hello\". Supported prefixes:\n \
- sstr: A cairo short string\n \
- no prefix: A cairo felt")]

Copy link
Collaborator

Choose a reason for hiding this comment

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

We may add a check that only this prefix is actually used, wdyt?

Copy link
Author

Choose a reason for hiding this comment

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

Yeah, the check will be quite useful. I'll add it.

@@ -222,3 +230,35 @@ impl ModelArgs {
})
}
}

#[cfg(test)]
mod tests {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Thank you for thinking about tests.

In the current context, this test should already be covered into the calldata_decoder file. We can remove this one. 👍

You could write a test on the argument though.

Copy link
Author

Choose a reason for hiding this comment

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

Awesome, that'll be the better option. These tests were meant to go away eventually.

Copy link
Collaborator

Choose a reason for hiding this comment

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

That's actually good having those here for the command, thank you!

Copy link
Author

Choose a reason for hiding this comment

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

My pleasure, sir.

@glihm
Copy link
Collaborator

glihm commented Jan 8, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

@emarc99
Copy link
Author

emarc99 commented Jan 8, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

@glihm
Copy link
Collaborator

glihm commented Jan 15, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

Hey @emarc99, let me know if you have any blocker on that.

@emarc99
Copy link
Author

emarc99 commented Jan 16, 2025

Don't forget to run the scripts/ for the linter. They are in the repository scripts/ folder.

Noted, sir.

Hey @emarc99, let me know if you have any blocker on that.

The script rust_fmt.sh keep failing to run. So I applied cargo fmt on file directly.

@emarc99 emarc99 marked this pull request as ready for review January 16, 2025 16:27
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

🧹 Nitpick comments (3)
bin/sozo/src/commands/model.rs (2)

113-117: Ohayo, sensei! Clarify the help message formatting

The help message for the keys argument could be formatted for better readability in the command-line interface. Adjusting the indentation and line breaks will make the supported prefixes clearer to the user.

Apply this diff to improve the formatting:

     #[arg(value_name = "KEYS")]
     #[arg(value_delimiter = ',')]
-    #[arg(help = "Comma separated values e.g., \
-                         0x12345,0x69420,sstr:\"hello\". Supported prefixes:\n  \
-                         - sstr: A cairo short string\n  \
-                         - no prefix: A cairo felt")]
+    #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\".\nSupported prefixes:\n  - sstr: A Cairo short string\n  - no prefix: A Cairo felt")]

136-137: Ohayo, sensei! Enhance error message for unsupported prefixes

If a user provides an unsupported prefix, the error message could be more informative. Including the invalid prefix in the message and listing supported prefixes will guide the user towards correct usage.

Apply this diff to improve the error message:

     if s.contains(':') && !s.starts_with("sstr:") {
-        anyhow::bail!("Only 'sstr:' prefix is supported for model keys");
+        anyhow::bail!("Unsupported prefix in key '{}'. Only 'sstr:' prefix is supported for model keys.", s);
     }
crates/dojo/world/src/config/calldata_decoder.rs (1)

164-171: Ohayo, sensei! Handle mismatched quotes in sstr decoding

When decoding sstr prefixed values, the current implementation trims quotes if they are present but doesn't validate if they are correctly paired. This could lead to unexpected behavior with mismatched or unpaired quotes. Consider adding validation to check for properly matched quotes and provide an informative error message if they are not.

Apply this diff to add quote validation:

     "sstr" => {
         let value = if value.starts_with('"') && value.ends_with('"') {
             value.trim_matches('"')
+        } else if value.starts_with('"') || value.ends_with('"') {
+            return Err(CalldataDecoderError::ParseError("Mismatched quotes in 'sstr' value.".to_string()));
         } else {
             value
         };
         ShortStrCalldataDecoder.decode(value)?
     },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69d83d0 and fee9cfb.

📒 Files selected for processing (3)
  • bin/sozo/src/commands/mod.rs (1 hunks)
  • bin/sozo/src/commands/model.rs (4 hunks)
  • crates/dojo/world/src/config/calldata_decoder.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • bin/sozo/src/commands/mod.rs
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

243-303: Ohayo, sensei! Excellent addition of argument parsing tests

Great job adding tests for the Get command's argument parsing. The tests cover both hexadecimal and sstr prefixed inputs, ensuring robust handling of various input formats.

Comment on lines 139 to 141
let felts = calldata_decoder::decode_calldata(s)?;
Ok(felts[0])
}
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! Prevent potential index out-of-bounds panic

The code assumes that felts contains at least one element. If decode_calldata(s) returns an empty vector, accessing felts[0] will cause a panic. Consider adding a check to ensure felts is not empty before accessing the first element.

Apply this diff to handle the potential empty felts:

     let felts = calldata_decoder::decode_calldata(s)?;
+    if felts.is_empty() {
+        anyhow::bail!("Failed to parse key '{}': no values returned.", s);
+    }
     Ok(felts[0])
📝 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
let felts = calldata_decoder::decode_calldata(s)?;
Ok(felts[0])
}
let felts = calldata_decoder::decode_calldata(s)?;
if felts.is_empty() {
anyhow::bail!("Failed to parse key '{}': no values returned.", s);
}
Ok(felts[0])
}

@emarc99 emarc99 requested a review from glihm January 16, 2025 16:58
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

For the linting, you can use:

bash scripts/rust_fmt.sh --fix

Comment on lines +165 to +170
let value = if value.starts_with('"') && value.ends_with('"') {
value.trim_matches('"')
} else {
value
};
ShortStrCalldataDecoder.decode(value)?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Wasn't the quotes already taken in account? Would you mind explaining the choice here.
Maybe this should land in decode function in case we have some?

Copy link
Author

Choose a reason for hiding this comment

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

Second part of test kept failing with below error;

running 1 test
test commands::model::tests::test_model_get_argument_parsing ... FAILED

failures:

---- commands::model::tests::test_model_get_argument_parsing stdout ----
thread 'commands::model::tests::test_model_get_argument_parsing' panicked at bin/sozo/src/commands/model.rs:296:13:assertion `left == right` failed
  left: [0x54cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5, 0x226d6973747922]
 right: [0x54cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5, 0x6d69737479]
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    commands::model::tests::test_model_get_argument_parsing

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 51 filtered out; finished in 1.30s

error: test failed, to rerun pass `--bin sozo`

Copy link
Author

Choose a reason for hiding this comment

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

The issue wanted below to work.

sozo --profile sepolia model get Account 0x054cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5,sstr:"misty"

Maybe what was intended was below, without quotes around the short string; if so I'll remove the check for trimming quotes.

sozo --profile sepolia model get Account 0x054cb935d86d80b5a0a6e756edf448ab33876d01dd2b07a2a4e63a41e06d0ef5,sstr:misty

@@ -222,3 +230,35 @@ impl ModelArgs {
})
}
}

#[cfg(test)]
mod tests {
Copy link
Collaborator

Choose a reason for hiding this comment

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

That's actually good having those here for the command, thank you!

@emarc99
Copy link
Author

emarc99 commented Jan 16, 2025

For the linting, you can use:

bash scripts/rust_fmt.sh --fix

There's progress with this command. Will apply it soon and pr.

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 (3)
bin/sozo/src/commands/model.rs (3)

113-115: Ohayo! Consider improving help text readability

The help text could be more readable with consistent indentation and alignment:

-        #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\". Supported \
-                      prefixes:\n  - sstr: A cairo short string\n  - no prefix: A cairo felt")]
+        #[arg(help = "Comma separated values e.g., 0x12345,0x69420,sstr:\"hello\".\n\
+                      Supported prefixes:\n\
+                      - sstr: A cairo short string\n\
+                      - no prefix: A cairo felt")]

130-140: Ohayo! Consider additional input validation

The parser handles prefix validation and empty results well. Consider adding validation for malformed inputs:

 fn model_key_parser(s: &str) -> Result<Felt> {
+    if s.trim().is_empty() {
+        anyhow::bail!("Empty key is not allowed");
+    }
     if s.contains(':') && !s.starts_with("sstr:") {
         anyhow::bail!("Only 'sstr:' prefix is supported for model keys");
     }
     let felts = calldata_decoder::decode_calldata(s)?;
     if felts.is_empty() {
         anyhow::bail!("Failed to parse key '{}': no values returned.", s);
     }
     Ok(felts[0])
 }

241-303: Ohayo! Consider adding more edge case tests

The test coverage is good, but could be enhanced with additional edge cases:

#[test]
fn test_model_get_edge_cases() {
    // Test empty input
    let result = TestCommand::try_parse_from(["model", "get", "Account", ""]);
    assert!(result.is_err());

    // Test malformed sstr (missing quotes)
    let result = TestCommand::try_parse_from(["model", "get", "Account", "sstr:hello"]);
    assert!(result.is_err());

    // Test malformed hex
    let result = TestCommand::try_parse_from(["model", "get", "Account", "0xZZZ"]);
    assert!(result.is_err());
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0dac4 and 7d3d719.

📒 Files selected for processing (2)
  • bin/sozo/src/commands/model.rs (4 hunks)
  • crates/dojo/world/src/config/calldata_decoder.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/dojo/world/src/config/calldata_decoder.rs
🔇 Additional comments (1)
bin/sozo/src/commands/model.rs (1)

3-3: Ohayo, sensei! Import looks good!

The calldata_decoder import is correctly added and aligns with the new key parsing functionality.

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)
bin/sozo/src/commands/mod.rs (1)

132-149: Clean error handling improvement, sensei!

The version check error handling is now more precise about manifest locations and handles both regular and virtual workspaces consistently. Nice work!

Consider making the error messages even more user-friendly by adding a hint about how to fix the version mismatch:

-                    "Found dojo-core version mismatch: expected {}. Please verify your dojo \
-                     dependency in {}",
+                    "Found dojo-core version mismatch: expected {}. Please update your dojo \
+                     dependency to the expected version in {} (hint: update the tag in your dependency)",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3d719 and 018847f.

📒 Files selected for processing (1)
  • bin/sozo/src/commands/mod.rs (3 hunks)
🔇 Additional comments (2)
bin/sozo/src/commands/mod.rs (2)

108-108: Verify Hash command's config independence, sensei!

The Hash command no longer uses the config parameter. This change looks intentional and aligns with the testing comment, but let's verify that the Hash command implementation doesn't require any config parameters.


50-51: Ohayo! Verify if Execute command functionality has changed.

The documentation change from "Execute one or several systems" to "Execute a system" suggests a breaking change in functionality. Let's verify if this reflects an actual implementation change.

@emarc99 emarc99 requested a review from glihm January 17, 2025 18:55
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Hey @emarc99, thank you for your patience and sorry for the delay.

So lately we have relaxed the keys constraint, so anything can be a key (if it's serializable). Would you mind updating the PR to support all the prefixes? :)

Also, the quotes shouldn't be an issue, but let me know how it goes.

@emarc99
Copy link
Author

emarc99 commented Jan 21, 2025

Hey @emarc99, thank you for your patience and sorry for the delay.

So lately we have relaxed the keys constraint, so anything can be a key (if it's serializable). Would you mind updating the PR to support all the prefixes? :)

Also, the quotes shouldn't be an issue but let me know how it goes.

Alright, I'll update the PR accordingly, sir.

@glihm
Copy link
Collaborator

glihm commented Jan 23, 2025

Hey @emarc99, thank you for your patience and sorry for the delay.
So lately we have relaxed the keys constraint, so anything can be a key (if it's serializable). Would you mind updating the PR to support all the prefixes? :)
Also, the quotes shouldn't be an issue but let me know how it goes.

Alright, I'll update the PR accordingly, sir.

Thank you, let me know if you have any questions. 👍

@glihm
Copy link
Collaborator

glihm commented Jan 27, 2025

All good @emarc99 or do you still need some feedback? Let me know if you're blocked.

@emarc99
Copy link
Author

emarc99 commented Jan 27, 2025

All good @emarc99 or do you still need some feedback? Let me know if you're blocked.

Yea, I am running tests. I'll update in less than 24 hours for some feedback if tests keep failing, sir.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] Sozo model get is not using prefixes
2 participants