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: where type issues #958

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

fix: where type issues #958

wants to merge 2 commits into from

Conversation

Yohe-Am
Copy link
Contributor

@Yohe-Am Yohe-Am commented Jan 10, 2025

  • Fixes issues with type counts.

Migration notes


  • The change comes with new or modified tests
  • Hard-to-understand functions have explanatory comments
  • End-user documentation is updated to reflect the change

Summary by CodeRabbit

  • New Features

    • Enhanced duplicate detection mechanism for type graphs
    • Improved type identification and relationship tracking
  • Refactor

    • Updated model identifier handling in type generation
    • Modified key management for skip models from type-based to string-based keys
  • Bug Fixes

    • Streamlined type duplicate detection logic
    • Improved error handling for unsupported type scenarios

@Yohe-Am Yohe-Am requested a review from a team January 10, 2025 06:40
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

📝 Walkthrough

Walkthrough

The pull request introduces changes in two files: src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs and tools/list-duplicates.ts. In the Rust file, the Where struct's skip_models field type is modified from using TypeId to String keys, changing how model identifiers are stored and accessed. In the TypeScript file, a new listDuplicatesEnhanced function is added to improve duplicate type detection in a type graph, with the existing listDuplicates function now calling this new implementation.

Changes

File Change Summary
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs - Changed skip_models field type from BTreeMap<TypeId, String> to BTreeMap<String, String>
- Updated nested method to use model name as key
- Modified generate method to lookup using model type name
- Simplified suffix generation logic in name method
tools/list-duplicates.ts - Added new listDuplicatesEnhanced function for advanced duplicate type detection
- Modified listDuplicates to call listDuplicatesEnhanced
- Enhanced duplicate tracking with reducedSetMap and reducedSet

Sequence Diagram

sequenceDiagram
    participant LD as listDuplicates
    participant LDE as listDuplicatesEnhanced
    participant TG as TypeGraphDS

    LD->>LDE: Call with TypeGraph
    LDE->>TG: Analyze Type Graph
    LDE-->>LDE: Detect Duplicates
    LDE-->>LDE: Build Reduced Set Map
    LDE->>LDE: Process Type Relationships
    LDE-->>LD: Return Duplicate Information
Loading

The sequence diagram illustrates the new flow where listDuplicates now delegates to listDuplicatesEnhanced, which performs a more comprehensive analysis of the type graph to detect and manage duplicate types.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

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

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
Contributor

@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

🧹 Nitpick comments (2)
tools/list-duplicates.ts (2)

29-30: Remove unused variable 'theWheres' or uncomment the code that uses it

The variable theWheres is populated but not utilized since the code that uses it (lines 248-253) is commented out. This may cause confusion and unnecessary memory usage.

Consider either removing the unused variable and related code if it's no longer needed, or uncommenting and updating the code block to utilize theWheres appropriately.

Also applies to: 248-253


124-142: Clean up commented-out code in 'suffix2' generation

In the name method, there is a block of commented-out code regarding nested_suffix and processing of keys (lines 124-142). Keeping unused code can reduce readability and maintainability.

Consider removing the commented-out code to clean up the method:

            let suffix2 = if !self.skip_models.is_empty() {
-                /* let nested_suffix = if self.aggregates {
-                    "_where_with_aggregates"
-                } else {
-                    "_where"
-                }; */

                let mut keys = self
                    .skip_models
                    .keys()
                    .cloned()
                    .collect::<Vec<_>>();
                keys.sort();
                format!("_excluding_{}", keys.join("_and_"))
            } else {
                "".to_string()
            };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d8dac2 and 2b53581.

⛔ Files ignored due to path filters (20)
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__Post__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__User__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where Post.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where User.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (4 hunks)
  • tools/list-duplicates.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
  • GitHub Check: test-full
  • GitHub Check: pre-commit
🔇 Additional comments (2)
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (2)

20-20: Assess the impact of changing 'skip_models' key from 'TypeId' to 'String'

Changing the key type of skip_models from TypeId to String (line 20) may have performance implications due to the costlier string comparisons and potential for key collisions if different models share the same name. In line 64, when accessing skip_models, ensure that the model names are unique and consistent.

Please confirm that model names are unique identifiers in this context and that this change won't introduce unintended side effects. If necessary, consider using a combination of TypeId and String or another unique identifier to maintain performance and correctness.

Also applies to: 64-64


Line range hint 78-83: Ensure 'edges' correctly accumulates dependencies in 'function' case

Similar to the issue in listDuplicatesEnhanced, verify that in the generate method, when constructing edges, the dependencies for 'function' types include both input and output without overwriting. This ensures proper traversal and processing of type relations.

Review the logic around building edges to confirm that both input and output dependencies are accounted for correctly.

