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

Add save and load functionality to MSONable #670

Merged
merged 3 commits into from
May 13, 2024

Conversation

matthewcarbone
Copy link
Contributor

This PR (re-)adds feature #653.

From #654:

In particular, it adds save and load methods to MSONable. These methods are flexible, and hook into the existing decoder and encoders in monty.json. They work by replacing any instance of an attribute that cannot be serialized by what is essentially a random hash reference to an object in a pickle file saved next to the json. This is then detected during loading, and swapped out for the object when the classmethod load is called.

One key difference from the (buggy) #654 is that the decoder was left unchanged. The encoder simply has a fallback when save is called, but otherwise behaves identically when the other MSONable methods are invoked.

When save is called and an un-MSONable object is encountered, it is swapped out for a unique identifier of the form:

{"@object_reference" : unique_id}

The object is then stored in a dictionary and pickled next to the saved json.

Any time "@object_reference" is encountered during rehydration, it is replaced by the pickled result. I look for these object references by recursively searching the loaded json file (lists and dictionaries only) and replacing these references with their objects before passing to from_dict.

Important

When I tried to implement this before, it came with some breaking bugs due to the fact that MSONable is used in other repositories in ways that weren't completely covered by the testing suite here. Here's an example. I was extra careful in this case to not touch any of the default behaviors, and to simply provide fallbacks where exceptions would otherwise be thrown, but that's never a guarantee!

@Andrew-S-Rosen let me know what you think!

Copy link

coderabbitai bot commented May 12, 2024

Walkthrough

The recent changes involve significant enhancements to JSON serialization capabilities in the monty/json.py module. These improvements include new features such as partial JSON generation, advanced saving/loading mechanisms, and a custom JSON encoder to handle unserializable objects. The corresponding test module, tests/test_json.py, has also been updated to validate these enhancements thoroughly.

Changes

File Changes Summary
monty/json.py Modified imports, introduced new methods for JSON handling, added MontyEncoder class with improvements to the default method, and included the jsanitize function.
tests/.../json.py Updated imports and expanded TestJson to incorporate tests for the newly added serialization and loading functionalities.

Recent Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 5b26904 and 077159b.
Files selected for processing (1)
  • tests/test_json.py (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/test_json.py

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

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

Out of diff range and nitpick comments (1)
tests/test_json.py (1)

394-454: The test_save_load method appropriately tests the new serialization functionalities. Consider adding more detailed comments within the test to explain the scenarios, especially the expected failures, to enhance readability and maintainability.

Comment on lines +20 to +21
from typing import Any, Dict
from uuid import UUID, uuid4
Copy link

Choose a reason for hiding this comment

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

Consider consolidating imports from the same module to maintain code cleanliness.

- from typing import Any, Dict
- from uuid import UUID, uuid4
+ from typing import Any, Dict
+ from uuid import UUID, uuid4

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.

Suggested change
from typing import Any, Dict
from uuid import UUID, uuid4
from typing import Any, Dict
from uuid import UUID, uuid4

@Andrew-S-Rosen
Copy link
Contributor

Andrew-S-Rosen commented May 12, 2024

@matthewcarbone: Thanks for revisiting this! And don't worry about the breakage from last time; the tests passed in monty, so you did everything you were supposed to do. You can't be expected to control for things in other repos, but I appreciate your flexibility on this.

This looks pretty safe to me! I did not find any issues with it breaking other repos this time around. 👍 For instance, see:

@matthewcarbone
Copy link
Contributor Author

@Andrew-S-Rosen Much appreciated, thanks for checking these things 👍

You can't be expected to control for things in other repos, but I appreciate your flexibility on this.

Thank you, but still I think I should've been a bit more careful last time. I simply didn't think about the case where people overwrite from_dict, but I certainly should have.

Anyways, I'll fix the linting, then we can proceed whenever/if you and @shyuep want to!

@matthewcarbone
Copy link
Contributor Author

@Andrew-S-Rosen it actually looks like the linting error is from a different file:

monty/functools.py:87: error: Argument 1 to "__call__" of "_Wrapper" has incompatible type "lazy_property"; expected "Callable[[VarArg(Never), KwArg(Never)], Never]"  [arg-type]

To be completely honest, I'm not that familiar with mypy, but if you'd like I can try to debug this.

@Andrew-S-Rosen
Copy link
Contributor

Yeah, it's the reason most of the PRs are currently failing (including mine in #669).

Admittedly, I am also not very familiar with mypy. We will have to wait for @shyuep to review the PRs when he has a moment.

@matthewcarbone
Copy link
Contributor Author

Sounds good. I'll stay in a holding pattern for now. 👍

@shyuep shyuep merged commit a1d241a into materialsvirtuallab:master May 13, 2024
4 of 5 checks passed
enum_values=enum_values,
recursive_msonable=recursive_msonable,
)
jsanitize(i, strict=strict, allow_bson=allow_bson, enum_values=enum_values)
Copy link
Contributor

Choose a reason for hiding this comment

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

I should have reviewed this better, but the recursive_msonable kwarg was removed in a few places. I'll make a patch.

Andrew-S-Rosen added a commit to Andrew-S-Rosen/monty that referenced this pull request May 13, 2024
In materialsvirtuallab#670, the `recursive_msonable` keyword argument was removed from the internal `jsanitize` calls. I have patched it back.
@matthewcarbone matthewcarbone deleted the mc-save-load-2 branch May 13, 2024 17:56
@matthewcarbone
Copy link
Contributor Author

Well that was fast, hoping for no bugs this time 😁

@Andrew-S-Rosen
Copy link
Contributor

Pinging @utf, @gpetretto, and @davidwaroquiers since this may be something that impacts jobflow/jobflow-remote development.

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.

None yet

3 participants