A method and system for intelligent detection of logical defects based on business semantic enhancement
By constructing a historical defect knowledge base, multimodal code representation, and adaptive agent reasoning, the problem of insufficient defect detection capability for complex business logic in existing technologies is solved, achieving efficient and intelligent defect detection and management, and improving code quality assurance capabilities.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- GUODIAN NANJING AUTOMATION SOFTWARE ENG
- Filing Date
- 2026-04-07
- Publication Date
- 2026-06-05
AI Technical Summary
Existing technologies are insufficient to effectively detect and prevent complex business logic defects. They lack systematic management and in-depth understanding of historical defects. Traditional tools have limited detection capabilities and struggle to capture the deep semantics and business logic of code, leading to frequent production accidents.
By constructing a historical business defect knowledge base, performing multimodal code representation learning, employing hierarchical retrieval and adaptive agent reasoning, and combining natural language instruction-driven tools for static and dynamic analysis, defect detection results are generated.
It enables efficient and intelligent detection of defects in complex business logic, improves defect utilization and detection capabilities, enhances code quality assurance, adapts to new defect types, and supports enterprise-level code quality management.
Smart Images

Figure CN122152670A_ABST
Abstract
Description
Technical Field
[0001] This application relates to a method and system for intelligent detection of logical defects based on business semantic enhancement, belonging to the field of software code quality detection technology. Background Technology
[0002] As software systems continue to expand in scale and business logic becomes increasingly complex, business logic defects have become one of the main factors leading to production incidents. Unlike code syntax errors or simple defects, business logic defects typically involve complex business rules, data flow, and cross-module interactions, making them difficult to detect using traditional static analysis tools. Existing technologies have several shortcomings in handling the detection and prevention of historical major business defects, specifically in the following aspects:
[0003] Low utilization and lack of systematic management of historical defects: Existing systems lack systematic management and utilization of business defects found in historical scans. Defect records usually only contain simple descriptions and repair solutions, lacking in-depth information such as business context, root cause analysis, and code context, making it difficult to learn patterns and rules from historical defects.
[0004] Insufficient Business Logic Defect Detection Capabilities: Traditional static analysis tools primarily detect simple defects such as syntax errors, null pointer references, and resource leaks. Their ability to detect complex business logic defects, such as missing boundary conditions, data inconsistencies, and violations of business rules, is limited. Business logic defects often involve cross-module data flow, complex business rules, and implicit constraints, which existing tools struggle to understand and model. Surveys show that most production incidents are caused by business logic defects, but existing tools have limited detection capabilities.
[0005] Lack of deep understanding of code structure and business semantics: Existing code representation methods mainly use simple bag-of-words models or code fragment vectors, losing structural information such as abstract syntax trees, control flow graphs, and data dependency graphs, making it difficult to capture the deep semantics and business logic of the code. Business semantics, such as business entities, business rules, and business processes, are even more difficult to understand and model using traditional methods. Most business logic defects are hidden in the code structure or business semantics, making them difficult for existing methods to detect. Summary of the Invention
[0006] Objective: In view of at least one of the above technical problems, this application provides a method and system for intelligent detection of logical defects based on business semantic enhancement. Through multimodal code representation learning, hierarchical retrieval, adaptive agent reasoning and other technical solutions, it can achieve efficient, intelligent and adaptive business logic defect detection and meet the code quality assurance needs of enterprises.
[0007] The technical solution adopted in this application is as follows:
[0008] Firstly, this application provides a logical defect intelligent detection method based on business semantic enhancement, including:
[0009] S1. Construct a historical business defect knowledge base using multi-dimensional information about historical defects. The historical business defect knowledge base stores the business domain, language, file path, code semantic vector, defect code graph structure and business rules for each historical defect.
[0010] S2. Extract business domain, language, file path, and business rules from the code to be detected; use a pre-trained code model to generate a code semantic vector based on the code to be detected;
[0011] S3. Perform multimodal representation learning on the code to be detected, and use a multimodal fusion mechanism to fuse the embedded representations of abstract syntax tree, control flow graph, program dependency graph and business semantic graph to generate code graph structure;
[0012] S4. Based on the business domain, language, file path, code semantic vector, code graph structure and business rules of the code to be detected, a hierarchical retrieval strategy is used to filter out a preset number of similar historical defects from the historical business defect knowledge base.
[0013] S5. Input the code to be detected and similar historical defects into the adaptive agent inference engine. Use natural language command-driven tools to perform static and dynamic analysis on the code to be detected and generate a comprehensive defect detection result. The defect detection result includes whether a problem exists, the type of problem, the confidence level, the root cause, the scope of impact, and the repair suggestions.
[0014] S6. Verify the results based on the confidence level output by the adaptive agent inference engine and generate a defect report.
[0015] Secondly, this application provides a logical defect intelligent detection system based on business semantic enhancement, including a processor and a storage medium;
[0016] The storage medium is used to store instructions;
[0017] The processor is configured to operate according to the instructions to execute the method according to the first aspect.
[0018] Thirdly, this application provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the method described in the first aspect.
[0019] Fourthly, this application provides a computer device including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the method described in the first aspect.
[0020] Fifthly, this application provides a computer program product, including a computer program that, when executed by a processor, implements the method described in the first aspect.
[0021] The inventiveness of this invention is reflected in the following four aspects:
[0022] (1) Multi-dimensional Modeling Innovation of Historical Business Defect Knowledge Base: This invention proposes a multi-dimensional information collection method for historical business defects. It not only records basic defect information and remediation plans, but also focuses on collecting in-depth information such as business context, root cause analysis, code context, and defect pattern characteristics, providing LLM with sufficient context for understanding the essence of defects. A vector database is used to store the semantic vectors of defects, supporting semantic search rather than simple text matching, enabling the identification of historical defects with similar code but different expressions. Compared to traditional defect recording methods, this method is more in line with the cognitive characteristics of LLM, providing a high-quality knowledge base for intelligent assessment.
[0023] (2) Innovation in Multimodal Code Representation Learning: This invention integrates abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs to construct a multimodal graph neural network representation of code. A business semantic graph is introduced to model the relationships between business entities, business rules, and business operations. A heterogeneous graph neural network is used to learn the embedded representation of the business semantic graph. Compared to simple semantic vectors or bag-of-words models, this method preserves the complete structural information and business semantics of the code, and can capture defects hidden in the code structure or business semantics.
[0024] (3) Innovative Hierarchical Retrieval and Business Rule Matching: This invention proposes a four-layer hierarchical retrieval framework, which filters similar historical defects step by step from four granularities: business domain, semantics, structure, and business rules. It introduces business rule retrieval to directly match business logic defect patterns. The retrieved candidate historical defects are used as input for context-enhanced LLM using retrieval enhancement generation technology. Compared with single-layer retrieval or simple keyword matching, this method effectively solves the problem of missing relevant defects.
[0025] (4) Adaptive Agent Reasoning and Self-Reflection Innovation: This invention introduces a collaborative mechanism based on a large language model and dedicated analysis tools. Through tool invocation, self-reflection, and iterative optimization, it achieves deep code reasoning. The agent can invoke tools such as data flow analysis, boundary condition detection, business rule verification, and code difference comparison to proactively reflect on its analysis process and iteratively optimize based on reflection feedback. Compared to a single large language model invocation, this method analyzes the code from multiple perspectives, enhancing reasoning capabilities.
[0026] Beneficial Effects: The intelligent detection method and system for logical defects based on business semantic enhancement provided in this application have the following advantages: Through the construction of a historical defect knowledge base, multimodal code representation learning, hierarchical retrieval, adaptive agent reasoning and other technical solutions, it realizes intelligent detection of historical major business defects, solves the technical problems in the existing technology such as low utilization rate of historical defects, insufficient detection capability of business logic defects, shallow understanding of code structure, low retrieval recall rate, insufficient reasoning depth of large language models, slow knowledge base updates and poor adaptability to new defect types, and meets the needs of enterprise code quality assurance, DevSecOps platform and intelligent operation and maintenance system. Attached Figure Description
[0027] Figure 1 This is a schematic diagram of a logic defect intelligent detection system based on business semantic enhancement according to an embodiment of this application;
[0028] Figure 2 This is a schematic diagram of the process for constructing a historical business defect knowledge base according to one embodiment of this application.
[0029] Figure 3 This is a schematic diagram of a multimodal code representation learning process according to one embodiment of this application.
[0030] Figure 4 This is a schematic diagram of a multimodal fusion adaptive selection process according to an embodiment of this application.
[0031] Figure 5 This is a schematic diagram of a hierarchical retrieval process according to an embodiment of this application.
[0032] Figure 6 This is a schematic diagram of an adaptive agent inference process according to an embodiment of this application.
[0033] Figure 7 This is a flowchart illustrating a logical defect intelligent detection method based on business semantic enhancement according to an embodiment of this application. Detailed Implementation
[0034] The present application will be further described below with reference to the accompanying drawings and embodiments. The following embodiments are only used to more clearly illustrate the technical solutions of the present application, and should not be used to limit the scope of protection of the present application.
[0035] In the description of this application, "several" means one or more, "multiple" means two or more, "greater than," "less than," and "exceeding" are understood to exclude the stated number, while "above," "below," and "within" are understood to include the stated number. The use of "first" and "second" in the description is merely for distinguishing technical features and should not be construed as indicating or implying relative importance, or implicitly indicating the number of indicated technical features, or implicitly indicating the order of the indicated technical features.
[0036] In the description of this application, the terms "one embodiment," "some embodiments," "illustrative embodiment," "example," "specific example," or "some examples," etc., refer to specific features, structures, materials, or characteristics described in connection with that embodiment or example, which are included in at least one embodiment or example of this application. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described may be combined in any suitable manner in one or more embodiments or examples.
[0037] The term "and / or" simply describes the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A alone, A and B simultaneously, or B alone. Additionally, the character " / " generally indicates that the preceding and following related objects have an "or" relationship.
[0038] Example 1: This example provides a logical defect intelligent detection method based on business semantic enhancement, including:
[0039] S1. Construct a historical business defect knowledge base using multi-dimensional information about historical defects. The historical business defect knowledge base stores the business domain, language, file path, code semantic vector, defect code graph structure, and business rules for each historical defect.
[0040] It should be noted that the multi-dimensional information of historical defects includes basic information, business context, root cause analysis, code context, remediation plan, defect pattern characteristics, and statistical information.
[0041] Based on this, a historical business defect knowledge base is constructed, including: recording multi-dimensional information for each historical defect, including basic information, business context, root cause analysis, code context, remediation plan, defect pattern characteristics and statistical information;
[0042] The basic information includes defect identifier, title, severity, business domain, business scenario, first discovery time, and number of occurrences;
[0043] The business context includes an impact description, affected users, affected functions, and the scope of business impact, which describes why this defect is important to the business.
[0044] Root cause analysis includes direct causes, underlying causes, and design flaws. Direct causes describe problems at the code level, underlying causes analyze the root causes of problems in requirements, design, and processes, and design flaws point out deficiencies at the architecture or design level.
[0045] The code context includes programming language, file path, class name, method name, line number, code snippet, API endpoint, and data table, which are used to provide complete code context information;
[0046] The fix plan includes a fix description, code differences, and test cases, which detail how to fix the defect and how to verify the fix.
[0047] Defect pattern features include pattern type, key indicators and similar keywords, which are used to extract the essential features of defects and facilitate the subsequent identification of similar defects.
[0048] The statistics include affected items, recurrence rate, and average repair time, used to quantify the impact of defects and the difficulty of repair.
[0049] S2. Extract business domain, language, file path, and business rules from the code to be detected; use a pre-trained code model to generate a code semantic vector based on the code to be detected.
[0050] S3. Perform multimodal representation learning on the code to be detected, and use a multimodal fusion mechanism to fuse the embedded representations of abstract syntax tree, control flow graph, program dependency graph and business semantic graph to generate code graph structure.
[0051] In some embodiments, step S3 specifically includes:
[0052] Construct an abstract syntax tree to represent the syntax structure of the code. Nodes include classes, methods, variables, and expressions, while edges include inclusion, invocation, and reference.
[0053] Construct a control flow graph to represent the execution logic of the code. Nodes include basic blocks, and edges include conditional jumps and loops.
[0054] Construct a program dependency graph to represent the data dependencies of the code. Nodes include statements and variables, and edges include data dependencies and control dependencies.
[0055] Constructing a business semantic graph includes: extracting business entities from code; extracting business rules from code, including business constraints, business logic, and business processes; extracting business operations from code, including creation, update, deletion, and query; and constructing relationships between business entities, business rules, and business operations to obtain a business semantic graph, including business processes, data flow, and rule constraints.
[0056] Graph neural networks are used to learn embedded representations of abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs. For abstract syntax trees, graph attention networks are used to automatically focus on nodes and edges that are more critical to semantic understanding using attention mechanisms. For control flow graphs, gated graph neural networks are used to capture the dynamic characteristics of state transitions in the control flow through gating mechanisms. For program dependency graphs, a sampling aggregation strategy is introduced to improve computational efficiency while ensuring representation quality. Heterogeneous graph neural networks are used to learn embedded representations of business semantic graphs. These heterogeneous graph neural networks contain different types of nodes and edges, and meta-path aggregation is used to aggregate different types of neighbors.
[0057] The code graph structure is obtained by fusing the embedded representations of the abstract syntax tree, control flow graph, program dependency graph, and business semantic graph using a multimodal fusion mechanism;
[0058] The multimodal fusion mechanism employs an adaptive selection strategy, dynamically choosing the fusion method based on code complexity, defect type, and real-time requirements. The fusion methods include concatenation, attention-weighted, and tensor fusion. Code complexity is comprehensively evaluated using cyclomatic complexity, the number of graph nodes, and the number of graph edges. Defect types are identified as syntax defects, logic defects, or business defects through static analysis and pattern matching. Real-time requirements are categorized into batch detection, real-time detection, or online detection based on the detection scenario.
[0059] When the code complexity is below the first threshold or the detection scenario is real-time detection, the concatenation method is used; when the code complexity is between the first and second thresholds and the defect type is logic-based, the attention weighting method is used; when the code complexity is above the second threshold or the defect type is business-based, the tensor fusion method is used.
[0060] S4. Based on the business domain, language, file path, code semantic vector, code graph structure, and business rules of the code to be detected, a hierarchical retrieval strategy is used to filter and obtain a preset number of similar historical defects from the historical business defect knowledge base.
[0061] In some embodiments, step S4 specifically includes:
[0062] The first layer of coarse-grained retrieval includes business domain, language, and file path as search dimensions. It uses an inverted index to recall a first preset number of candidate historical defects.
[0063] The second layer is a medium-granularity retrieval, with the retrieval dimension being the code semantic vector. Based on the code to be detected, a pre-trained code model is used to generate the code semantic vector, and a similarity algorithm is used to calculate the similarity. A second preset number of candidate historical defects is recalled, which is less than the first preset number.
[0064] The third layer of fine-grained retrieval uses code graph structure similarity as the retrieval dimension. A graph matching algorithm is used to calculate the similarity between the code graph structure and the defective code graph structure, and a third preset number of candidate historical defects is recalled. The third preset number is less than the second preset number.
[0065] The fourth layer is business rule retrieval, with the retrieval dimension being business rule pattern matching. Business rules are extracted from historical defects, directly matched with business logic defects, and a fourth preset number of candidate historical defects are recalled as similar historical defects.
[0066] In this embodiment, a retrieval-enhanced generation technique is used to take a fourth preset number of candidate historical defects as input to a context-enhanced large language model.
[0067] S5. Input the code to be detected and similar historical defects into the adaptive agent inference engine. Use natural language command-driven tools to perform static and dynamic analysis on the code to be detected and generate defect detection results. The defect detection results include whether there is a problem, the type of problem, the confidence level, the root cause, the scope of impact, and the repair suggestions.
[0068] In some embodiments, step S5 specifically includes:
[0069] S51 preliminary analysis involves combining the code to be detected with similar historical defects to form prompt words, which are then input into a large language model for analysis to obtain preliminary analysis results. The preliminary analysis results include the problem existence judgment, problem type, preliminary root cause hypothesis, and initial confidence level.
[0070] S52 Tool Invocation: Based on the problem type, the corresponding tool is invoked to analyze the code to be detected and similar historical defects, and the tool analysis results are obtained; the tools include a data flow analyzer, a boundary condition detector, a business rule verifier, and a code difference comparator;
[0071] S53 Observation: Integrating the results of instrumental analysis into a chain of evidence;
[0072] S54 Self-Reflection: The criticism module compares the results of the tool analysis with the preliminary analysis results, checks the consistency, completeness and sufficiency of the evidence, and obtains reflective feedback;
[0073] S55 Iterative Optimization: If the analysis is deemed insufficient, reflective feedback is added to the prompt words, and S51-S54 are executed iteratively until the iteration termination condition is met, and the final analysis result is output.
[0074] S56 Confidence Calibration: The confidence level of the large language model is dynamically adjusted based on the number of iterations, consistency of tool analysis results, sufficiency of evidence, and historical reflection feedback.
[0075] Furthermore, the tool invocation step includes:
[0076] Data flow analyzers track the flow path of variables and detect data inconsistencies and loss of accuracy;
[0077] The boundary condition detector detects if statements, loop statements, and exception handling, and identifies missing boundary conditions.
[0078] The business rule validator verifies whether the code implementation conforms to formal business constraints, which are extracted from historical defects.
[0079] The code difference comparator compares the code to be detected with historical defective codes to identify similarities and differences.
[0080] Furthermore, the self-reflection steps include:
[0081] The critique module is used to evaluate the quality of the current analysis results, taking into account factors such as the consistency, completeness, and sufficiency of evidence. The critique module generates reflective feedback that points out deficiencies and omissions in the analysis.
[0082] If the reflection feedback indicates that the analysis is insufficient, the Agent re-analyzes the code based on the reflection feedback; if the reflection feedback indicates that the analysis is sufficient, the iteration stops.
[0083] S6. Verify the results based on the confidence level output by the adaptive agent inference engine and generate a defect report.
[0084] In some embodiments, step S6 specifically includes:
[0085] Based on the confidence level output by the large language model, the report is classified into levels. High confidence level results in automatic creation of defect reports, medium confidence level results are marked as requiring manual confirmation, and low confidence level results are ignored.
[0086] For results with medium confidence, a detailed chain of evidence and suggested manual verification steps are provided. The chain of evidence includes similar historical defects, tool analysis results, reasoning process, and remediation suggestions. Feedback from manual verification is recorded and used to optimize the prompt and model.
[0087] Example 2: Based on Example 1, this example provides a logical defect intelligent detection system based on business semantic enhancement, including a processor and a storage medium;
[0088] The storage medium is used to store instructions;
[0089] The processor is configured to operate according to the instructions to execute the method according to Embodiment 1.
[0090] In some embodiments, such as Figure 1As shown, the intelligent logic defect detection system based on business semantic enhancement includes: a historical business defect knowledge base management module, a multimodal code representation learning module, a hierarchical retrieval module, an adaptive agent reasoning module, and a result verification module.
[0091] The historical business defect knowledge base management module is used to collect multi-dimensional information on historical defects. This multi-dimensional information includes basic defect information, business context, root cause analysis, code context, remediation plan, and defect pattern characteristics. It uses a vector database to store the semantic vectors of defects and a relational database to store structured metadata, supporting semantic search and structured queries.
[0092] The multimodal code representation learning module is used to learn multimodal representations of the code to be detected. It integrates abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs to construct a code graph structure, preserving the complete structural information and business semantics of the code. It uses graph neural networks to learn the embedding representations of each layer of the graph and uses a multimodal fusion mechanism to fuse the embedding representations of each layer of the graph. The multimodal fusion mechanism adopts an adaptive selection strategy to extract code features including code complexity, defect type, and real-time requirements. Code complexity is evaluated by comprehensively considering cyclomatic complexity, the number of graph nodes, and the number of graph edges to obtain a complexity score. Defect type is identified by static analysis of code feature patterns and matched with a predefined defect type library to obtain defect classification. Real-time requirements are determined according to the detection scenario configuration to determine the detection timeliness level. Based on the extracted features, a decision tree or neural network model is used to dynamically select splicing, attention weighting, or tensor fusion methods to achieve optimal matching of fusion methods.
[0093] The hierarchical retrieval module employs a hierarchical retrieval strategy to progressively filter similar historical defects at four granularities: business domain, semantics, structure, and business rules. The first layer, coarse-grained retrieval, uses an inverted index to recall a first preset number of candidate historical defects. The second layer, medium-grained retrieval, uses code semantic vectors to recall a second preset number of candidate historical defects. The third layer, fine-grained retrieval, uses code graph structure similarity to recall a third preset number of candidate historical defects. The fourth layer, business rule retrieval, uses business rule pattern matching to recall a fourth preset number of candidate historical defects. The retrieved candidate historical defects are used as context using retrieval enhancement generation technology.
[0094] The adaptive agent inference module is used to combine a large language model and a dedicated analysis tool through a collaborative mechanism. It integrates tool calls, self-reflection, and iterative optimization. The module inputs the code to be detected and similar historical defects into the large language model, analyzes whether the code has defects similar to historical defects, generates preliminary results from the initial analysis, calls the data flow analyzer, boundary condition detector, business rule validator, and code difference comparator to the tool, observes the results collected from the tool and performs comprehensive analysis, evaluates the comprehensiveness of the analysis and checks for omissions through self-reflection, iteratively optimizes and re-analyzes based on the feedback from reflection, and dynamically adjusts the confidence level based on the number of iterations, tool consistency, and historical feedback from reflection.
[0095] The result verification module is used to verify the results based on the confidence level output by the large language model, classify the confidence level according to a preset threshold, and automatically create defect reports or mark them as requiring manual confirmation.
[0096] like Figure 1 As shown, this embodiment provides an intelligent logic defect detection system based on business semantic enhancement. The system adopts a layered design, including a data layer, a presentation layer, a retrieval layer, an inference layer, and an application layer.
[0097] The data layer comprises a vector database and a relational database. The vector database stores semantic vectors of defects and code, supporting efficient vector similarity search. The relational database stores structured metadata, including basic defect information, root cause analysis, code context, remediation plans, and statistical information. The data layer also provides data import / export interfaces, supporting the import of historical defect data from external defect tracking systems.
[0098] Representation Layer: This layer includes a code parser and a multimodal representation learner. The code parser is responsible for parsing the source code and generating an abstract syntax tree, control flow graph, program dependency graph, and business semantic graph, supporting multiple programming languages. The multimodal representation learner uses graph neural networks to learn the embedding representations of each layer's graph and uses a multimodal fusion mechanism to fuse the embedding representations of each layer's graph to generate code semantic vectors. The fusion mechanism includes concatenation, attention weighting, and tensor fusion.
[0099] The retrieval layer includes a hierarchical retrieval engine, implementing a four-layer hierarchical retrieval framework. The first layer, coarse-grained retrieval, uses an inverted index for fast filtering based on business domain, language, and file path. The second layer, medium-grained retrieval, uses code semantic vectors and cosine similarity. The third layer, fine-grained retrieval, uses code graph structure and graph edit distance. The fourth layer, business rule retrieval, uses business rule pattern matching. The retrieval layer also includes a retrieval scoring module, which calculates the final retrieval score based on the retrieval strategy and returns a preset number of similar historical defect records.
[0100] The inference layer comprises an adaptive agent inference engine and a large language model service. The agent inference engine employs a collaborative mechanism based on the large language model and dedicated analysis tools to perform initial analysis, tool invocation, result observation, self-reflection, iterative optimization, and confidence calibration. Tools include a data flow analyzer, boundary condition detector, business rule validator, and code difference comparator. The large language model service provides a unified interface for the large model, supporting prompt template management and dynamic prompt construction.
[0101] Application Layer: Includes code scanning interface, defect report generator, visual interface, and API services. The code scanning interface provides batch and incremental code scanning; the defect report generator automatically generates defect reports containing detailed chains of evidence; the visual interface provides functions such as code browsing, defect viewing, statistical analysis, and knowledge base management; and the API services support integration with existing systems.
[0102] Through the system architecture described in this embodiment, the system realizes a complete closed loop from data collection, code representation, similar defect retrieval, intelligent reasoning to defect report generation. Users can detect historical major business defects through the interface or API interface. The system realizes intelligent detection of business logic defects through technologies such as multimodal code understanding, hierarchical retrieval, and adaptive agent reasoning.
[0103] like Figure 2 As shown in the figure, this embodiment details how to build a historical business defect knowledge base and collect multi-dimensional information on historical defects.
[0104] The system first collects historical defect information from multiple data sources. These sources include historical scan records and code review records, from which business logic defects such as missing boundary conditions, data inconsistencies, and violations of business rules are extracted. An external defect tracking system imports historical business defects via API interfaces or files, filtering for business logic defects and excluding syntax errors and simple defects. Production incident reports and post-mortem documents extract major defects, focusing on analyzing their business impact and root causes. Code commit records and change logs extract defect information through commit information and code differences.
[0105] For each historical defect, the system collects multi-dimensional information. This multi-dimensional information includes basic information, business context, root cause analysis, code context, remediation plan, defect pattern characteristics, and statistical information. Basic information includes defect identifier, title, severity, business domain, business scenario, first discovery time, and frequency of occurrence. Business context includes impact description, affected users, affected functions, and business impact scope, focusing on why this defect is important to the business. Root cause analysis includes direct causes, underlying causes, and design flaws. Direct causes describe code-level problems; underlying causes analyze fundamental issues such as requirements, design, and processes; and design flaws point to shortcomings at the architectural or design level. Code context includes programming language, file path, class name, method name, line number, code snippet, API endpoint, and data table, providing complete code context information. Remediation plans include remediation description, code differences, and test cases, detailing how to fix the defect and how to verify the fix. Defect pattern characteristics include pattern type, key indicators, and similar keywords, extracting the essential characteristics of the defect to facilitate subsequent identification of similar defects. Statistical information includes affected projects, recurrence rate, and average remediation time, quantifying the impact and difficulty of remediation.
[0106] The system uses a vector database to store the semantic vectors and code semantic vectors of defects. For each defect's description, root cause, code snippets, and other textual information, a text encoding model is used to generate semantic vectors. For code snippets, a code encoding model is used to generate code semantic vectors. Both semantic and code semantic vectors are stored in the vector database, supporting efficient semantic search. The system also uses a relational database to store structured metadata, creating multiple tables including a basic information table, a root cause analysis table, a code context table, a remediation plan table, a defect pattern feature table, and a statistical information table. Indexes are created for key fields to support efficient querying and statistics.
[0107] The method described in this embodiment constructs a high-quality historical business defect knowledge base, which not only records the surface information of defects, but also collects in-depth information such as root causes, code context, and defect patterns, providing a sufficient knowledge foundation for subsequent intelligent analysis.
[0108] like Figure 3 As shown, this embodiment details how to perform multimodal code representation learning, integrating abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs.
[0109] In the implementation of multimodal code representation learning, the system first performs multi-level parsing of the source code to be tested, generating four graph representations with different semantic granularities and structural characteristics. The abstract syntax tree (AST) is generated by a language-specific parser, with nodes covering syntactic units such as classes, methods, variables, and expressions, and edges depicting syntactic relationships such as inclusion, calling, or referencing, thus fully reflecting the static syntactic structure of the code. Based on this, the system constructs a control flow graph, using basic blocks as nodes and conditional jumps, loops, and sequential execution as edges, accurately describing the dynamic execution path of the program. Furthermore, combined with data flow analysis, the system generates a program dependency graph, where nodes include statements and variables, and edges reflect data dependencies and control dependencies, comprehensively depicting the internal information flow and logical constraints of the program.
[0110] Beyond the underlying program structure, the system also focuses on extracting high-level business semantics and constructing a business semantic graph. This graph identifies business entities such as "user" and "order" by analyzing naming conventions, annotations, and domain models in the code; it extracts business rules such as business constraints, core logic, and key processes through rule engines or pattern matching techniques; and it identifies typical business operations such as creation, querying, updating, and deletion based on clues such as method names and API calls. Building upon this foundation, the system further establishes relationships between entities, rules, and operations, such as the sequence of business processes, data flow paths between entities, and the constraints imposed by rules on operations, ultimately forming a semantic network rich in domain knowledge.
[0111] To effectively learn the vector representations of the aforementioned heterogeneous graphs, the system employs a targeted graph neural network architecture. For abstract syntax trees, a graph attention network is used, leveraging the attention mechanism to automatically focus on nodes and edges that are more critical to semantic understanding. For control flow graphs, a gated graph neural network is employed, using a gating mechanism to capture the dynamic characteristics of state transitions in the control flow. For large-scale program dependency graphs, the system introduces a sampling aggregation strategy to improve computational efficiency while ensuring representation quality. For complex business semantic graphs—containing multiple types of nodes and edges—a heterogeneous graph neural network is used, employing predefined meta-paths (e.g., "business entity → business operation → business entity") to perform differentiated aggregation of different types of neighbors, thereby achieving feature fusion across semantic types.
[0112] After obtaining the embedded representations of each graph layer, the system integrates them into a unified code semantic vector through a multimodal fusion mechanism. One approach is to directly concatenate the embeddings of each graph, preserving the integrity of the original features. Another approach is to introduce a self-attention mechanism to dynamically calculate the importance weights of each modality representation, enabling the fusion result to adaptively highlight the most discriminative view. Additionally, tensor fusion methods can be employed to model the interaction relationships between different graph structures through high-order tensor decomposition, uncovering potential cross-modal coupling patterns. The resulting code semantic vector not only fully preserves the program's syntactic structure, control logic, and data dependencies but also deeply integrates high-level business semantics, significantly surpassing traditional representation methods that rely solely on text sequences or single graph structures. This provides a richer and more robust semantic foundation for downstream tasks such as code understanding, defect detection, and intelligent completion.
[0113] like Figure 4 As shown, this embodiment proposes an adaptive selection mechanism for multimodal fusion, which can dynamically select the most suitable fusion method based on the inherent features of the code and the external constraints of the detection scenario, thereby achieving an optimal balance between detection accuracy and computational efficiency.
[0114] The system first extracts three key features from the code to be inspected: code complexity, defect type, and real-time requirements. Regarding complexity, the system quantitatively evaluates cyclomatic complexity, the number of nodes in the abstract syntax tree, the number of nodes in the control flow graph, and the total number of nodes and edges in the program dependency graph. Cyclic complexity is calculated by counting the number of decision points, or it can be directly derived from the graph structure (i.e., number of edges minus number of nodes plus 2). All indicators are normalized to the [0,1] interval and then weighted and summed according to preset weights to form the final complexity score. These weights can be set based on domain experience or optimized through learning from historical data. Regarding defect types, the system relies on a structured defect pattern library for matching and identification. This library covers three main categories: syntax (e.g., null pointer dereference, array out-of-bounds errors, unreleased resources), logic (e.g., incorrect conditional statements, loop logic exceptions, state machine defects), and business (e.g., rule violations, missing permissions, disordered processes). The system calculates the similarity between the static analysis features of the current code and the patterns in the library, selecting the category with the highest score as its defect type label. As for real-time requirements, they are configured according to the specific detection scenario: batch detection allows for response times of more than a second, which is classified as "low" real-time; online detection needs to be completed within a few seconds after code submission, which is classified as "medium"; while real-time detection requires a response time of milliseconds, which is marked as "high". The system classifies real-time performance into three levels: high, medium, and low accordingly.
[0115] Based on the above characteristics, the system employs a three-layer decision tree to adaptively select the fusion method. The first layer uses code complexity as the criterion: if the complexity score is below a first threshold (e.g., 0.3), it is considered simple code, and the concatenation fusion method with the lowest computational cost is directly selected; if the score is above a second threshold (e.g., 0.7), it proceeds to the third layer; if it falls between the two, it proceeds to the second layer. The second layer focuses on defect type: when a logical defect is identified, attention-weighted fusion is used because it can dynamically adjust the contribution weights of each graph embedding, making it more effective at capturing cross-modal logical connections; if it is a syntax defect, the concatenation method is still used, as such problems can usually be effectively identified using only an abstract syntax tree. The third layer is dedicated to high-complexity scenarios: if the defect type is business-related, tensor fusion is used to model the high-order interaction relationships between graphs at each layer, addressing complex business semantic coupling; if it is syntax or logic-related, it reverts to the attention-weighted method, controlling computational cost while ensuring effectiveness.
[0116] In addition, the system is designed with a real-time priority coverage mechanism to ensure that performance constraints are not breached. When the real-time level is "high," the concatenation method is forcibly used regardless of code complexity or defect type to ensure response speed. When the level is "medium," a complexity upper limit constraint is added to the original decision tree—attention weighting or tensor fusion is only allowed when the complexity is below the second threshold; otherwise, it falls back to concatenation. When the level is "low," the decision tree logic is followed completely, prioritizing the maximization of detection performance.
[0117] To further enhance the intelligence of the strategy, the system introduces a continuous optimization mechanism based on historical reflection and feedback. After each detection, the system records code features, the selected fusion method, the detection result, and manually confirmed labels. When the accuracy does not meet expectations, the system automatically adjusts the thresholds in the decision tree: for example, increasing the first threshold to enable attention mechanisms for more moderately complex code to improve performance; or decreasing the second threshold to reduce the frequency of high-overhead tensor fusion to save resources. The optimization process uses gradient descent or grid search, with a weighted comprehensive score of accuracy, recall, and detection time as the objective function. Simultaneously, the system also performs feature importance analysis: if the correlation between cyclomatic complexity and detection performance is significantly higher than the number of nodes or edges, its weight in complexity calculation is increased; if the confidence of defect type classification is low, auxiliary features (such as line count, function call depth, etc.) are introduced to enhance the robustness of the judgment.
[0118] like Figure 5 As shown in this embodiment, a four-layer hierarchical retrieval strategy is described in detail. This strategy aims to gradually filter similar historical defects related to the code to be detected from four different granularities: business domain, semantics, structure, and business rules, so as to achieve efficient and accurate defect recall.
[0119] The system first performs a coarse-grained search, rapidly narrowing down the candidate pool based on an inverted index. This layer uses business domain, programming language, and file path as key dimensions. The system pre-builds and maintains three types of inverted indexes: mappings from business domain to historical defects, from language to historical defects, and from file path to historical defects. When code to be detected is input, the system quickly searches the corresponding indexes based on its business domain, language, and source file path, initially recalling a pre-set number of candidate historical defects, significantly reducing subsequent computational load.
[0120] Building upon the initial screening, the system proceeds to a second layer of fine-grained retrieval, focusing on semantic similarity of the code. This layer utilizes a pre-trained code encoding model (such as CodeBERT or GraphCodeBERT) to generate semantic vectors for the code to be detected and calculates the cosine similarity between these vectors and the semantic vectors of each candidate historical defect code. The system sorts these vectors in descending order of similarity and retains a second predetermined number of candidate historical defects with the highest scores, thereby further filtering irrelevant items at the semantic level.
[0121] The third layer is fine-grained structure matching, employing graph representation learning and graph similarity measurement. The system uses graph neural networks to encode the multimodal graph structure of the code (such as abstract syntax trees, control flow graphs, etc.) to generate structure-aware graph embeddings. Subsequently, the structural differences between the code graph to be detected and the candidate historical defect graphs are quantified by graph edit distance—this distance is defined as the minimum number of operations required to transform one graph into another, including the insertion, deletion, or replacement of nodes / edges. To facilitate fusion, the system normalizes the original edit distance to the [0,1] interval (the larger the value, the more similar the structure), and sorts them accordingly, retaining a third preset number of high structural similarity candidates.
[0122] The fourth layer focuses on business compliance, performing rule-based deep verification. The system extracts typical business rule patterns (such as missing permission checks, incorrect status transitions, and irregular amount calculations) from the historical defect database and performs rule matching and logic verification on the code to be tested. If a code implementation is found to violate a known business rule, it is marked as a high-risk potential defect and included in the fourth preset number of final candidate sets.
[0123] After completing the four-layer retrieval, the system uses the recalled historical defects as enhanced context, and inputs them together with the code to be detected into the large language model. By providing real and specific defect cases as references, the model can more accurately identify whether similar problems exist in the current code, significantly improving the context-awareness and reliability of defect judgment.
[0124] To further unify multi-granularity information, the system also calculates a comprehensive search score for final ranking. This score is a weighted fusion of four parts: business domain matching (1 if they match, 0 otherwise), semantic similarity (cosine value, range 0–1), structural similarity (normalized graph edit distance, range 0–1), and business rule matching (1 if the rule is violated, 0 otherwise). The final score is normalized to the [0,1] interval, and the system uses this interval to rank the candidate historical defect list, returning the most relevant historical defect as a basis for auxiliary analysis.
[0125] Through the aforementioned hierarchical retrieval mechanism, which progresses from coarse to fine and layer by layer, the system effectively suppresses noise interference while maintaining a high recall rate, significantly reducing the omission of relevant defects. Experiments show that this strategy not only improves retrieval efficiency but also provides high-quality, multi-dimensional contextual support for subsequent large-scale model inference, thereby enhancing the overall accuracy and interpretability of defect detection.
[0126] like Figure 6 As shown, this embodiment details how to build an adaptive agent inference engine, using a collaborative mechanism based on a large language model and dedicated analysis tools, combined with tool invocation, self-reflection, and iterative optimization.
[0127] The system constructs an adaptive agent inference engine, using a collaborative mechanism based on a large language model and dedicated analysis tools. In the initial analysis phase, the large language model receives the code to be detected and similar historical defects, generating preliminary analysis results, including the existence of problems, problem types, and preliminary root cause analysis. In the tool invocation phase, the agent invokes tools for in-depth analysis. These tools include a data flow analyzer that tracks variable flow paths to detect data inconsistencies and accuracy loss; a boundary condition detector that detects conditional statements, loop statements, and exception handling to identify missing boundary conditions; a business rule validator that verifies whether the code implementation conforms to business rules; and a code difference comparator that compares the code to be detected with historical defective code to identify similarities and differences. In the result observation phase, the agent collects and synthesizes the results returned by the tools, using these results as additional evidence to help the agent analyze the code more comprehensively. In the self-reflection phase, the agent uses a critique module to evaluate the quality of the current analysis results, considering the consistency, completeness, and sufficiency of evidence. The critique module generates reflective feedback pointing out deficiencies and omissions in the analysis. In the iterative optimization phase, the agent re-analyzes the code based on the reflective feedback. If the reflective feedback indicates that the analysis is sufficient, the iteration stops. During the confidence calibration phase, the confidence level is dynamically adjusted based on the number of iterations, the consistency of tool returns, and historical reflection feedback. If the number of iterations is high or the tool returns are inconsistent, the confidence level is reduced.
[0128] The critique module is a lightweight, large language model or rule engine specifically designed to evaluate the quality of Agent analysis. It checks the consistency of the analysis (whether the analysis conclusions align with the tool's results), the completeness of the analysis (whether important code paths or boundary conditions have been missed), and the sufficiency of the evidence (whether there is sufficient evidence to support the analysis conclusions). The critique module generates detailed reflective feedback, specifically pointing out areas where the analysis was insufficient and where reconsideration is needed. The Agent then re-analyzes based on this feedback, avoiding blind spots and errors from the initial analysis.
[0129] For example, the detailed steps are as follows:
[0130] 1. Agent Inference Engine Architecture
[0131] The adaptive agent inference engine consists of four core components:
[0132] (1) Agent Controller: As the scheduling hub of the inference engine, it is responsible for coordinating the workflow of each component, including task decomposition, tool call decision, iteration control and result integration. The Agent Controller is implemented based on a large language model and has the ability to plan tasks, make decisions and understand natural language.
[0133] (2) Criticism Module: A lightweight large language model or rule engine specifically designed to evaluate the quality of Agent analysis results. The criticism module operates independently of the main analysis model, providing an objective third-party evaluation perspective.
[0134] (3) Toolset: Includes four dedicated analysis tools: data flow analyzer, boundary condition detector, business rule validator and code difference comparator. Each tool encapsulates specific static analysis capabilities.
[0135] (4) Prompt Manager: Responsible for managing and dynamically building various Prompt templates, including initial analysis Prompt, tool call Prompt, critique Prompt and iterative optimization Prompt.
[0136] The data flow is as follows: the input layer receives the code to be detected and similar historical defects. After processing by the Agent controller, the output layer outputs structured detection results and confidence levels for use by the subsequent result verification module.
[0137] 2. Six-stage reasoning process
[0138] The system executes a six-stage reasoning process, with a closed-loop feedback mechanism between each stage.
[0139] S51. Initial Analysis Phase
[0140] The Agent controller invokes the large language model to organize the code to be detected and the retrieved similar historical defects into a structured Prompt input.
[0141] The initial analysis outputs structured JSON results, including a problem existence determination, problem type, preliminary root cause hypothesis, and initial confidence level.
[0142] S52. Tool Invocation Phase
[0143] Based on the problem type identified in the initial analysis, the Agent controller selects and invokes the appropriate dedicated analysis tool according to the tool invocation decision rules. The tool invocation decision rules are shown in Table 1.
[0144] Table 1: Tool Invocation Decision Rules
[0145]
[0146] The specific functions of each tool are as follows:
[0147] Data Flow Analyzer: Traces variable definitions—using chains to construct the program's data flow graph, detecting data inconsistencies and precision loss issues during variable transfer across functions and modules. Output includes variable flow paths, data contamination points, and type conversion records.
[0148] Boundary condition detector: Scans conditional statements, loop statements, and exception handling in the code to identify the presence of boundary condition checks. The detection scope includes: zero value checks, negative value checks, null value checks, overflow checks, array out-of-bounds checks, and division by zero checks. The output includes a list of missing boundary conditions and potential risk points.
[0149] Business rule validator: Extracts formalized business rule constraints from historical defects and verifies whether the code implementation meets these constraints. Business rules include: permission verification rules, amount calculation rules, status transition rules, and data validation rules. Output includes a list of rule violations and their locations.
[0150] Code Difference Comparator: Calculates the structural similarity between the code to be detected and historical defective code, identifying similar code snippets and key differences. It uses an AST comparison algorithm and semantic similarity calculation. Output includes similarity scores, similar code blocks, and differing code blocks.
[0151] S53. Observation Results Stage
[0152] The Agent collects the analysis results returned by various tools and compares and verifies these results with the initial analysis. The tool results are returned in structured JSON format, and the Agent integrates these results into a chain of evidence. If the tool results are consistent with the initial analysis conclusions, the confidence level is increased; if there are contradictions, the results are marked for further analysis.
[0153] S4. Self-reflection stage
[0154] The critique module receives the current analysis results (including initial analysis and tool results) and evaluates them from three dimensions:
[0155] (1) Consistency check: Verify whether the analysis conclusions are consistent with the evidence returned by the tool. Specific check items include: whether the root cause hypothesis is supported by tool evidence, whether the problem type judgment matches the tool detection results, and whether the confidence score is consistent with the strength of evidence.
[0156] (2) Completeness check: Evaluate whether the analysis covers all relevant aspects. Specific check items include: whether all critical code paths (main path, exception path, boundary path) have been checked, whether all relevant variables and data structures have been checked, whether concurrency scenarios and timing issues have been considered, and whether important boundary conditions have been omitted.
[0157] (3) Evidence sufficiency check: Assess whether the evidence supporting the conclusion is sufficient. Specific check items include: whether there is direct code evidence to support the existence of the defect, whether there are historical defect cases for reference, whether the results of tool analysis point to the same conclusion, and whether there is any counter-evidence that has not been explained.
[0158] The criticism module outputs structured reflective feedback, including: consistency score / completeness score / sufficiency of evidence score, specific problem descriptions, and improvement suggestions.
[0159] S55. Iterative Optimization Phase
[0160] If the critique module determines that iteration is needed, the Agent controller re-analyzes the code based on the issues and improvement suggestions in the reflection feedback. The iterative optimization Prompt adds reflection feedback information to the initial Prompt.
[0161] The iteration termination conditions include the following three cases (any one of which will terminate the iteration): the critique module evaluation is passed (pass=true and needs_iteration=false), the maximum number of iterations is reached (the default value is 3), and the output results of two consecutive iterations are consistent (judged by JSON comparison).
[0162] S6. Confidence Calibration Phase
[0163] The system dynamically calculates the final confidence level based on multiple factors. The confidence level calculation formula is as follows:
[0164] Baseline confidence level = Instrumental consistency score × 0.4 + Evidence adequacy score × 0.3 + Historical reflection and feedback score × 0.3.
[0165] Where: Tool consistency score = Number of items whose tool results are consistent with the analysis conclusions / Total number of tool result items;
[0166] Sufficient evidence score = evidence_score output by the criticism module;
[0167] Historical reflection feedback score = accuracy rate of historical detection of this type of defect (statistics from the knowledge base).
[0168] Final confidence level = Base confidence level × Iteration decay coefficient.
[0169] in:
[0170] Iteration decay coefficient = 0.95^(iteration number - 1);
[0171] When the number of iterations is 1, the decay coefficient is 1.0;
[0172] When the number of iterations is 3, the decay coefficient is 0.9025.
[0173] The iterative decay mechanism encourages the agent to draw reliable conclusions within a smaller number of iterations, thus avoiding infinite iterations.
[0174] The system achieves deep code reasoning through the method described in this embodiment. Compared to a single large language model call, this method analyzes the code from multiple perspectives through tool calls, identifies and corrects blind spots through self-reflection, continuously improves the analysis quality through iterative optimization, and finally outputs highly reliable detection results.
[0175] like Figure 7 As shown, this embodiment describes the end-to-end workflow of the intelligent detection method for logical defects based on business semantic enhancement, specifically including the following steps:
[0176] Step 1: System Initialization. Upon system startup, the vector database and relational database are initialized, and necessary indexes are created. The code parser is initialized, supporting multiple programming languages. The graph neural network model is initialized, loading the pre-trained code representation model. The large language model service is initialized. Tools are initialized, including a data flow analyzer, boundary condition detector, business rule validator, and code difference comparator.
[0177] Step 2: Building a Historical Defect Knowledge Base. The system collects historical defect information from historical scan records, external defect tracking systems, production incident reports, and code commit records. For each historical defect, multi-dimensional information is collected, including basic information, business context, root cause analysis, code context, remediation plan, defect pattern characteristics, and statistical information. A vector database is used to store the semantic vectors of the defects and the semantic vectors of the code, and a relational database is used to store structured metadata. A knowledge base quality report is generated, which summarizes the number of defects, the business domains covered, and the distribution of defect types.
[0178] Step 3: Code Scanning Task Creation. Users create a code scanning task by filling in the task name, selecting the code repository, choosing the programming language, and selecting the business domain. The system pulls the code to be scanned from the code repository, parses the code, and generates an abstract syntax tree, control flow graph, program dependency graph, and business semantic graph.
[0179] Step 4: Multimodal code representation learning. The system uses graph neural networks to learn embedded representations of abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs. It then uses a multimodal fusion mechanism to fuse these embedded representations to generate code semantic vectors.
[0180] Step 5: Hierarchical Search. The system performs a four-layer hierarchical search: the first layer, coarse-grained search, recalls a first preset number of candidate historical defects; the second layer, medium-grained search, recalls a second preset number of candidate historical defects; the third layer, fine-grained search, recalls a third preset number of candidate historical defects; and the fourth layer, business rule search, recalls a fourth preset number of candidate historical defects. Search enhancement techniques are used to incorporate a preset number of similar historical defects as context.
[0181] Step 6: Adaptive Agent Inference. The system constructs an adaptive agent inference engine. Initial analysis allows the large language model to generate preliminary analysis results. Tool invocation allows the agent to call tools for in-depth analysis. Observation results allow the agent to collect and synthesize the results returned by the tool. Self-reflection allows the agent to evaluate whether the analysis is comprehensive and check for omissions. Iterative optimization re-analyzes based on reflection feedback. Confidence calibration dynamically adjusts the confidence level based on the number of iterations, consistency of tool analysis results, and historical reflection feedback.
[0182] Step 7: Result Verification and Reporting. The system verifies the results based on the confidence level output by the large language model. High confidence levels automatically generate defect reports, medium confidence levels are marked as requiring manual confirmation with suggestions, and low confidence levels are ignored. Defect reports contain a detailed chain of evidence, including similar historical defects, tool analysis results, reasoning processes, and remediation suggestions. Feedback from manual confirmation is recorded and used to optimize prompts and the model.
[0183] Through the above process, the system realizes a complete closed loop from the construction of a historical defect knowledge base, code representation learning, hierarchical retrieval, adaptive agent reasoning to defect report generation, meeting the needs of enterprise code quality assurance, DevSecOps platform and intelligent operation and maintenance system.
[0184] Example 3: Based on Example 1, this example provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the method described in Example 1.
[0185] Example 4: Based on Example 1, this example provides a computer device, including a memory and a processor. The memory stores a computer program, and the processor executes the computer program to implement the method described in Example 1.
[0186] Example 5: Based on Example 1, this example provides a computer program product, including a computer program that, when executed by a processor, implements the method described in Example 1.
[0187] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-usable storage media (including but not limited to disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0188] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, as well as combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0189] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1The function specified in one or more boxes.
[0190] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0191] The above description is only a preferred embodiment of this application. It should be noted that for those skilled in the art, several improvements and modifications can be made without departing from the principle of this application, and these improvements and modifications should also be considered within the scope of protection of this application.
Claims
1. A logical defect intelligent detection method based on business semantic enhancement, characterized in that, include: S1. Construct a historical business defect knowledge base using multi-dimensional information about historical defects. The historical business defect knowledge base stores the business domain, language, file path, code semantic vector, defect code graph structure, and business rules for each historical defect. S2. Extract business domain, language, file path, and business rules from the code to be detected; use a pre-trained code model to generate a code semantic vector based on the code to be detected; S3. Perform multimodal representation learning on the code to be detected, and use a multimodal fusion mechanism to fuse the embedded representations of abstract syntax tree, control flow graph, program dependency graph and business semantic graph to generate code graph structure; S4. Based on the business domain, language, file path, code semantic vector, code graph structure and business rules of the code to be detected, a hierarchical retrieval strategy is used to filter out a preset number of similar historical defects from the historical business defect knowledge base. S5. Input the code to be detected and similar historical defects into the adaptive agent inference engine, and use natural language instruction-driven tools to perform static and dynamic analysis on the code to be detected, and generate defect detection results in a comprehensive manner. The defect detection results include whether a problem exists, the type of problem, the confidence level, the root cause, the scope of impact, and repair recommendations. S6. Verify the results based on the confidence level output by the adaptive agent inference engine and generate a defect report.
2. The method according to claim 1, characterized in that, Build a historical business defect knowledge base, including: recording multi-dimensional information for each historical defect, including basic information, business context, root cause analysis, code context, remediation plan, defect pattern characteristics and statistical information; The basic information includes defect identifier, title, severity, business domain, business scenario, first discovery time, and number of occurrences; The business context includes an impact description, affected users, affected functions, and the scope of business impact, which describes why this defect is important to the business. Root cause analysis includes direct causes, underlying causes, and design flaws. Direct causes describe problems at the code level, underlying causes analyze the root causes of problems in requirements, design, and processes, and design flaws point out deficiencies at the architecture or design level. The code context includes programming language, file path, class name, method name, line number, code snippet, API endpoint, and data table, which are used to provide complete code context information; The fix plan includes a fix description, code differences, and test cases, which detail how to fix the defect and how to verify the fix. Defect pattern features include pattern type, key indicators and similar keywords, which are used to extract the essential features of defects and facilitate the subsequent identification of similar defects. The statistics include affected items, recurrence rate, and average repair time, used to quantify the impact of defects and the difficulty of repair.
3. The method according to claim 1, characterized in that, S3 includes: Construct an abstract syntax tree to represent the syntax structure of the code. Nodes include classes, methods, variables, and expressions, while edges include inclusion, invocation, and reference. Construct a control flow graph to represent the execution logic of the code. Nodes include basic blocks, and edges include conditional jumps and loops. Construct a program dependency graph to represent the data dependencies of the code. Nodes include statements and variables, and edges include data dependencies and control dependencies. Constructing a business semantic graph includes: extracting business entities from code; extracting business rules from code, including business constraints, business logic, and business processes; extracting business operations from code, including creation, update, deletion, and query; and constructing relationships between business entities, business rules, and business operations to obtain a business semantic graph, including business processes, data flow, and rule constraints. Graph neural networks are used to learn embedded representations of abstract syntax trees, control flow graphs, program dependency graphs, and business semantic graphs. For abstract syntax trees, graph attention networks are used to automatically focus on nodes and edges that are more critical to semantic understanding using attention mechanisms. For control flow graphs, gated graph neural networks are used to capture the dynamic characteristics of state transitions in the control flow through gating mechanisms. For program dependency graphs, a sampling aggregation strategy is introduced to improve computational efficiency while ensuring representation quality. Heterogeneous graph neural networks are used to learn embedded representations of business semantic graphs. These heterogeneous graph neural networks contain different types of nodes and edges, and meta-path aggregation is used to aggregate different types of neighbors. The code graph structure is obtained by fusing the embedded representations of the abstract syntax tree, control flow graph, program dependency graph, and business semantic graph using a multimodal fusion mechanism.
4. The method according to claim 1 or 3, characterized in that, The multimodal fusion mechanism adopts an adaptive selection strategy, dynamically selecting the fusion method based on code complexity, defect type, and real-time requirements; the fusion methods include splicing method, attention weighting method, and tensor fusion method; When the code complexity is below the first threshold or the detection scenario is real-time detection, the concatenation method is adopted; When the code complexity is between the first and second thresholds and the defect type is logic-based, an attention-weighted approach is used. When the code complexity exceeds the second threshold or the defect type is a business-related defect, the tensor fusion method is used.
5. The method according to claim 4, characterized in that, Code complexity is comprehensively evaluated by considering cyclomatic complexity, number of graph nodes, and number of graph edges. Defect types are identified as syntax defects, logic defects, or business defects through static analysis and pattern matching. Real-time requirements are categorized into batch detection, real-time detection, or online detection based on the detection scenario.
6. The method according to claim 1, characterized in that, S4 include: The first layer of coarse-grained retrieval includes business domain, language, and file path as search dimensions. It uses an inverted index to recall a first preset number of candidate historical defects. The second layer is a medium-granularity retrieval, with the retrieval dimension being the code semantic vector. Based on the code to be detected, a pre-trained code model is used to generate the code semantic vector, and a similarity algorithm is used to calculate the similarity. A second preset number of candidate historical defects is recalled, which is less than the first preset number. The third layer of fine-grained retrieval uses code graph structure similarity as the retrieval dimension. A graph matching algorithm is used to calculate the similarity between the code graph structure and the defective code graph structure, and a third preset number of candidate historical defects is recalled. The third preset number is less than the second preset number. The fourth layer is business rule retrieval, with the retrieval dimension being business rule pattern matching. Business rules are extracted from historical defects, directly matched with business logic defects, and a fourth preset number of candidate historical defects are recalled as similar historical defects.
7. The method according to claim 1, characterized in that, S5 include: S51 preliminary analysis involves combining the code to be detected with similar historical defects to form prompt words, which are then input into a large language model for analysis to obtain preliminary analysis results. The preliminary analysis results include the problem existence judgment, problem type, preliminary root cause hypothesis, and initial confidence level. S52 Tool Invocation: Based on the problem type, the corresponding tool is invoked to analyze the code to be detected and similar historical defects, and the tool analysis results are obtained; the tools include a data flow analyzer, a boundary condition detector, a business rule verifier, and a code difference comparator; S53 Observation: Integrating the results of instrumental analysis into a chain of evidence; S54 Self-Reflection: The criticism module compares the results of the tool analysis with the preliminary analysis results, checks the consistency, completeness and sufficiency of the evidence, and obtains reflective feedback; S55 Iterative Optimization: If the analysis is deemed insufficient, reflective feedback is added to the prompt words, and S51-S54 are executed iteratively until the iteration termination condition is met, and the final analysis result is output. S56 Confidence Calibration: The confidence level of the large language model is dynamically adjusted based on the number of iterations, consistency of tool analysis results, sufficiency of evidence, and historical reflection feedback.
8. The method according to claim 7, characterized in that, The tool invocation steps include: Data flow analyzers track the flow path of variables and detect data inconsistencies and loss of accuracy; The boundary condition detector detects if statements, loop statements, and exception handling, and identifies missing boundary conditions. The business rule validator verifies whether the code implementation conforms to formal business constraints, which are extracted from historical defects. The code difference comparator compares the code to be detected with historical defective codes to identify similarities and differences.
9. The method according to claim 7, characterized in that, The self-reflection steps include: The critique module evaluates the quality of the current analysis results, taking into account factors such as the consistency, completeness, and sufficiency of evidence. The critique module generates reflective feedback that points out deficiencies and omissions in the analysis. If the reflection feedback indicates that the analysis is insufficient, the Agent re-analyzes the code based on the reflection feedback; if the reflection feedback indicates that the analysis is sufficient, the iteration stops.
10. The method according to claim 1, characterized in that, S6 includes: Based on the confidence level output by the large language model, the report is classified into levels. High confidence level results in automatic creation of defect reports, medium confidence level results are marked as requiring manual confirmation, and low confidence level results are ignored. For results with medium confidence, a detailed chain of evidence and suggested manual verification steps are provided. The chain of evidence includes similar historical defects, tool analysis results, reasoning process, and remediation suggestions. Feedback from manual verification is recorded and used to optimize the prompt and model.
11. A logical defect intelligent detection system based on business semantic enhancement, characterized in that, Including processor and storage media; The storage medium is used to store instructions; The processor is configured to operate according to the instructions to perform the method according to any one of claims 1 to 10.