Architecture defect detection method and device based on knowledge graph

By constructing an enhanced knowledge graph based on knowledge graphs, parsing source code, and performing pattern matching, the problems of low efficiency and insufficient deep defect identification in traditional methods are solved, achieving efficient architectural defect detection and report generation, and improving the quality and maintainability of software systems.

CN121833451APending Publication Date: 2026-04-10CHINA CONSTRUCTION BANK
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-19
Publication Date
2026-04-10

AI Technical Summary

Technical Problem

Existing technologies struggle to automatically identify and warn of deep-seated architectural design flaws such as illegal dependencies, harmful circular dependencies, and violations of design patterns between architectural layers in software development. Traditional manual reviews are inefficient and inconsistent, while automated tools lack deep semantic understanding capabilities.

Method used

By constructing an enhanced knowledge graph based on knowledge graphs, the source code is parsed to generate an abstract syntax tree, and pattern matching is performed on the graph based on predefined rules to identify architectural design defects and generate structured walkthrough reports.

Benefits of technology

It enables automated, in-depth architectural quality analysis and early warning, improves the efficiency and accuracy of code reviews, and ensures the consistency and maintainability of the system architecture.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121833451A_ABST
    Figure CN121833451A_ABST
Patent Text Reader

Abstract

The invention discloses an architecture defect detection method and device based on a knowledge graph, and belongs to the technical field of software engineering and artificial intelligence. Generating an abstract syntax tree by analyzing source codes and dependency configuration, and extracting a code entity and a syntax relationship to construct an initial knowledge graph; performing role and architecture layer labeling on the nodes based on a preset architecture semantic rule to form an enhanced knowledge graph; loading an architecture semantic rule base, analyzing the graph query statement into an executable instruction, and executing mode matching on the enhanced knowledge graph to detect architecture design defects; and generating a structured walkthrough record according to a matching result, and mapping the structured walkthrough record to the specific position of the source code through node position metadata to form an automatic code walkthrough report containing defect description. According to the invention, automatic and accurate detection of architecture defects is realized, and the efficiency and reliability of code quality evaluation are improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of software engineering and artificial intelligence technology, and in particular to a method, apparatus, device and storage medium for detecting architectural defects based on knowledge graphs. Background Technology

[0002] In the software development lifecycle, code review is a critical quality assurance activity for ensuring the intrinsic quality of software, identifying potential defects, and maintaining the consistency of system architecture. However, the code review techniques currently widely used in the industry have inherent limitations and are difficult to meet the needs of modern complex software systems for architectural governance and efficient quality control, specifically in the following two aspects: First, the effectiveness of traditional code review methods, which rely on human expert review, is largely limited by the depth of experience, breadth of knowledge, and available time of the reviewers. This process is typically time-consuming, and review standards vary from person to person, leading to highly subjective and unrepeatable review results, making it difficult to establish a stable and unified evaluation system. In the rapid iterative environment dominated by agile development and continuous integration / continuous delivery (CI / CD) paradigms, this highly manual and inefficient review model has become a significant bottleneck affecting the smoothness of the development process and project delivery schedule.

[0003] Secondly, while widely used automated static code analysis tools improve detection efficiency to some extent, their technical focus is primarily on syntax-level checks (such as code formatting and naming conventions) and local, predefined defect pattern matching (such as null pointer references and unreleased resources). These tools lack a deep understanding and analytical capability regarding the overall architectural design intent of the codebase, high-order semantic dependencies between modules, and the consistency of business logic across components. Therefore, they cannot effectively identify and warn of higher-level architectural design flaws and "design smells," such as "illegal direct dependencies between architectural levels," "harmful circular dependencies between packages or modules," and "violations of established design patterns or architectural styles." The legacy of these deep-seated flaws is a significant reason for the gradual decay of system architecture, rising maintenance costs, and the accumulation of technical debt, and existing automated tools have significant gaps in their detection capabilities in this area.

[0004] In summary, existing technologies are either limited by the efficiency and consistency issues of manual review, or lack the ability to analyze at the deep semantic and architectural levels. There is an urgent need for an innovative method that can deeply integrate code semantic understanding and architectural design rules to achieve automated and in-depth architectural defect detection. Summary of the Invention

[0005] The present invention aims to at least partially solve one of the technical problems in the related art.

[0006] To address this, the present invention discloses a knowledge graph-based method for detecting architectural defects. By parsing the source code, an enhanced knowledge graph containing architectural semantics is constructed. Based on predefined rules, pattern matching is performed on the graph to identify architectural design defects, and a structured walkthrough report mapped to specific locations in the source code is generated, thereby achieving automated and in-depth architectural quality analysis and early warning.

[0007] Another objective of this invention is to propose an architecture defect detection device based on knowledge graphs.

[0008] The third objective of this invention is to provide a computer device.

[0009] A fourth objective of this invention is to provide a non-transitory computer-readable storage medium.

[0010] To achieve the above objectives, this invention proposes a knowledge graph-based method for detecting architectural defects, comprising: S1: Obtain source code files and dependency configuration files, use a multi-language code parser to generate an abstract syntax tree, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph; S2, Based on preset architectural semantic rules, the initial nodes are labeled with roles, and the package and module nodes are labeled with architectural layers to form an enhanced knowledge graph containing architectural semantics; S3, load the predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects; S4 generates structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code, forming an automated code walkthrough report containing defect descriptions.

[0011] The knowledge graph-based architectural defect detection method of this invention may also have the following additional technical features: In one embodiment of the present invention, code parsing and abstract syntax tree generation include: S11 uses ANTLR and Tree-sitter parsers to perform lexical analysis on the source code file, decomposing the character stream into lexical units of keywords, identifiers, operators, constants, and delimiters; S12, perform syntactic analysis on the lexical unit sequence according to the grammar rules of the programming language, and construct a language-independent abstract syntax tree, which includes the hierarchical structure, syntactic relationships and architectural attributes of code entities.

