Skip to content

[opt] : optmize duplicate check memory usage for sql like insert into t1 selct from t2 - #17020

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
jensenojs:opt-16375-step2
Jun 21, 2024
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
jensenojs:opt-16375-step2

Conversation

@jensenojs

@jensenojs jensenojs commented Jun 20, 2024 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #16375 #16650 https://github.com/matrixorigin/MO-Cloud/issues/1574

What this PR does / why we need it:

在 #16847 之后重新打开fuzzy build在更小节点的逻辑, 在insert into A select from B的场景下, 如果B能够保证数据的唯一性, 在去重检测的时候可以避免内存的浪费


PR Type

Enhancement


Description

  • Enhanced insert statement initialization to handle unique column checks.
  • Updated DML utility functions to support unique column handling.
  • Optimized fuzzy filter logic for unique column checks.
  • Extended fuzzy filter types with new methods and fields for unique columns.
  • Adjusted fuzzy filter construction and pipeline instructions for unique columns.
  • Modified proto definitions to include unique column information.

Changes walkthrough 📝

Relevant files
Enhancement
10 files
build_constraint_util.go
Enhance insert statement initialization for unique column checks.

pkg/sql/plan/build_constraint_util.go

  • Modified initInsertStmt function to return an additional map for
    unique column checks.
  • Added logic to handle unique column checks during insert operations.
  • Introduced helper functions to find table definitions and unique
    columns.
  • +82/-27 
    build_dml_util.go
    Update DML utilities for unique column handling.                 

    pkg/sql/plan/build_dml_util.go

  • Updated buildInsertPlans and related functions to handle unique column
    checks.
  • Modified function signatures to include the new unique column map
    parameter.
  • +38/-13 
    filter.go
    Optimize fuzzy filter for unique column checks.                   

    pkg/sql/colexec/fuzzyfilter/filter.go

  • Optimized fuzzy filter logic to handle unique column checks.
  • Simplified build and probe phases based on unique column information.
  • +30/-63 
    types.go
    Extend fuzzy filter types for unique column support.         

    pkg/sql/colexec/fuzzyfilter/types.go

  • Added new fields and methods to support unique column checks in fuzzy
    filter arguments.
  • Introduced methods for adding and testing unique columns.
  • +60/-4   
    operator.go
    Adjust fuzzy filter construction for unique columns.         

    pkg/sql/compile/operator.go

  • Modified constructFuzzyFilter to consider unique column information.
  • Adjusted logic for determining build index based on unique column
    checks.
  • +14/-7   
    build_insert.go
    Enhance insert plan building for unique columns.                 

    pkg/sql/plan/build_insert.go

  • Updated buildInsert function to handle unique column checks.
  • Passed unique column map to buildInsertPlans.
  • +2/-2     
    scopeRemoteRun.go
    Support unique column checks in pipeline instructions.     

    pkg/sql/compile/scopeRemoteRun.go

  • Added support for unique column checks in pipeline instructions.
  • Updated conversion functions to handle new unique column field.
  • +6/-4     
    build_load.go
    Enhance load plan building for unique columns.                     

    pkg/sql/plan/build_load.go

  • Updated buildLoad function to handle unique column checks.
  • Passed unique column map to buildInsertPlans.
  • +1/-1     
    plan.proto
    Extend plan proto for unique column checks.                           

    proto/plan.proto

  • Added ifInsertFromUnique field to Node message.
  • Adjusted field numbers to accommodate new field.
  • +5/-3     
    pipeline.proto
    Extend pipeline proto for unique column checks.                   

    proto/pipeline.proto

    • Added IfInsertFromUnique field to FuzzyFilter message.
    +1/-0     

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @qodo-code-review

    Copy link
    Copy Markdown

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review [1-5] 4
    🧪 Relevant tests No
    🔒 Security concerns No
    ⚡ Key issues to review Possible Bug:
    The PR introduces a significant change in the handling of unique column checks in SQL insert operations. The new ifInsertFromUniqueColMap is used to track whether columns being inserted are from a unique column source. This map is populated and used across various functions, but there is a potential risk of incorrect behavior if the map is not correctly populated or if the logic interpreting this map is flawed. This needs thorough testing, especially edge cases where the uniqueness of source columns might be ambiguous.
    Performance Concern:
    The changes introduce additional complexity in the SQL insert logic by adding checks and mappings for unique columns. This could potentially impact performance, especially in scenarios with large datasets or complex insert operations. Performance benchmarks should be conducted to ensure that these changes do not degrade performance.

    @qodo-code-review

    Copy link
    Copy Markdown

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Performance
    Simplify the method by using a single return statement

    Optimize the GetIfInsertFromUnique method by using a single return statement.

    pkg/pb/pipeline/pipeline.pb.go [1767-1770]

    -if m != nil {
    -    return m.IfInsertFromUnique
    -}
    -return false
    +return m != nil && m.IfInsertFromUnique
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Simplifying the 'GetIfInsertFromUnique' method to a single return statement enhances code readability and efficiency.

    8
    Check the buildOnSink condition once to determine the flow and enhance performance

    To enhance performance, consider checking the buildOnSink condition once and using it to
    determine the flow, rather than checking it multiple times within the same function.

    pkg/sql/colexec/fuzzyfilter/filter.go [248-262]

    -buildOnSink := arg.ifBuildOnSink()
    -
    -if buildOnSink { // build fuzzy on sink scan
    +if buildOnSink := arg.ifBuildOnSink(); buildOnSink { // build fuzzy on sink scan
         if arg.IfInsertFromUnique {
             arg.add(pkCol)
         } else {
    -        err := arg.testAndAdd(proc, pkCol)
    -        if err != nil {
    +        if err := arg.testAndAdd(proc, pkCol); err != nil {
                 return err
             }
         }
     } else { // build on table scan
         arg.add(pkCol)
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    Why: The suggestion is valid as it optimizes the condition check by ensuring it's done once per function call. However, the improvement is minor and affects only the clarity and slight performance of the code.

    5
    Possible bug
    Add a nil check before accessing the map to prevent potential nil pointer dereference

    Add a check to ensure ifInsertFromUniqueColMap is not nil before accessing it to prevent
    potential nil pointer dereference.

    pkg/sql/plan/build_dml_util.go [1316-1317]

    -if insertFromUnique, exists := ifInsertFromUniqueColMap[indexdef.Parts[0]]; exists {
    +if ifInsertFromUniqueColMap != nil {
    +    if insertFromUnique, exists := ifInsertFromUniqueColMap[indexdef.Parts[0]]; exists {
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding a nil check before accessing 'ifInsertFromUniqueColMap' is crucial to prevent runtime errors due to nil pointer dereference, which is a significant improvement.

    8
    Enhancement
    Rename the boolean field to better reflect its purpose and improve readability

    Consider renaming the IfInsertFromUnique field to IsInsertFromUnique to better reflect its
    boolean nature and improve readability.

    pkg/pb/pipeline/pipeline.pb.go [1699]

    -IfInsertFromUnique   bool      `protobuf:"varint,5,opt,name=IfInsertFromUnique,proto3" json:"IfInsertFromUnique,omitempty"`
    +IsInsertFromUnique   bool      `protobuf:"varint,5,opt,name=IsInsertFromUnique,proto3" json:"IsInsertFromUnique,omitempty"`
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Renaming 'IfInsertFromUnique' to 'IsInsertFromUnique' improves readability by following common boolean naming conventions.

    7
    Simplify the check for empty children nodes in the function

    The function findTableDefFromSource can be simplified by returning nil directly if
    node.Children is nil or empty, reducing the need for an additional check.

    pkg/sql/plan/build_constraint_util.go [474-475]

    -if node.Children == nil || len(node.Children) == 0 {
    +if len(node.Children) == 0 {
       return nil
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: The suggestion is valid and simplifies the code by directly checking for an empty slice, which is a more idiomatic way in Go to check for nil or empty slices.

    6
    Rename the variable to better reflect its boolean nature

    Consider renaming the variable ifInsertFromUnique to isInsertFromUnique to better reflect
    its boolean nature and improve readability.

    pkg/sql/plan/build_dml_util.go [486]

    -ifInsertFromUnique := false
    +isInsertFromUnique := false
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Renaming 'ifInsertFromUnique' to 'isInsertFromUnique' improves readability by following common naming conventions for boolean variables.

    6
    Maintainability
    Use a helper function for error handling to reduce redundancy

    The error handling in the function initInsertStmt can be improved by using a helper
    function to reduce redundancy and improve readability.

    pkg/sql/plan/build_constraint_util.go [390-772]

    -if err != nil {
    +if err := checkError(err); err != nil {
       return false, nil, nil, err
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: This suggestion is beneficial as it promotes code reuse and improves readability by abstracting repetitive error handling into a helper function. However, the exact implementation details and scope of the helper function need careful consideration to ensure it fits all use cases in the function.

    7
    Refactor the initialization of ifInsertFromUnique into a separate function to reduce code duplication

    Combine the multiple ifInsertFromUnique initialization lines into a single function to
    reduce code duplication and improve maintainability.

    pkg/sql/plan/build_dml_util.go [1496-1501]

    -ifInsertFromUnique := false
    -if tableDef.Pkey != nil && ifInsertFromUniqueColMap != nil {
    -    if tableDef.Pkey.PkeyColName != catalog.FakePrimaryKeyColName && tableDef.Pkey.PkeyColName != catalog.CPrimaryKeyColName {
    -        if insertFromUnique, exists := ifInsertFromUniqueColMap[tableDef.Pkey.PkeyColName]; exists {
    -            ifInsertFromUnique = insertFromUnique
    -        }
    -    }
    -}
    +ifInsertFromUnique := getIfInsertFromUnique(tableDef, ifInsertFromUniqueColMap)
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Combining multiple initializations of 'ifInsertFromUnique' into a single function would enhance maintainability and reduce code duplication.

    7
    Best practice
    Add documentation for the new field in the protobuf definition

    Ensure that the IfInsertFromUnique field is documented in the protobuf definition to
    maintain consistency and clarity.

    pkg/pb/pipeline/pipeline.pb.go [1699]

    +// IfInsertFromUnique indicates whether the insert is from a unique source.
     IfInsertFromUnique   bool      `protobuf:"varint,5,opt,name=IfInsertFromUnique,proto3" json:"IfInsertFromUnique,omitempty"`
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding documentation for 'IfInsertFromUnique' is a good practice for maintainability and clarity, especially for new fields in a protobuf definition.

    6
    Rename the variable buildOnSink to isBuildOnSink to better reflect its boolean nature

    To improve code clarity, consider renaming the variable buildOnSink to isBuildOnSink to
    better reflect its boolean nature.

    pkg/sql/colexec/fuzzyfilter/filter.go [248-262]

    -buildOnSink := arg.ifBuildOnSink()
    +isBuildOnSink := arg.ifBuildOnSink();
     
    -if buildOnSink { // build fuzzy on sink scan
    +if isBuildOnSink { // build fuzzy on sink scan
         if arg.IfInsertFromUnique {
             arg.add(pkCol)
         } else {
    -        err := arg.testAndAdd(proc, pkCol)
    -        if err != nil {
    +        if err := arg.testAndAdd(proc, pkCol); err != nil {
                 return err
             }
         }
     } else { // build on table scan
         arg.add(pkCol)
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 4

    Why: Renaming the variable improves readability by making the boolean nature of the variable clearer. However, this is a minor improvement and does not impact functionality.

    4
    Possible issue
    Ensure arg.test and arg.testAndAdd handle necessary cleanup or state reset in case of errors

    To avoid potential issues, ensure that arg.test and arg.testAndAdd handle any necessary
    cleanup or state reset in case of errors.

    pkg/sql/colexec/fuzzyfilter/filter.go [273-275]

    -err := arg.test(proc, pkCol)
    -if err != nil {
    +if err := arg.test(proc, pkCol); err != nil {
    +    // handle cleanup or state reset if necessary
         return err
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: This suggestion is important as it addresses error handling and resource management, which are crucial for maintaining the stability and reliability of the application. However, the suggestion does not provide specific details on how to implement the cleanup or state reset, limiting its effectiveness.

    6
    Initialize the map to ensure it is non-nil and avoid potential runtime errors

    Ensure that the ifInsertFromUniqueColMap is passed as a non-nil value to avoid potential
    runtime errors.

    pkg/sql/plan/build_dml_util.go [124]

    -ifInsertFromUniqueColMap map[string]bool,
    +ifInsertFromUniqueColMap map[string]bool = make(map[string]bool),
     
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    Why: While initializing 'ifInsertFromUniqueColMap' as non-nil can prevent runtime errors, the suggestion incorrectly modifies the function signature instead of ensuring the map is initialized where it's used.

    5

    @matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jun 20, 2024
    @jensenojs

    jensenojs commented Jun 20, 2024 •

    Copy link
    Copy Markdown
    Contributor Author

    heap pprof

    使用如下issue的ddl进行测试

    准备数据 : 数据规模5亿

    -- ddl可能有数据名干问题, 禁一下
    CREATE TABLE `xxx` (
    `xxx` BIGINT NOT NULL AUTO_INCREMENT,
    `xxx` VARCHAR(255) DEFAULT null,
    `xxx` VARCHAR(64) DEFAULT null,
    `xxx` VARCHAR(64) DEFAULT null ',
    `xxx` BIGINT DEFAULT null ,
    `xxx` DOUBLE DEFAULT null,
    `xxx` VARCHAR(64) DEFAULT null 
    PRIMARY KEY `xxx` (`xxx`)
    );
    
    insert into xxx select result, result || "vahicle_id", result || "longitude", result || "latitude", result, 1.0, result || "area" from generate_series(1,500000000) g;
    

    在准备数据完之后, 重新启动mo, 然后用insert into select的方式来复制数据. 并且记录inuse space

    main

    image

    耗时 4min 35.57

    this pr

    image

    耗时1 min 47.78

    @jensenojs

    Copy link
    Copy Markdown
    Contributor Author
    企业微信截图_84107165-de18-42bc-a1ab-971159d08f6c

    还是会有too many collision for fuzzy filter的问题, 等这个问题fix之后这个pr才能进去

    @jensenojs

    Copy link
    Copy Markdown
    Contributor Author

    复测没有问题了

    @mergify
    mergify Bot merged commit d39bec0 into matrixorigin:main Jun 21, 2024
    @jensenojs
    jensenojs deleted the opt-16375-step2 branch June 24, 2024 01:09
    jensenojs added a commit to jensenojs/matrixone that referenced this pull request Jun 28, 2024
    fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
    … t1 selct from t2 (matrixorigin#17020)
    
    在 matrixorigin#16847 之后重新打开fuzzy build在更小节点的逻辑, 在insert into A select from B的场景下, 如果B能够保证数据的唯一性, 在去重检测的时候可以避免内存的浪费
    
    Approved by: @badboynt1, @ouyuanning, @aunjgr, @m-schen
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Labels

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    6 participants