Comment on lines +79 to +82
edges.set(idx, [structure.input]);
addToRevEdges(structure.input, idx);
edges.set(idx, [structure.output]);
addToRevEdges(structure.output, idx);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix overwriting of edges in 'function' case to include both input and output edges

In the 'function' case of the switch statement, the code calls edges.set(idx, ...) twice, which overwrites the previous value. As a result, only the last edge is stored, and the input edge is lost. This can lead to incorrect graph traversal or incomplete processing of types.

Apply this diff to fix the issue:

case "function":
-  edges.set(idx, [structure.input]);
-  addToRevEdges(structure.input, idx);
-  edges.set(idx, [structure.output]);
+  edges.set(idx, [structure.input, structure.output]);
  addToRevEdges(structure.input, idx);
  addToRevEdges(structure.output, idx);
  break;
📝 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
edges.set(idx, [structure.input]);
addToRevEdges(structure.input, idx);
edges.set(idx, [structure.output]);
addToRevEdges(structure.output, idx);
edges.set(idx, [structure.input, structure.output]);
addToRevEdges(structure.input, idx);
addToRevEdges(structure.output, idx);

@@ -32,7 +32,7 @@ impl Where {

fn nested(&self, name: &str, model_id: TypeId) -> Self {
let mut skip_models = self.skip_models.clone();
skip_models.insert(self.model_id, name.to_string());
skip_models.insert(self.model_id.name().unwrap().unwrap(), name.to_string());
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential errors without double 'unwrap()' calls to prevent panics

In lines 35 and 122, self.model_id.name().unwrap().unwrap() is used. The double unwrap() may lead to panics if the Option or Result values are None or Err. To ensure robustness, consider handling these cases properly.

Apply this diff to safely handle the potential None or Err values:

-            skip_models.insert(self.model_id.name().unwrap().unwrap(), name.to_string());
+            let model_name = self.model_id.name()?.unwrap_or_default();
+            skip_models.insert(model_name, name.to_string());

...

-        let model_name = self.model_id.name().unwrap().unwrap();
+        let model_name = self.model_id.name()?.unwrap_or_default();

Alternatively, you can handle the Option and Result explicitly:

if let Some(Ok(model_name)) = self.model_id.name() {
    skip_models.insert(model_name.clone(), name.to_string());
} else {
    // Handle the error or return early
}

Also applies to: 122-122

@luckasRanarison
Copy link
Contributor

Awesome, the vivavox typegraph size went down to 1.4mb!

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 77.72%. Comparing base (3d8dac2) to head (2b53581).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #958   +/-   ##
=======================================
  Coverage   77.72%   77.72%           
=======================================
  Files         154      154           
  Lines       19154    19154           
  Branches     1930     1930           
=======================================
  Hits        14888    14888           
  Misses       4243     4243           
  Partials       23       23           

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

// .unwrap_or(name)
// })
.collect::<Vec<_>>();
keys.sort();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Debugging is fun 🤕

Comment on lines 21 to +26

export function listDuplicatesEnhanced(tg: TypeGraphDS, _rootIdx = 0) {
// to <- from
const reducedSetMap = new Map<number, number[]>();
const reducedSet = new Set<number>();
let cycleNo = 0;
Copy link
Contributor

Choose a reason for hiding this comment

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

🔥

Comment on lines -110 to +116
└── [posts]: optional #81
└── item: union #80
├── variant_0: struct #75
│ └── [every]: optional #74
│ └── item: struct 'Post_where_excluding_User' #73
│ ├── [author]: optional #71
│ │ └── item: struct 'User_where_excluding_Post_and_User' #70
│ │ ├── [id]: optional #58
│ │ │ └── item: &_prisma_integer_filter_ex #16
│ │ ├── [name]: optional #59
│ │ │ └── item: &_prisma_string_filter_ex #33
│ │ └── [posts]: optional #68
│ │ └── item: union #67
│ │ ├── variant_0: struct #62
│ │ │ └── [every]: optional #61
│ │ │ └── item: &Post_where_excluding_User #60
│ │ ├── variant_1: struct #64
│ │ │ └── [some]: optional #63
│ │ │ └── item: &Post_where_excluding_User #60
│ │ └── variant_2: struct #66
│ │ └── [none]: optional #65
│ │ └── item: &Post_where_excluding_User #60
└── [posts]: optional #68
└── item: union #67
├── variant_0: struct #62
│ └── [every]: optional #61
│ └── item: struct 'Post_where_excluding_User' #60
│ ├── [author]: optional #58
│ │ └── item: &User_where #57
Copy link
Contributor

Choose a reason for hiding this comment

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

Neat!

Copy link
Contributor

@michael-0acf4 michael-0acf4 left a comment

Choose a reason for hiding this comment

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

Very good stuff!

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.

3 participants