[0012] In one embodiment of the present invention, the initial node is assigned a role based on preset architectural semantic rules, including: S21. Class and interface nodes are labeled with roles according to the naming conventions of code entities. Classes whose names end with Controller are labeled with the Controller role, and interfaces that inherit from JpaRepository are labeled with the Repository role. S22, by parsing the code package path and architecture configuration file, performs architecture layer annotation on package and module nodes, annotating packages with "presentation" in the path as the presentation layer, and modules with "domain" in the path as the business logic layer.

[0013] In one embodiment of the present invention, loading a predefined architecture rule base and parsing it into executable instructions includes: S31, based on the path of the code change and module information, filter the applicable rule subset and load only the rules related to the changed code; S32 optimizes graph query statements for multiple rules, including merging similar queries and optimizing traversal paths, to reduce the number of queries in the knowledge graph and improve traversal efficiency.

[0014] In one embodiment of the present invention, it further includes: S5 listens for push events and merge request events in the code repository. When a code change is detected, it triggers a walkthrough task and loads and executes applicable architectural rules from the rule base based on the context information of the changed code.

[0015] To achieve the above objectives, another aspect of the present invention proposes a knowledge graph-based architectural defect detection device, comprising: The code parsing and knowledge graph construction module is used to obtain source code files and dependency configuration files, generate an abstract syntax tree using a multi-language code parser, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph. The architecture semantic annotation module is used to annotate the initial nodes with roles based on preset architecture semantic rules, and to annotate the package and module nodes with architecture layer, forming an enhanced knowledge graph containing architecture semantics. The architecture rule matching module is used to load a predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects. The report generation and mapping module is used to generate structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code to form an automated code walkthrough report containing defect descriptions.

[0016] In one embodiment of the present invention, it further includes: The event listening and task triggering module is used to listen for push events and merge request events in the code repository. When a code change is detected, a walkthrough task is triggered, and applicable architectural rules are selected from the rule base based on the context information of the changed code for loading and execution.

[0017] This invention discloses a knowledge graph-based architectural defect detection method and apparatus. By constructing an enhanced knowledge graph that integrates architectural semantics and performing semantic rule matching, it effectively solves the core problems of low efficiency and inconsistent standards in traditional manual inspections, as well as the insufficient ability of existing static analysis tools to detect high-level architectural design defects. It achieves full-process automation from code parsing, semantic enhancement, rule matching to defect location and report generation, significantly improving the depth, accuracy, and efficiency of architectural defect identification. This provides an effective automated governance tool for ensuring software system architectural consistency, inhibiting architectural decay, and reducing maintenance costs.

[0018] To achieve the above objectives, a third aspect of this application provides a computer device, including a processor and a memory; wherein the processor reads executable program code stored in the memory to run a program corresponding to the executable program code, for implementing a knowledge graph-based architectural defect detection method as described in the first aspect embodiment.

[0019] To achieve the above objectives, a fourth aspect of this application provides a non-transitory computer-readable storage medium storing a computer program that, when executed by a processor, implements a knowledge graph-based architectural defect detection method as described in the first aspect.

[0020] Additional aspects and advantages of the invention will be set forth in part in the description which follows, and in part will be obvious from the description, or may be learned by practice of the invention. Attached Figure Description

[0021] The above and / or additional aspects and advantages of the present invention will become apparent and readily understood from the following description of the embodiments taken in conjunction with the accompanying drawings, wherein: Figure 1 This is a flowchart of a knowledge graph-based architectural defect detection method according to an embodiment of the present invention; Figure 2 This is a flowchart illustrating the specific steps of a knowledge graph-based architecture defect detection method according to an embodiment of the present invention. Figure 3 This is a flowchart of the code knowledge graph construction process for a knowledge graph-based architecture defect detection method according to an embodiment of the present invention; Figure 4 This is a schematic diagram of a knowledge graph-based architecture defect detection device according to an embodiment of the present invention. Figure 5 It is a computer device according to an embodiment of the present invention. Detailed Implementation

[0022] It should be noted that, unless otherwise specified, the embodiments and features described in the present invention can be combined with each other. The present invention will now be described in detail with reference to the accompanying drawings and embodiments.

[0023] To enable those skilled in the art to better understand the present invention, the technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings of the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of the present invention.

[0024] The following description, with reference to the accompanying drawings, describes a knowledge graph-based method, apparatus, device, and storage medium for detecting architectural defects according to embodiments of the present invention.

[0025] The core idea of ​​this invention is to construct an enhanced knowledge graph that integrates code syntax and architectural semantics, mapping code entities, syntactic relationships, and high-level design constraints to a unified semantic representation space. This enables structured modeling of the integrity and consistency of the system architecture design. Based on this graph, the system can automatically load predefined architectural rules, accurately identify deep-seated design flaws such as illegal dependencies and hierarchical confusion through graph pattern matching, and directly map the detection results back to the source code location. This transforms traditional code review, which relies on manual or shallow syntax analysis, into an intelligent architecture governance closed loop based on semantic understanding, automated execution, and precise location. Ultimately, this improves the efficiency and depth of code review while ensuring the long-term health and maintainability of the system architecture.

[0026] Example 1 To achieve the above invention, embodiments of the present invention provide a knowledge graph-based method for detecting architectural defects, such as... Figure 1 As shown, it includes: S1: Obtain source code files and dependency configuration files, use a multi-language code parser to generate an abstract syntax tree, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph.

[0027] Specifically, the process begins with a lexical analyzer segmenting the source code character stream into a series of minimal lexical units (tokens), including keywords (such as if, class), identifiers (such as variable names, class names), operators, constants, delimiters, etc. Subsequently, a parser, based on the target language's syntax rules (such as JavaCC for Java or PLY for Python), transforms these token sequences into a hierarchical Abstraction (AST), where each node represents a syntactic component in the code, such as a class declaration (ClassDeclaration) or a method declaration (MethodDeclaration).

[0028] Furthermore, this invention employs a language-independent AST construction method, adapting to the grammar rules of different languages ​​(such as ANTLR grammar files or Tree-sitter language definitions) to achieve unified parsing of multiple programming languages ​​(such as Java, Python, C#, etc.). The AST construction must satisfy grammatical correctness checks to ensure the generated tree structure conforms to language specifications, while also supporting the identification and recording of grammatical errors.

[0029] Specifically, the code parser needs to support loading multilingual syntax definition files, and its parsing accuracy should meet the requirements of language specifications such as ISO / IEC 9899 (C language standard) or JLS (Java Language Specification). AST nodes should contain complete syntax attribute information, such as class name, modifiers, method parameter list, return type, etc., and their storage format can be JSON or XML for easy subsequent processing.

[0030] Specifically, this step is widely applicable to projects developed using multiple languages, especially in microservice architectures and modular systems. It can effectively resolve cross-language dependencies, providing structured input for knowledge graph construction. Through the generation of the AST, the system can identify code entities and their syntactic relationships, laying the foundation for subsequent architectural semantic enhancement and pattern matching.

[0031] Specifically, this step transforms the raw code text into a structured syntax tree, providing a precise grammatical foundation for the construction of the knowledge graph, thereby improving the semantic depth and automation of code review.

[0032] Furthermore, S1 includes: S11 uses ANTLR and Tree-sitter parsers to perform lexical analysis on the source code file, decomposing the character stream into lexical units of keywords, identifiers, operators, constants, and delimiters.

[0033] Specifically, lexical analysis is the process of converting a sequence of characters in source code into a series of minimal lexical units (tokens). These units include keywords (such as if, class), identifiers (such as variable names, class names), operators (such as +, ==), constants (such as numbers, strings), delimiters (such as;, {}), etc. The lexical analyzer scans and matches the input character stream using predefined lexical rules (token rules) to identify semantically meaningful code segments.

[0034] Furthermore, both ANTLR and Tree-sitter support lexical rule definitions for multiple programming languages. For example, ANTLR defines lexical and syntactic structures through .g4 grammar files, while Tree-sitter is implemented using parsers in .c or .wasm format. During lexical analysis, the parser maintains a character position index (such as startLine, startCol, endLine, and endCol) for subsequent syntax analysis and error location. In addition, the token type of a lexical unit is typically represented by an integer; for example, the keyword CLASS might correspond to the integer 1001, the identifier IDENTIFIER to 1002, and the operator EQUALS to 1003, etc.

[0035] Specifically, this step is widely applicable to the automated analysis of multilingual code libraries, especially demonstrating good compatibility and parsing efficiency in mainstream development languages ​​such as Java, Python, and JavaScript. The results of lexical analysis will serve as the foundation for subsequent syntax analysis and knowledge graph construction, ensuring accurate parsing of code structure and complete extraction of semantic information.

[0036] Specifically, lexical analysis using ANTLR or Tree-sitter can efficiently and accurately convert source code into structured token sequences, providing high-quality input for building abstract syntax trees and knowledge graphs. This step significantly improves the automation of code parsing and cross-language support, and is a key prerequisite for high-level architectural reviews and defect detection.

[0037] S12, perform syntactic analysis on the lexical unit sequence according to the grammar rules of the programming language, and construct a language-independent abstract syntax tree, which includes the hierarchical structure, syntactic relationships and architectural attributes of code entities.

[0038] Specifically, the core of this step is to transform the source code from a linear text form into a structured tree representation, thereby providing a foundation for subsequent code entity extraction and architectural semantic enhancement.

[0039] Specifically, this process typically consists of two stages: lexical analysis and syntax analysis. The lexical analyzer segments the source code character stream into a series of lexical units (tokens), such as keywords (if, class), identifiers (variable names, class names), operators (+, ==), constants (numbers, strings), and delimiters (commas, semicolons). The parser, based on the context-free grammar (CFG) of the target programming language or the syntax rules provided by parser generation tools (such as ANTLR, Tree-sitter), recursively descents or bottom-up parses the sequence of lexical units to construct a syntax tree that conforms to the language structure. Furthermore, to achieve a language-independent abstract syntax tree, the system standardizes and abstracts the grammatical structure of the specific language, removing redundant information related to language implementation details while retaining the hierarchical structure, syntactic relationships, and architectural attributes of the code entities.

[0040] Furthermore, the parsing process requires configuring a language-specific parser rule set, such as ANTLR's .g4 grammar file or Tree-sitter's .wasm parser module. The parser's output must conform to the standard AST structure, including node types (such as ClassDeclaration, MethodDeclaration), node attributes (such as name, modifiers), and parent-child node relationships (such as CONTAINS, CALLS). When constructing the AST, the system typically sets a maximum recursion depth limit (such as 1000 levels) to prevent parsing anomalies or performance degradation caused by excessive nesting.

[0041] Specifically, this step is widely used for the unified parsing and analysis of multi-language code libraries, such as mixed projects using languages ​​like Java, Python, and JavaScript. By constructing a language-independent AST, the system can uniformly handle code structures from different languages, providing a consistent data model for subsequent knowledge graph construction.

[0042] Specifically, this step enables standardized modeling of the code structure, laying the foundation for entity extraction and architectural semantic enhancement. Through the construction of the Abstract Syntax Tree (AST), the system can accurately identify the syntactic structure and entity relationships in the code, thereby improving the accuracy and automation of code reviews.

[0043] S2, based on preset architectural semantic rules, the initial nodes are labeled with roles, and the package and module nodes are labeled with architectural layers to form an enhanced knowledge graph containing architectural semantics.

[0044] Specifically, the core of this step lies in mapping code entities to specific roles or levels in the software architecture through semantic analysis and rule matching, thereby giving the knowledge graph the ability to understand the system structure at a high level.

[0045] Specifically, this step first relies on the Abstract Syntax Tree (AST) and entity extraction results generated during the code parsing phase. The system identifies the role of each code entity by loading a predefined architectural semantic rule library. For example, for a class node, if its class name ends with "Controller," or its inheritance / implementation relationship contains a specific framework class (such as the `@RestController` annotation in Spring), the system marks it as a "Controller" role. Similarly, if a class implements the `JpaRepository` interface, it is marked as a "Repository" role. For package or module nodes, the system categorizes them into architectural layers such as presentation layer, business logic layer, and data persistence layer by parsing their path naming rules (such as `com.example.presentation`, `com.example.persistence`) or reading architectural configuration files (such as module definitions in `pom.xml` and `build.gradle`).

[0046] Furthermore, each rule in the architecture semantic rule base includes a rule identifier, triggering condition, constraints, and matching pattern. For example, a role annotation rule can be defined as: IF (class.name.endsWith("Controller") OR class.annotations.contains("@RestController")) THEN class.role = "Controller". Architecture layer annotation rules can be based on path matching, such as IF (package.path.startsWith("com.example.presentation")) THEN package.layer = "Presentation". In addition, the system supports rule priority settings (e.g., priority = 1) and conflict resolution strategies (e.g., override = true) to ensure correct annotation when multiple rules are matched.

[0047] Specifically, this step is widely used in complex systems such as microservice architectures and layered architectures (e.g., MVC). By labeling roles and layers, the system can identify architectural design problems such as cross-layer calls, circular dependencies, and obfuscated component responsibilities. For example, if the "Controller" class directly calls the "Repository" class, it violates the dependency constraints of the layered architecture, and the system will generate a walkthrough record accordingly.

[0048] Specifically, this step significantly enhances the semantic richness and analyzability of the knowledge graph, providing a structured semantic foundation for subsequent pattern matching and code walkthroughs. By introducing architectural roles and hierarchical information, the system can achieve high-level review of the code structure, thereby enhancing the accuracy and automation of code walkthroughs.

[0049] Furthermore, S2 includes: S21. Class and interface nodes are labeled with roles according to the naming conventions of code entities. Classes whose names end with Controller are labeled with the Controller role, and interfaces that inherit from JpaRepository are labeled with the Repository role.

[0050] Specifically, this step maps code entities to role labels with clear architectural semantics by parsing their naming characteristics and inheritance relationships, thereby improving the expressive power and analytical accuracy of the knowledge graph at the architectural level.

[0051] Specifically, this step first extracts the names of classes or interfaces and their inheritance relationships from the abstract syntax tree. For example, in Java, if an interface inherits from JpaRepository, the system traverses the syntax tree to identify its inheritance chain and extracts the interface name and the name of the class it inherits from. Further, the system loads a pre-defined naming convention rule library, which contains regular expressions and inheritance relationship matching rules. For example, `.*Controller` matches class names ending in `Controller`, `.*Repository` matches class names ending in `Repository`, or it identifies whether an interface inherits from standard framework interfaces such as JpaRepository through inheritance relationships. During code entity identification, the system performs regular expression matching on class names or interface names. If a match is successful, it assigns the corresponding architectural role label, such as `Controller`, `Repository`, or `Service`.

[0052] Furthermore, the regular expressions in the naming convention rule library must meet the syntax requirements of the project language. For example, in Java, class names typically follow the UpperCamelCase naming convention, so the regular expression should be ^[AZ][a-zA-Z0-9]*Controller. In addition, inheritance matching must be based on the language's syntax structure. For instance, in Java, interface inheritance is expressed using the `extends` keyword, and the system needs to recognize this keyword and its suffix class name, and match it with known framework interfaces (such as JpaRepository).

[0053] Specifically, this step is widely used in project structures such as microservice architecture and layered architecture (such as MVC) to automatically identify the responsibility boundaries of components at each layer. For example, in a Spring Boot project, the system can automatically identify UserController as the Controller role and UserRepository as the Repository role, thereby establishing a clear architectural hierarchy in the knowledge graph.

[0054] Specifically, this step significantly improves the intelligence level of code review through semantic enhancement, enabling the system to identify illegal dependencies between architectural layers, such as the controller layer directly calling data persistence layer components, thereby achieving automatic review of architectural design rules and improving code quality and system maintainability.

[0055] S22, by parsing the code package path and architecture configuration file, performs architecture layer annotation on package and module nodes, annotating packages with "presentation" in the path as the presentation layer, and modules with "domain" in the path as the business logic layer.

[0056] Specifically, this step is technically implemented based on semantic recognition of the path features and naming conventions of code entities, thereby achieving automatic parsing and classification of code structures.

[0057] Specifically, the system first obtains the path information of code packages through the file system or project build tools (such as Maven and Gradle). During path resolution, the system uses a regular expression matching strategy. For example, packages containing "presentation" in the path are marked as presentation layers; modules containing "domain" are marked as business logic layers. In addition, the system can read architecture configuration files (such as application.yml, pom.xml, or custom architecture description files) to extract the mapping relationship between modules and layers, and add architecture layer tags to the corresponding code nodes accordingly.

[0058] Furthermore, the system supports user-defined path matching rules and hierarchical mapping tables. The path matching pattern is / src / main / java / com / example / (presentation|domain|infrastructure), and each pattern is bound to a corresponding architecture layer tag. Simultaneously, the system allows configuration of path matching priority strategies to handle cases where multiple matching keywords exist in the path, ensuring the accuracy and consistency of the annotation.

[0059] Specifically, this step is widely applicable to code projects with layered architectures (such as MVC, Clean Architecture, and Hexagonal Architecture), especially in microservice architectures. It can automatically categorize multiple modules and help identify architectural violations such as cross-layer dependencies and circular references. Through architectural layer annotation, the system provides a semantic foundation for subsequent graph queries and pattern matching, enabling the review rules to perform accurate matching and analysis based on the architectural hierarchy, thereby significantly improving the automation and depth of code reviews.

[0060] S3, load the predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects.

[0061] Specifically, the technical implementation of this step is based on the query language of graph databases (such as Cypher, Gremlin, etc.), which parses the graph query statements in the architecture rules into executable graph traversal instructions, and performs pattern matching on the enhanced knowledge graph to detect architectural design defects in the code.

[0062] Specifically, each rule in the architecture rule base contains a graph query statement that describes an architectural pattern that should be avoided in the code. For example, the rule "The controller layer should not directly depend on the data persistence layer" can be expressed as: starting from the class node labeled Controller, search for a class node directly connected to the class node labeled Repository or JpaRepository through CALLS or DEPENDS_ON relationships. The traversal engine first parses these graph queries to verify that their structure conforms to the specifications of the graph database query language and ensures that the referenced node labels (such as Class, Method, Controller) and relationship types (such as CALLS, DEPENDS_ON) exist and are valid in the knowledge graph. Subsequently, the engine compiles these queries into executable graph traversal instructions, such as generating Cypher statements in Neo4j or Gremlin scripts in JanusGraph.

[0063] Furthermore, this step involves several key parameters, including the complexity of the query statement (such as the number of nodes, edges, and path length), the coverage of the matching pattern (such as whether multi-level dependencies are supported and whether wildcard matching is allowed), and execution efficiency optimization strategies (such as query merging and path pruning). For example, if a rule's graph query statement involves a dependency chain with a path length of 3, its matching complexity can be expressed as O(n^3), where... This represents the average out-degree of nodes in the graph. To improve execution efficiency, the system can employ query optimization algorithms, such as merging multiple queries based on rule similarity, or accelerating graph traversal through pre-computed indexes.

[0064] Specifically, this step is widely applicable to complex software projects such as microservice architectures, layered architectures, and modular systems. For example, in a Spring Boot project, the system can detect whether an `@RestController` class directly calls the `JpaRepository` interface, thus violating the design principles of a layered architecture. By establishing clear architectural roles and dependencies in a knowledge graph, this step enables a global review of the code structure, rather than being limited to local syntax or coding standards.

[0065] Specifically, this step automates the review of high-level code structure by transforming architectural rules into executable graph query instructions, significantly improving the accuracy and consistency of code reviews. Simultaneously, through pattern matching technology, the system can identify architectural defects that are difficult for traditional static analysis tools to detect, thereby enhancing the maintainability and scalability of the software system.

[0066] Furthermore, S3 includes: S31 filters the applicable rule subset based on the code change path and module information, and loads only the rules related to the changed code.

[0067] Specifically, the core of this step lies in achieving efficient loading and execution of rules through a context-aware rule matching mechanism, thereby improving the efficiency and accuracy of code review.

[0068] Specifically, the system obtains a set of paths to changed files by listening for push events from the code repository (such as Git push or merge request events). Then, the walkthrough engine filters rules related to these paths from the rule base based on path matching strategies. For example, if the changed file is located in the `src / controller / ` directory, the system will load all rules containing constraints related to the Controller architecture role or presentation layer architecture. Rule matching can use regular expressions (such as `^src / controller / .*\.java`) or path prefix matching (such as `startswith("src / controller")`) to ensure that rules only apply to code entities related to the changes.

[0069] Furthermore, each rule in the rule base includes a `trigger_path` field, which specifies the file path or module range to which the rule applies. During filtering, the walkthrough engine matches the changed paths against the `trigger_path` in the rules; if a match is found, the rule is added to the execution set. In addition, the system allows users to manually specify rule sets via configuration files or APIs, enabling more flexible rule loading control.

[0070] Specifically, the technical benefit of this step is a significant reduction in the computational overhead and memory usage of rule loading. By filtering rules at the path or module level, the system can avoid loading rules irrelevant to the current change, thereby reducing the complexity and execution time of graph queries. For example, in a system with 1000 rules, if the change involves only 5 modules, the number of rules to load can be reduced to less than 50, improving walkthrough efficiency by over 90%. This mechanism has significant application value in scenarios such as continuous integration pipelines and pre-commit code checks, enabling rapid and accurate architectural compliance verification.

[0071] S32 optimizes graph query statements for multiple rules, including merging similar queries and optimizing traversal paths, to reduce the number of queries in the knowledge graph and improve traversal efficiency.

[0072] Specifically, the core of this step lies in reducing the number of repeated accesses to the knowledge graph through semantic analysis and structural rewriting of graph query statements, thereby reducing system resource consumption and speeding up the overall walkthrough process.

[0073] Furthermore, the optimization process first parses the graph query statements in all loaded architecture rules to extract their query patterns, including node labels, relationship types, property constraints, and traversal paths. Then, the system uses a pattern matching algorithm to identify rules with the same or similar query structures; for example, multiple rules may involve a path pattern where the Controller node calls the Repository node. After identifying these similar queries, the system merges them into a unified graph query statement, avoiding multiple scans of the same subgraph by sharing intermediate results and path traversals.

[0074] Furthermore, this optimization process involves several key parameters, such as the query pattern similarity threshold. Used to determine whether two queries can be merged; path length limit. This is used to control the complexity of the merged query and prevent query performance degradation; as well as the query execution priority. This is used to determine the order in which the merged queries are executed in the execution queue. In a real system, It is usually set to 0.85. Limit to 5 levels to ensure query executability and response speed.

[0075] Specifically, this optimization step is widely used in continuous integration environments with large-scale codebases, especially in microservice or layered architecture systems where multiple rules may involve the same component hierarchy. By merging similar queries, the system can complete the matching of multiple rules in a single graph traversal, significantly reducing the number of queries and improving walkthrough efficiency.

[0076] Specifically, this step effectively reduces the query load on the graph database, decreases redundant calculations, and improves the overall throughput and response speed of the code walkthrough. In actual testing, the average query execution time after merging and optimization was reduced by more than 30%, while the system resource utilization rate decreased by about 20%, thus achieving efficient and scalable automated code walkthrough capabilities.

[0077] S4 generates structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code, forming an automated code walkthrough report containing defect descriptions.

[0078] Specifically, the technical implementation of this step is based on the code location metadata stored in the nodes of the knowledge graph. Through the mapping mechanism between the precise graph query results and the source code, the abstract architectural defects are concretized into locatable and traceable code problems.

[0079] Specifically, this step first receives the pattern matching results returned by the code walkthrough execution phase, which is a set of graph subgraphs that satisfy predefined architectural rules. Each subgraph contains several nodes (such as classes, methods, packages, etc.) and their relationships (such as calls, inheritance, dependencies, etc.). The system maps the nodes in the graph to specific locations in the source code by parsing the metadata attributes of these nodes, including file path (file_path), start line number (start_line), end line number (end_line), start column number (start_col), and end column number (end_col). For example, if the file_path of a certain type of node is / src / main / java / com / example / controller / UserController.java, the start_line is 15, and the end_line is 42, then the system can accurately locate the text range of that type in the source code.

[0080] Furthermore, the system transforms each matching result into a structured walkthrough record. The record format typically includes: rule identifier (rule_id), graph identifier of the involved node (node_id), defect type (defect_type), defect description (description), file path (file_path), and code location (start_line, end_line, etc.). These records can be organized into JSON or XML format for easy subsequent processing and integration.

[0081] Specifically, this step is widely used in continuous integration (CI) processes, automated pre-commit checks, and integrated analysis of code review platforms. For example, in GitLab or GitHub's CI / CD pipeline, the system can automatically perform a walkthrough task after each code push and provide real-time feedback to the developer's terminal or review interface, helping to quickly locate and fix architectural code defects.

[0082] Specifically, by precisely mapping defect information in the code map to their location in the source code, the operability and traceability of code reviews are significantly improved. Developers can jump directly to the problematic code without manually searching for defect locations, thereby improving defect fixing efficiency, reducing maintenance costs, and enhancing the standardization and consistency of the code architecture.

[0083] S5 listens for push events and merge request events in the code repository. When a code change is detected, it triggers a walkthrough task and loads and executes applicable architectural rules from the rule base based on the context information of the changed code.

[0084] Specifically, this step uses an event-driven approach to ensure that code changes can be detected in real time or near real time and trigger a walkthrough process, thereby improving the timeliness and accuracy of code quality assurance.

[0085] Specifically, the system listens for push or merge request events by integrating with the code repository's Webhook interface (such as APIs provided by platforms like GitLab, GitHub, and Gitee). When an event occurs, the system receives an event payload containing metadata such as the changed file path, commit information, and change type (add, modify, delete), and parses out the changed code entity and its module or package path. Further, the system matches this context information with a predefined architecture rule base, filtering out a subset of rules applicable to the current change. For example, if the change occurs in the `com.example.controller` package, the system only loads architecture rules related to the controller layer, such as the controller layer should not directly depend on the data persistence layer.

[0086] Furthermore, the event listening module needs to support multi-language code repositories (such as Git and SVN) and be compatible with the event formats of mainstream CI / CD platforms. The rule filtering process needs to be based on path matching algorithms (such as prefix matching and regular expression matching), with a matching accuracy of over 95% to ensure the accuracy of rule loading. In addition, the rule loading module needs to have a rule caching mechanism, with a cache hit rate of no less than 80%, to reduce the performance overhead caused by repeated parsing and compilation.

[0087] Specifically, this step is widely applicable to code quality assurance processes in continuous integration environments. For example, after each code commit or merge request update, the system automatically triggers a walkthrough task without manual intervention, thereby achieving real-time review of code changes. This mechanism is particularly suitable for complex systems such as microservice architectures and layered architectures, effectively identifying issues such as architectural hierarchy violations and abnormal component dependencies.

[0088] Specifically, this step significantly improves the response speed and execution efficiency of code review through an event-driven and context-aware rule loading mechanism. Simultaneously, by accurately matching change contexts and architecture rules, it avoids the resource waste caused by global scanning, enhances the system's ability to detect architectural consistency issues, and lays a solid foundation for subsequent graph pattern matching and report generation.

[0089] This invention discloses a knowledge graph-based architectural defect detection method. By constructing an enhanced knowledge graph that integrates architectural semantics and performing graph pattern matching, it effectively solves the core problem in existing technologies where architectural reviews rely on human experience and are difficult to automate in identifying high-level design defects. This method achieves closed-loop automation across the entire process, from code parsing, semantic enhancement, and rule matching to defect location and report generation, significantly improving the accuracy and efficiency of code reviews. Through an event-driven and context-aware rule loading mechanism, the system enhances its ability to conduct real-time review and continuous standardization of code changes, providing efficient automated tools to ensure the architectural consistency and maintainability of software systems.

[0090] Example 2 To achieve the above invention, embodiments of the present invention also provide specific steps of a knowledge graph-based architectural defect detection method, such as... Figure 2 As shown, it includes: The core of one embodiment of this invention lies in performing code parsing and architectural semantic enhancement on source code files to construct a semantically rich code knowledge graph. Simultaneously, architectural rules are loaded and pattern matching is performed on this graph. Based on the pattern matching results, structured walkthrough records are automatically generated, and these records are mapped to source code to form a walkthrough report, achieving high-level, automated code walkthroughs. Specifically, this includes: S101, Knowledge Graph Construction (e.g.) Figure 3(As shown).

[0091] S1011, Code Parsing and Abstract Syntax Tree Generation. Code parsing is the process of converting a sequence of source code characters into a structured representation (abstract syntax tree). Code parsing consists of two stages: lexical analysis and syntax analysis. Lexical analysis decomposes the source code character stream into a series of smallest lexical units, such as keywords (if, class), identifiers (variable names, class names), operators, constants, delimiters, etc. Syntax analysis parses the above unit sequence step by step according to the syntax rules of the programming language, identifies syntax errors, and constructs an abstract syntax tree. A source code parser (such as ANTLR, Tree-sitter, etc.) is used to perform lexical and syntax analysis on the project's source code files and dependency configuration files. For different programming languages, the corresponding syntax rules are used to generate language-independent abstract syntax trees. These abstract syntax trees can accurately reflect code entities, the relationships between code entities, and the architectural attributes of the code entities in a hierarchical structure.

[0092] S1012, Code Entity and Relationship Extraction. Traverse the generated abstract syntax tree to extract core code entities as candidate nodes for the knowledge graph. These include: files, packages, modules, classes, interfaces, methods, fields, variables, etc. For example: identify the ClassDeclaration node, extract attributes such as class name and modifiers, and create a Class entity; identify the MethodDeclaration node, extract the method name, return type, and parameter list, and create a Method entity. Extract the basic syntactic relationships between code entities as initial edges for the knowledge graph. These include: inheritance, implementation, inclusion, invocation, parameters, return, etc. For example: if a ClassDeclaration node contains a MethodDeclaration node, establish a CONTAINS edge between the corresponding Class entity and Method entity; traverse the MethodInvocation child nodes under the MethodDeclaration node, and establish a CALLS edge between the corresponding Method entity and the invoked Method entity.

[0093] S1013, Enhanced Architectural Semantics. Through predefined rules such as code entity annotations, naming conventions, project structure, and inheritance relationships, it annotates the architectural roles of class or interface nodes. For example, classes ending with "Controller" are annotated with the "Controller" role; if an interface inherits from "JpaRepository," it is annotated with the "Repository" role. By parsing code package paths or architecture configuration files, it annotates the architectural layer to which package or module nodes belong, such as the presentation layer, business logic layer, data persistence layer, and common library layer.

[0094] S1014, Knowledge Graph Construction and Storage. The nodes and edges, after architectural semantic enhancement, are used to construct a complete code knowledge graph. This graph is then stored in a graph database for subsequent graph query and traversal operations.

[0095] S102, Architectural rules loading.

[0096] Specifically, this step is used to read and parse at least one code walkthrough rule from a predefined architecture rule base. Each rule is an independent data unit containing elements such as rule identifier, rule metadata, triggering conditions, and core constraints.

[0097] Furthermore, the code review task is triggered when the system listens for one or more of the following events. The listening events include: the system listens for at least one of the following events: file saving or specific shortcut key commands; creation and updating of code repository push or merge requests; triggered by a scheduled task at a fixed time, such as every morning; or manually triggered by calling an API.

[0098] Furthermore, after an event is triggered, the walkthrough engine selects a subset of applicable rules from the rule base based on the context information of this walkthrough. For example, for paths or modules with changed code, only rules related to these modules are loaded; the user or system may specify the set of rules to be executed this time. The walkthrough engine reads the selected rules, performs syntax parsing on the graph query statements, verifies the correct structure of the query statements and the existence and validity of the referenced graph elements (such as node labels and relation types). Finally, the verified graph query statements are compiled into executable instructions. During this process, queries for multiple rules can be optimized, such as merging similar queries and optimizing traversal paths, to reduce the number of queries to the knowledge graph and improve walkthrough efficiency. S103, code walkthrough execution.

[0099] Specifically, this step is used to execute the compiled graph query instructions on the code knowledge graph to perform graph traversal and pattern matching. That is, starting from a certain starting point in the graph, the search is performed according to the constraints of the pattern (node ​​label, attribute, edge type, direction), and all subgraphs that satisfy the pattern description are traversed so that all constraints are met at the same time.

[0100] Furthermore, a successful match will return one or more nodes of the pattern, indicating that a vulnerability has been detected in the source code; otherwise, if the query result is empty, it means that no vulnerability exists in the source code. Finally, based on the pattern matching result, a structured walkthrough record is automatically generated, which includes: the triggering rule identifier, the identification of the involved nodes in the graph, and a detailed description of the vulnerability information. S104, Report generated.

[0101] Specifically, this step is used to map the walkthrough records to specific locations in the source code, and automatically generate a structured code walkthrough report based on the mapping results. The output walkthrough report is synchronously integrated into the development environment and code review platform.

[0102] The mapping rules are based on the location information metadata stored for each entity node during the knowledge graph construction phase. When the walkthrough execution engine generates a walkthrough record, for the entity nodes involved in the walkthrough record, the stored file path, starting line number / column number and other attributes can be directly read to locate the precise range in the source code, and then a standardized report can be generated.

[0103] This invention discloses a knowledge graph-based architectural defect detection method. By constructing an enhanced knowledge graph that integrates architectural semantics and performing graph pattern matching, it effectively solves the core problem of traditional code reviews relying on human experience and struggling to automate the detection of high-level design defects. It achieves a closed-loop automation of the entire process from code parsing, semantic enhancement, rule matching to defect location and report generation, significantly improving the accuracy and efficiency of architectural reviews. Through an event-driven and context-aware rule loading mechanism, the system enhances its ability to conduct real-time review and continuous standardization of code changes, providing efficient automated tools to ensure the architectural consistency and long-term maintainability of software systems.

[0104] Example 3 To achieve the above invention, such as Figure 4 As shown, this embodiment also provides a knowledge graph-based architecture defect detection device 10, which includes: The code parsing and knowledge graph construction module 100 is used to obtain source code files and dependency configuration files, generate an abstract syntax tree using a multi-language code parser, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph.

[0105] The architecture semantic annotation module 200 is used to annotate the initial nodes with roles based on preset architecture semantic rules, and to annotate the package and module nodes with architecture layer, forming an enhanced knowledge graph containing architecture semantics.

[0106] The architecture rule matching module 300 is used to load a predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects.

[0107] The report generation and mapping module 400 is used to generate structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code to form an automated code walkthrough report containing defect descriptions.

[0108] In one embodiment of the present invention, it further includes: an event listening and task triggering module, used to listen to push events and merge request events of the code repository, trigger a walkthrough task when a code change is detected, and select applicable architecture rules from the rule base according to the context information of the changed code for loading and execution.

[0109] This invention discloses a knowledge graph-based architecture defect detection device. By modularly integrating code parsing, semantic annotation, rule matching, and report generation functions, it effectively solves the core problems of traditional architecture review tools, such as low automation, lack of semantic understanding, and fragmented detection processes. The device achieves fully integrated automated processing from source code parsing, knowledge graph construction, semantic rule matching to defect location and report output, significantly improving the accuracy, timeliness, and traceability of architecture defect detection. Through event listening and context-aware rule triggering mechanisms, it enhances the system's adaptability to continuous integration environments, providing efficient automated tool support for ensuring the architectural quality and evolutionary consistency of complex software systems.

[0110] To implement the methods of the above embodiments, the present invention also provides a computer device, such as... Figure 5 As shown, the computer device 600 includes a memory 601 and a processor 602; wherein, the processor 602 reads the executable program code stored in the memory 601 to run a program corresponding to the executable program code, so as to implement the various steps of the knowledge graph-based architecture defect detection method described above.

[0111] To implement the above embodiments, this application also proposes a non-transitory computer-readable storage medium storing a computer program thereon, which, when executed by a processor, implements a knowledge graph-based architectural defect detection method as described in the foregoing embodiments.

[0112] In the description of this specification, the references to terms such as "one embodiment," "some embodiments," "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 the present invention. 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. Moreover, without contradiction, those skilled in the art can combine and integrate the different embodiments or examples described in this specification, as well as the features of different embodiments or examples.

[0113] Furthermore, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include at least one of that feature. In the description of this invention, "a plurality of" means at least two, such as two, three, etc., unless otherwise explicitly specified.

Claims

1. A knowledge graph-based method for detecting architectural defects, characterized in that, include: S1: Obtain source code files and dependency configuration files, use a multi-language code parser to generate an abstract syntax tree, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph; S2, Based on preset architectural semantic rules, the initial nodes are labeled with roles, and the package and module nodes are labeled with architectural layers to form an enhanced knowledge graph containing architectural semantics; S3, load the predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects; S4 generates structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code, forming an automated code walkthrough report containing defect descriptions.

2. The method as described in claim 1, characterized in that, Code parsing and abstract syntax tree generation, including: S11 uses ANTLR and Tree-sitter parsers to perform lexical analysis on the source code file, decomposing the character stream into lexical units of keywords, identifiers, operators, constants, and delimiters; S12, perform syntactic analysis on the lexical unit sequence according to the grammar rules of the programming language, and construct a language-independent abstract syntax tree, which includes the hierarchical structure, syntactic relationships and architectural attributes of code entities.

3. The method as described in claim 1, characterized in that, The initial nodes are assigned roles based on preset architectural semantic rules, including: S21. Class and interface nodes are labeled with roles according to the naming conventions of code entities. Classes whose names end with Controller are labeled with the Controller role, and interfaces that inherit from JpaRepository are labeled with the Repository role. S22, by parsing the code package path and architecture configuration file, performs architecture layer annotation on package and module nodes, annotating packages with "presentation" in the path as the presentation layer, and modules with "domain" in the path as the business logic layer.

4. The method as described in claim 1, characterized in that, Load the predefined architecture rule library and parse it into executable instructions, including: S31, based on the path of the code change and module information, filter the applicable rule subset and load only the rules related to the changed code; S32 optimizes graph query statements for multiple rules, including merging similar queries and optimizing traversal paths, to reduce the number of queries in the knowledge graph and improve traversal efficiency.

5. The method as described in claim 1, characterized in that, Also includes: S5 listens for push events and merge request events in the code repository. When a code change is detected, it triggers a walkthrough task and loads and executes applicable architectural rules from the rule base based on the context information of the changed code.

6. A knowledge graph-based architecture defect detection device, characterized in that, include: The code parsing and knowledge graph construction module is used to obtain source code files and dependency configuration files, generate an abstract syntax tree using a multi-language code parser, and extract code entities and corresponding basic syntactic relationships as the initial nodes and edges of the knowledge graph. The architecture semantic annotation module is used to annotate the initial nodes with roles based on preset architecture semantic rules, and to annotate the package and module nodes with architecture layer, forming an enhanced knowledge graph containing architecture semantics. The architecture rule matching module is used to load a predefined architecture semantic rule library, parse the graph query statements in the rules into executable instructions, and perform pattern matching on the enhanced knowledge graph to detect architecture design defects. The report generation and mapping module is used to generate structured walkthrough records based on pattern matching results. By reading the code location metadata stored in the nodes, the structured walkthrough records are mapped to specific locations in the source code to form an automated code walkthrough report containing defect descriptions.

7. The apparatus as claimed in claim 6, characterized in that, Also includes: The event listening and task triggering module is used to listen for push events and merge request events in the code repository. When a code change is detected, a walkthrough task is triggered, and applicable architectural rules are selected from the rule base based on the context information of the changed code for loading and execution.

8. An electronic device, comprising: processor; The memory stores executable instructions; when the processor executes the instructions, it implements the knowledge graph-based architectural defect detection method as described in any one of claims 1-5.

9. A computer-readable storage medium storing a computer program, wherein when the computer program is executed by a processor, it implements a knowledge graph-based architectural defect detection method as claimed in any one of claims 1-5.