Rule-driven software defect prediction method, system, and medium

By constructing a neural symbolic hybrid architecture, programming standards and security rules are formalized into logical constraints, which solves the problems of poor interpretability and spurious correlation in deep learning models, improves the interpretability and accuracy of software defect prediction, and is suitable for projects with insufficient labeled data.

CN123178235APending Publication Date: 2026-11-27SHENZHEN STREAMING VIDEO TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611393225.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-08
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing software defect prediction methods suffer from poor interpretability and are prone to learning spurious correlations. Deep learning models struggle to identify violations of programming standards or security guidelines and fail to effectively utilize prior knowledge from the software engineering field.

Method used

A neural symbolic hybrid architecture is constructed to formalize programming specifications and security rules into logical constraints. These constraints are then injected into the neural network training through differentiable logical reasoning. A learnable rule weight gating mechanism is used to balance the constraints of the logical rules, generating a structured explanation report.

Benefits of technology

It improves the interpretability and accuracy of prediction results, reduces reliance on labeled data, prevents spurious relevance features, ensures that prediction results conform to programming standards, and enhances stability across projects.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178235A_ABST
    Figure CN123178235A_ABST
Patent Text Reader

Abstract

The application discloses a rule-driven software defect prediction method, system and medium, and belongs to the technical field of software engineering, and comprises the following steps: converting programming specifications and safety rules in a logical rule library into a first-order logic formula; obtaining a total predicate prediction loss according to the truth value probability of each logical predicate obtained by a neural predicate network; performing consistency detection on each logical predicate according to the truth value probability of each logical predicate to obtain a consistency loss; calculating the satisfaction degree of the rule according to the first-order logic formula and the truth value probability; obtaining a logical constraint loss according to the satisfaction degree; calculating a defect probability according to the satisfaction degree and performing differential block positioning to obtain a classification loss of defect prediction; jointly adjusting the constraint weight according to the total predicate prediction loss, the logical constraint loss, the consistency loss and the classification loss; and generating an explanation report according to the defect probability and the differential block positioning. Through the differentiable logical reasoning, the application injects the constraint into the neural network training, so that the prediction result conforms to the field rules and has a clear logical explanation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of software engineering and artificial intelligence technology, and in particular to a rule-driven software defect prediction method, system, and storage medium. Background Technology

[0002] Just-In-Time (JIT) software defect prediction plays a crucial role in the software development process, enabling the timely identification of potential defect risks upon code submission. Existing methods primarily rely on deep learning models to learn the statistical correlation between code features and defects from large amounts of historical data.

[0003] Purely data-driven deep learning methods suffer from two fundamental problems. The first is poor interpretability. Deep neural networks are black-box models; developers cannot understand the logic behind the predictions. When a model outputs "high defect risk," developers don't know which specific coding style or security rule has been violated, making it difficult to take targeted remedial measures. The second problem is the tendency to learn spurious correlations. The model might use statistically relevant features unrelated to defects as the basis for predictions, such as associating "commit time late at night" with defects, while ignoring genuine code quality issues.

[0004] Existing technologies use posterior attribution methods such as attention weights or SHAP values ​​to explain prediction results. These explanations can only tell developers "which features the model focuses on," not "which rule the code violates." Furthermore, posterior attribution cannot guarantee that prediction results comply with basic programming standards and security guidelines—even if the code clearly violates the rule that "locks must appear in pairs," the model may still miss the warning due to insufficient training data.

[0005] From a technical perspective, existing methods fail to effectively utilize the rich prior knowledge accumulated in the field of software engineering. Programming standards, security guidelines, design patterns, and other knowledge exist in the form of logical rules, possessing clear semantics and universality. Integrating this knowledge into predictive models can both improve the reliability of predictions and output meaningful explanations. Summary of the Invention

[0006] To address the aforementioned technical problems in the existing technology, this application provides a rule-driven software defect prediction method, system, and storage medium. By constructing a neural symbolic hybrid architecture, programming specifications and security rules are formalized into logical constraints. These constraints are then injected into the neural network training through differentiable logical reasoning, enabling the prediction results to both conform to domain rules and have a clear logical interpretation.

[0007] To achieve the above objectives, the first technical solution adopted in this application is: automatically converting logical rules in the logical rule base into first-order logical formulas, wherein the logical rules include programming specifications and security rules, and the logical rules are represented using predicate logic; mapping code fragments to the truth probabilities of each logical predicate using a neural predicate network to obtain the total predicate prediction loss, and training a dedicated prediction head for each logical predicate; performing consistency detection on each logical predicate based on its truth probabilities to obtain a consistency loss; calculating the satisfaction level of the logical rules based on the first-order logical formula and the truth probabilities of each logical predicate; and utilizing... A learnable rule weight gating mechanism is used to weight and aggregate the satisfaction of logical rules to obtain the logical constraint loss of the logical rules; the defect probability is calculated based on the satisfaction of the logical rules and differential block localization is performed; the classification loss of defect prediction is calculated based on the defect probability; the constraint weight of the logical rules is dynamically adjusted based on the total predicate prediction loss, logical constraint loss, consistency loss and defect prediction classification loss, so as to balance and fit the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base; a structured interpretation report is generated based on the defect probability and differential block localization.

[0008] Preferably, the neural predicate network adopts an architecture of shared encoder plus multiple prediction heads. Furthermore, based on the truth probability of mapping code fragments to each logical predicate by the neural predicate network, the total predicate prediction loss is obtained, and a dedicated prediction head is trained for each logical predicate. This head includes: a shared encoder that receives the token sequence of the code fragment and its context based on a pre-trained code language model and outputs a context-aware vector representation. The shared encoder has a rule-aware local context window and a predicate consistency constraint head.

[0009] Preferably, the satisfaction of logical rules is calculated based on the first-order logic formula and the truth probability of each logical predicate, including: using the Lukasiewicz T-norm to realize the differentiability of logical operations, transforming the first-order logic formula into a continuous loss function that can participate in gradient descent, so that the rules can participate in neural network training as loss functions; and calculating the satisfaction of the rules corresponding to the differentiable mathematical expression based on the differentiable mathematical expression and the truth probability of each logical predicate in the current code segment.

[0010] Preferably, the defect probability is calculated based on the satisfaction of the logical rules and differential block localization is performed. The classification loss of defect prediction is calculated based on the defect probability, including: when the satisfaction of the rule is lower than the violation judgment threshold, the rule violates the corresponding rule in the logical rules.

[0011] Preferably, differential block localization includes: logical operations containing existence quantifiers, each logical predicate being differentiable under existence quantifiers, and obtaining an index of the "most important evidence instance" for use in subsequent localization; in differential block localization, based on the logical predicate with the lowest rule satisfaction, according to the rule of existence quantifiers, obtaining the index of the "most important evidence instance" corresponding to the logical predicate, and obtaining the most important evidence instance based on the index of the "most important evidence instance".

[0012] Preferably, the method further includes: if the most important evidence instance is within the differential range, mapping the code element corresponding to the most important evidence instance back to the differential block; if the most important evidence instance is not within the differential range, tracing back to the most recent change point of the same object as the most important evidence instance.

[0013] Preferably, the constraint weights of the logical rules are dynamically adjusted based on the total predicate prediction loss, logical constraint loss, consistency loss, and defect prediction classification loss. This balances and fits the prediction head data for each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base. This includes: jointly applying the total predicate prediction loss, logical constraint loss, and consistency loss, while optimizing prediction accuracy, rule conformity, and predicate consistency. The defect prediction loss uses weighted cross-entropy to handle class imbalance, and the consistency loss is used to ensure the output consistency of mutually exclusive predicates.

[0014] Preferably, a structured explanation report is generated based on the defect probability and differential block location, including: the structured explanation report contains the predicted value and confidence interval of the defect probability of the rules in the code snippet, the list of rules violated by the code snippet, the satisfaction score and violation intensity of the rules, the specific reasons for the rule violation, the range of the located differential blocks in the code, and rule-based repair suggestions.

[0015] The second technical solution adopted in this application is: providing a rule-driven software defect prediction system, comprising: a module for automatically converting logical rules in a logical rule base into first-order logical formulas, wherein the logical rules include programming specifications and security rules, and the logical rules are represented using predicate logic; a module for mapping code fragments to the truth probabilities of each logical predicate based on a neural predicate network to obtain the total predicate prediction loss, and training a dedicated prediction head for each logical predicate; a module for performing consistency detection on each logical predicate based on the truth probabilities of each logical predicate to obtain the consistency loss; and a module for calculating the satisfaction degree of the logical rules based on the first-order logical formulas and the truth probabilities of each logical predicate. The module includes: a module for weighted aggregation of logical rule satisfaction using a learnable rule weight gating mechanism to obtain the logical constraint loss of the logical rules; a module for calculating the defect probability and performing differential block localization based on the logical rule satisfaction, and calculating the classification loss of defect prediction based on the defect probability; a module for dynamically adjusting the constraint weights of logical rules based on the total predicate prediction loss, logical constraint loss, consistency loss, and defect prediction classification loss, thereby balancing and fitting the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule library; and a module for generating a structured explanation report based on the defect probability and differential block localization.

[0016] The third technical solution adopted in this application is: providing a computer-readable storage medium storing computer instructions, wherein the computer instructions are operated to execute the rule-driven software defect prediction method in Solution 1.

[0017] The beneficial effects of the technical solution proposed in this application are as follows: the prediction results are directly related to specific logical rules, allowing developers to clearly understand "which programming standard or security rule has been violated," which is easier to understand and accept compared to attention-weighted attribution; logical rules, as prior knowledge, constrain model learning, reducing reliance on large amounts of labeled data and making them suitable for projects with insufficient labeled data; rule constraints prevent the model from learning spurious related features unrelated to defects, ensuring that the prediction results conform to basic programming standards and reducing common-sense false positives; the rule weights adopt learnable gating, which can automatically adjust the rule strength in different projects and at different stages, improving stability during cross-project migration. Attached Figure Description

[0018] Figure 1 This is a flowchart illustrating a specific implementation of the rule-driven software defect prediction method in this application; Figure 2 This is a schematic diagram of the neural symbolic reasoning defect prediction system architecture in this application; Figure 3 This is a schematic diagram of the differentiable logic reasoning process in this application; Figure 4This is a schematic diagram of a specific implementation of the rule-driven software defect prediction system of this application. Detailed Implementation

[0019] The preferred embodiments of this application will now be described in detail with reference to the accompanying drawings, so that the advantages and features of this application can be more easily understood by those skilled in the art, thereby providing a clearer and more definite definition of the scope of protection of this application.

[0020] It should be noted that, in this document, relational terms such as "first" and "second" are used merely to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising..." does not exclude the presence of additional identical elements in the process, method, article, or apparatus that includes the element.

[0021] Figure 1 This is a flowchart illustrating a specific implementation of the rule-driven software defect prediction method in this application.

[0022] Figure 1The rule-driven software defect prediction method shown includes: process S101, automatically converting logical rules in the logical rule base into first-order logical formulas, wherein the logical rules include programming specifications and security rules, and the logical rules are represented using predicate logic; process S102, mapping code fragments to the truth probabilities of each logical predicate according to the neural predicate network, obtaining the total predicate prediction loss, and training a dedicated prediction head for each logical predicate; process S103, performing consistency detection on each logical predicate according to the truth probabilities of each logical predicate, obtaining the consistency loss; process S104, calculating the satisfaction of the logical rules according to the first-order logical formulas and the truth probabilities of each logical predicate; process S1 05. Using a learnable rule weight gating mechanism, the satisfaction of logical rules is weighted and aggregated to obtain the logical constraint loss of the logical rules; Step S106. The defect probability is calculated based on the satisfaction of logical rules and differential block localization is performed. The classification loss of defect prediction is calculated based on the defect probability; Step S107. Based on the total predicate prediction loss, logical constraint loss, consistency loss and defect prediction classification loss, the constraint weights of logical rules are dynamically adjusted to balance and fit the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base; Step S108. Based on the defect probability and differential block localization, a structured explanation report is generated.

[0023] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S101, which automatically converts the logical rules in the logical rule base into first-order logical formulas, wherein the logical rules include programming specifications and security rules, and the logical rules are represented by predicate logic.

[0024] In this specific implementation, the logic rule base module is responsible for storing formalized programming specifications and security rules, supporting the creation, deletion, modification, and querying of rules, as well as version management. This module provides rule templates and semi-automatic rule building tools, and has rule conflict detection capabilities to ensure consistency within the rule set.

[0025] As an example, programming standards and security rules are formalized as first-order logic formulas. The rules are represented using predicate logic, and each rule consists of an antecedent (condition) and a consequent (conclusion).

[0026] As an example, we define a basic set of predicates, which are divided into the following categories: Code structure predicates describe the syntactic structure features of the code. `HasLoop(x)` indicates that code snippet x contains a loop structure; `HasBranch(x)` indicates that code snippet x contains a branch structure; `HasRecursion(x)` indicates that code snippet x contains a recursive call; `HasException(x)` indicates that code snippet x contains exception handling; `DeepNesting(x)` indicates that the nesting depth of code snippet x exceeds a threshold. Resource operation predicates describe the allocation and release of resources. `MemAlloc(x)` indicates that code snippet x performs memory allocation; `MemFree(x)` indicates that code snippet x performs memory release; `FileOpen(x)` indicates that code snippet x opens a file handle; `FileClose(x)` indicates that code snippet x closes a file handle; `LockAcquire(x)` indicates that code snippet x acquires a lock; `LockRelease(x)` indicates that code snippet x releases a lock. Security check predicates describe the existence of security measures. `NullCheck(x)` indicates that code snippet x... Includes null pointer checks: `BoundCheck(x)` indicates that code snippet x includes bounds checks, `TypeCheck(x)` indicates that code snippet x includes type checks, and `InputValidation(x)` indicates that code snippet x includes input validation. Control flow relation predicates describe the execution order between code snippets: `Follows(y,x)` indicates that code snippet y follows code snippet x in control flow, `Precedes(y,x)` indicates that code snippet y precedes code snippet x in control flow, `SameScope(x,y)` indicates that code snippets x and y are in the same scope, and `PointerDeref(x)` indicates that code snippet x performs a pointer dereferencing operation. To avoid false positives when releasing or unlocking occurs on different objects, the system introduces object consistency predicates: `SameVar(x,y)` indicates that code snippets x and y operate on the same resource variable or the same lock instance (e.g., the same pointer, the same file handle variable, or the same lock instance).

[0027] As an example, the system pre-sets the following core rules in the rule base: the resource leakage rule requires that requested resources must be released; the null pointer dereference rule requires that pointers must be checked before use; and the concurrency safety rule requires that locks must appear in pairs.

[0028] As an example, taking memory as an example, the resource leak rule that requires requested resources to be released is formalized as follows:

[0029] Follows(y,x) indicates that y follows x in the control flow, and SameVar(x,y) indicates that the request and release operations point to the same resource variable.

[0030] As an example, the null pointer dereference rule, which requires checking a pointer before it is used, is formally expressed as follows:

[0031] Where Precedes(y,x) means that y is ahead of x in the control flow.

[0032] As an example, the concurrency safety rule requiring locks to appear in pairs is formalized as follows:

[0033] SameScope(x,y) indicates that x and y are in the same scope, and SameVar(x,y) indicates that locking and unlocking are performed on the same lock instance.

[0034] As an example, the rule base allows domain experts to extend custom rules through templates. The template format is an implication of "if...then...", which the system automatically converts into a first-order logic formula. This formalizes programming standards and security rules into first-order logic formulas, building an extensible code security rule base that supports a unified representation of various rules such as resource management, null pointer protection, and concurrency security.

[0035] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S102, which maps code fragments to the truth probabilities of each logical predicate according to a neural predicate network, obtains the total predicate prediction loss, and trains a dedicated prediction head for each logical predicate.

[0036] In this specific implementation, the neural predicate network adopts an architecture of shared encoder plus multiple prediction heads. The shared encoder is based on a pre-trained code language model, receives a sequence of tokens of code fragments and their context, and outputs a context-aware vector representation.

[0037] In this specific implementation, the shared encoder introduces a rule-aware local context window and a predicate consistency constraint head, so that the output code fragment of the neural network satisfies the probability truth value of each logical predicate, and the introduction of a rule-aware local context window improves the stability of predicate judgment.

[0038] In this specific implementation, the neural predicate network module encodes code snippets into vector representations and trains a dedicated prediction head for each logical predicate. It outputs the probability truth values ​​of the code snippets satisfying each predicate and supports predicate consistency constraints to prevent mutually exclusive predicates from being true simultaneously.

[0039] As an example, the shared encoder, based on a pre-trained code language model (such as GraphCodeBERT), receives a sequence of tokens representing code snippets and their context, and outputs a context-aware vector representation. Where x is the input code snippet, For rule-aware local context windows, This is a sequence concatenation operation. For the encoded vector representation, the dimension d is usually 768 (dimensionless).

[0040] As an example, the system makes two improvements to the basic encoder. The first improvement is the introduction of a rule-aware local context window. The encoder input includes not only the statement itself, but also neighboring statements related to the rule, such as the successor statement window of the resource request statement and the exception branch window of the lock statement, thereby improving the stability of predicate judgment. The system extracts slices related to variables in x through data flow analysis as... The second improvement is the introduction of a predicate consistency constraint header. The system adds a consistency penalty to mutually exclusive predicates; for example, the same statement should not be judged as both locked and unlocked at the same time.

[0041] As an example, the system provides each logical predicate P k An independent prediction head is constructed, consisting of two fully connected network layers. Where P k For the k-th logical predicate, The first layer weight matrix has a hidden dimension d. h Take 128 (dimensionless). This is the first layer bias vector (dimensionless). This is the second layer weight vector (dimensionless). Let σ(·) be the second-layer bias scalar (dimensionless), σ(·) be the sigmoid activation function, and ReLU(z) = max(0,z) be the linear rectified activation function. For code snippet x, satisfy the predicate P k The probability (dimensionless).

[0042] As an example, the training data for the prediction heads comes from two parts. One part is automatically labeled data from static analysis tools, and the other part is manually labeled high-confidence samples. The system uses cross-entropy loss to train each prediction head. in Let be the prediction loss for the k-th predicate (dimensionless), and n be the number of training samples (positive integer). For the i-th sample, for the predicate P k The true label (dimensionless). The probability predicted by the model (dimensionless, ranging from 0 to 1).

[0043] As an example, the total predicate prediction loss is the aggregation of all predicate losses. ,in The total predicate prediction loss is dimensionless, and K is the total number of predicates (a positive integer).

[0044] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S103, which performs consistency detection on each logical predicate based on the truth probability of each logical predicate to obtain consistency loss.

[0045] In this specific implementation, predicate consistency loss is used to ensure the output consistency of mutually exclusive predicates. in For predicate consistency loss (dimensionless), Mutex is the set of mutually exclusive predicate pairs, (k,k') is the index of the mutually exclusive predicate pair, such as locking and unlocking should not be true at the same time, p k ,p k' They are predicates P k and P k' The true probability (dimensionless).

[0046] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S104, which calculates the satisfaction degree of the logical rule based on the first-order logic formula and the truth probability of each logical predicate.

[0047] In this specific implementation, the following is adopted: The T-norm enables the differentiability of logical operations, transforming first-order logical formulas into continuous loss functions that can participate in gradient descent, allowing rules to be used as loss functions in neural network training.

[0048] In this specific implementation, the degree of satisfaction of the rule corresponding to the differentiable mathematical expression is calculated based on the differentiable mathematical expression and the truth probability of each logical predicate in the current code segment.

[0049] In this specific implementation, the differentiable logic reasoning module transforms first-order logic formulas into differentiable mathematical expressions and calculates rule satisfaction as a soft constraint loss. This module supports logical operations such as conjunction, disjunction, negation, and implication, and introduces learnable rule weight gating to adaptively adjust the impact of rules on the model.

[0050] As an example, the system uses the Lukasiewicz T-norm as the basis of fuzzy logic and defines continuous logical operations. The continuous representation of the conjunction operation (AND) is as follows: A∧B≈max(0,A+B-1); the continuous representation of the disjunction operation (OR) is as follows: A∨B≈min(1,A+B); the continuous representation of the negation operation (NOT) is as follows: ¬A≈1-A; and the continuous representation of the implication operation (IMPLIES) is as follows: A→B≈min(1,1-A+B), where A, B ∈ [0, 1] are the truth probabilities (dimensionless) of the logical propositions.

[0051] As an example, the continuity of the universal quantifier (FORALL) is implemented using a mean operator to provide a denser gradient signal and avoid gradient vanishing. Where n is the total number of candidate instances of variable x (a positive integer), x i For the i-th candidate instance, P(x) i ) for instance x i The probability of satisfying predicate P (dimensionless, value range [0, 1]).

[0052] As an example, the continuation of the existential quantifier (EXISTS) is achieved by taking a softmax weighted sum over all instances. Where β is the smoothing coefficient (dimensionless, ranging from 1 to 20). This form maintains differentiability under the presence of quantifiers and naturally yields the index of the "most important evidence instance" in the implementation, facilitating subsequent location.

[0053] As an example, the system will assign each rule R in the rule set to... j Transform into a differentiable expression And calculate the rule satisfaction level accordingly. , where R j For the j-th rule in the rule base, For rule R j The corresponding differentiable logic expression, s j ∈[0,1] is rule R j Satisfaction level (dimensionless), p1,…,p KThis represents the truth probability (dimensionless) of each predicate in the current code segment.

[0054] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S105, which uses a learnable rule weight gating mechanism to weighted aggregate the satisfaction of logical rules to obtain the logical constraint loss of the logical rules.

[0055] As an example, to avoid rule noise harming model performance, the system introduces learnable gating to the rule weights, enabling the model to automatically adjust the rule strength for different items, ω. j =softplus(u j ), where ω j For rule R j The weight (dimensionless, ranging from 0 to +∞), u j Let be the learnable parameters (dimensionless real numbers) of rule j, softplus(u)=log(1+exp(u)), to ensure that the weights are non-negative, so that the model can automatically adjust the strength of logical constraints in different projects and at different stages, thereby improving cross-project transfer and engineering adaptability.

[0056] As an example, the logical constraint loss is obtained by weighted aggregation of the satisfaction of all rules. in Let |R| be the logical constraint loss (dimensionless), |R| be the total number of rules (positive integer), and ω be the total number of rules. j Let s be the learnable weight of the j-th rule. j To determine the satisfaction level of rule j, a quadratic approach is used to strengthen the penalty for rules with low satisfaction levels. The rule weights employ learnable gating, which can automatically adjust the rule strength across different projects and stages, thereby improving stability during cross-project migration.

[0057] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S106, which calculates the defect probability based on the satisfaction of logical rules and performs differential block localization, and calculates the classification loss of defect prediction based on the defect probability.

[0058] In this specific implementation, the defect prediction loss uses weighted cross-entropy to handle class imbalance. Where n is the number of training samples or the number of batch samples (a positive integer), y j ∈{0,1} represents the true defect label of the i-th sample. w0 and w1 are the defect probabilities predicted by the model (dimensionless, ranging from 0 to 1), and w0 and w1 are the class weights, set according to the sample proportion (dimensionless).

[0059] In this specific implementation, if the satisfaction level of a rule is lower than the violation determination threshold, the rule violates the corresponding rule in the logical rules.

[0060] As an example, the system filters rules whose satisfaction level is below a threshold. Where ViolatedRules is the set of rules violated, R j For the j-th rule in the rule base, s j For rule R j Satisfaction level, θ viol =0.5 is the violation judgment threshold (dimensionless).

[0061] In this specific implementation, the logical operation includes an existence quantifier. Each logical predicate can remain differentiable under the existence quantifier and obtain an index of the "most important evidence instance" for use in subsequent location. In this specific implementation, in differential block localization, based on the logical predicate corresponding to the lowest rule satisfaction, and according to the rule of existence quantifier, the index of the "most important evidence instance" corresponding to the logical predicate is obtained, and the most important evidence instance is obtained based on the index of the "most important evidence instance".

[0062] In this specific implementation, when the most important evidence instance is within the differential range, the code element corresponding to the most important evidence instance is mapped back to the differential block; In this specific implementation, if the most important evidence instance is not within the differential range, the process is to backtrack to the most recent change point of the same object as the most important evidence instance.

[0063] As an example, for rules with quantifiers, output the evidence pairs that minimize the rule satisfaction, locate the range of newly added or modified statements, and mark the set of statements with the greatest change in predicate truth value.

[0064] As an example, to ensure the consistency of the positioning logic, the system retains the evidence index when calculating the satisfaction of each rule.

[0065] As an example, regarding existential quantifiers The record makes the existence quantifier contribute the most. (The primary evidence instance corresponding to SoftmaxPool); for resource / lock rules triggered by the antecedent, use... Constraints bind evidence pairs to the same object, preventing the assumption that "releasing other resources / unlocking other locks" satisfies the rule. During location, [the constraint will be used to]... The corresponding code element maps back-difference blocks; if If it is not within the difference range, then backtrack to the state with... The most recent change point for the same object (e.g., new statements added near the allocation / release of the same resource variable).

[0066] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S107, which dynamically adjusts the constraint weights of logical rules based on the total predicate prediction loss, logical constraint loss, consistency loss, and defect prediction classification loss, thereby balancing and fitting the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base.

[0067] In this specific implementation, the total predicate prediction loss, logical constraint loss, and consistency loss are combined to simultaneously optimize prediction accuracy, rule compliance, and predicate consistency; the defect prediction loss uses weighted cross-entropy to handle class imbalance; and the consistency loss is used to ensure the output consistency of mutually exclusive predicates.

[0068] As an example, this module designs a joint loss function that simultaneously optimizes prediction accuracy, rule compliance, and predicate consistency; the total loss function consists of four parts. in This is the total loss function (dimensionless). The classification loss for defect prediction, The supervised loss for predicate prediction. For the loss of logical constraint satisfaction, The loss is the predicate consistency loss. λ1 is the predicate supervision weight, which is 1.0 by default. λ2 is the logical constraint weight, which adopts a dynamic adjustment strategy (see below). λ3 is the consistency constraint weight, which is 0.5 by default.

[0069] As an example, the tradeoff coefficient λ² employs a dynamic adjustment strategy. Initially, it is set to a small value (e.g., 0.1) to allow the model to learn patterns in the data. As training progresses, it is gradually increased (eventually reaching 1.0) to strengthen the rule constraints. The adjustment formula is as follows: Where t is the current training round (positive integer), T is the total training rounds (positive integer), and λ min =0.1, λ max =1.0 is the weight boundary (dimensionless). The training algorithm uses the Adam optimizer, and the learning rate is set to 5×10. -5 The batch size is 32, and the training rounds are 20.

[0070] exist Figure 1 In one specific embodiment shown, the rule-driven software defect prediction method of this application includes process S108, which generates a structured interpretation report based on defect probability and differential block location.

[0071] In this specific implementation, the structured interpretation report includes the predicted value and confidence interval of the defect probability of the rules in the code snippet, the list of rules violated by the code snippet, the satisfaction score and violation intensity of the rules, the specific reasons for the rule violation, the range of the located code difference block, and rule-based remediation suggestions.

[0072] As an example, this module performs inference based on the trained model and outputs the defect prediction results and their logical explanations.

[0073] As an example, for each violated rule, the system extracts the specific predicate that caused the violation. Among them, FailedPredicates(R j To cause rule R j The set of failed predicates violated, P k For the k-th logical predicate, P k ∈R j Indicates the predicate P k Appears in rule R j In the formula, p k <θ pred This indicates that the probability of the predicate being truthy is lower than a threshold, and is therefore deemed not to meet the condition, θ. pred =0.5 is the predicate decision threshold (dimensionless).

[0074] As an example, the confidence interval is calculated using Monte Carlo Dropout during the inference phase; the system keeps Dropout enabled in the defect prediction head and repeats the inference N times for the same input to obtain the result. Then, the confidence interval is given using quantiles; this method is consistent with the model's output probability and does not rely on additional annotations, where N is the number of repeated inferences, typically ranging from 30 to 200 (integers). q (·) represents the quantile operator, and the confidence interval is taken as... The prediction results are directly linked to specific logical rules, allowing developers to clearly understand "which programming standard or security rule has been violated," making it easier to understand and accept compared to attention weight attribution.

[0075] Figure 2 This is a schematic diagram of the neural symbolic reasoning defect prediction system architecture in this application.

[0076] like Figure 2As shown, the logic rule base module is responsible for storing formalized programming specifications and security rules, supporting rule creation, deletion, modification, querying, and version management. This module provides rule templates and semi-automatic rule building tools, and has rule conflict detection capabilities to ensure consistency within the rule set. Each rule corresponds to a learnable weight, which is input into the differentiable logic reasoning module for logical formula transformation. The input layer converts code changes into token sequences, which are then input into the neural predicate network module. In the neural predicate network module, code fragments are encoded into vector representations through a shared encoder, and a dedicated prediction head is trained for each logical predicate. It outputs the probability truth value that the code fragment satisfies each predicate, and then performs a predicate consistency check, calculating the consistency loss in the constraint training module. The constraint training module is responsible for jointly optimizing the prediction loss, logical constraint loss, and predicate consistency loss through backpropagation. It can dynamically adjust constraint weights to balance data fitting and rule compliance, and supports online updates and incremental learning to adapt to constantly changing code environments. The differentiable logic reasoning module transforms first-order logic formulas into differentiable mathematical expressions and calculates rule satisfaction as soft constraint loss. This module supports logical operations such as conjunction, disjunction, negation, and implication, and introduces learnable rule weight gating to adaptively adjust the impact of rules on the model. The interpretable prediction module outputs defect probability predictions, identifies and outputs violated logical rules and their severity. This module can also locate specific code difference blocks and generate rule-based root cause analysis reports to guide developers in making fixes.

[0077] Figure 3 This is a schematic diagram of the differentiable logic reasoning process in this application.

[0078] like Figure 3 As shown, the rule formula is parsed based on the predicate probability to find the corresponding operation type. The conjunction operation (AND) is max(0, A+B-1), the disjunction operation (OR) is min(1, A+B), the negation operation (NOT) is 1-A, and the implication operation (IMPLIES) is min(1, 1-A+B). Then, satisfaction is calculated, followed by learnable weighting. This formula yields the logical constraint loss, and then the resulting structure is backpropagated using gradients.

[0079] Figure 4 This is a schematic diagram of a specific implementation of the rule-driven software defect prediction system of this application.

[0080] exist Figure 4In the specific embodiment shown, the rule-driven software defect prediction system of this application includes: a first-order logic formula conversion module 401, which automatically converts logic rules in the logic rule library into first-order logic formulas, wherein the logic rules include programming specifications and security rules, and the logic rules are represented using predicate logic; a dedicated prediction head training module 402, which maps code fragments to the truth probabilities of each logic predicate according to a neural predicate network, obtains the total predicate prediction loss, and trains a dedicated prediction head for each logic predicate; a consistency loss acquisition module 403, which performs consistency detection on each logic predicate according to the truth probabilities of each logic predicate, and obtains the consistency loss; and a logic rule satisfaction calculation module 404, which calculates the satisfaction of the logic rule according to the first-order logic formula and the truth probabilities of each logic predicate; The logical constraint loss acquisition module 405 is used to obtain the logical constraint loss of logical rules by weighted aggregation of the satisfaction of logical rules using a learnable rule weight gating mechanism; the defect prediction classification loss calculation module 406 is used to calculate the defect probability and perform differential block localization based on the satisfaction of logical rules, and calculate the classification loss of defect prediction based on the defect probability; the prediction head data balancing and fitting module 407 is used to dynamically adjust the constraint weights of logical rules based on the total predicate prediction loss, logical constraint loss, consistency loss and defect prediction classification loss, and then balance and fit the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base; the structured interpretation report generation module 408 is used to generate a structured interpretation report based on the defect probability and differential block localization.

[0081] In one specific embodiment of this application, a computer-readable storage medium stores computer instructions that are operated to perform the rule-driven software defect prediction method described in any embodiment.

[0082] In one specific embodiment of this application, a computer device includes a processor and a memory, the memory storing computer instructions, wherein the processor operates the computer instructions to execute the rule-driven software defect prediction method described in any embodiment. In the embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces; the indirect coupling or communication connection between apparatuses or units may be electrical, mechanical, or other forms.

[0083] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0084] The above are merely embodiments of this application and do not limit the scope of this patent application. Any equivalent structural transformations made using the content of this application's specification and drawings, or direct or indirect applications in other related technical fields, are similarly included within the scope of patent protection of this application.

Claims

1. A rule-driven software defect prediction method, characterized in that, include: The logical rules in the logical rule base are automatically converted into first-order logical formulas, wherein the logical rules include programming specifications and security rules, and the logical rules are represented using predicate logic. The total predicate prediction loss is obtained by mapping code snippets to the truth probabilities of each logical predicate using a neural predicate network, and a dedicated prediction head is trained for each logical predicate. Based on the truth probability of each logical predicate, a consistency check is performed on each logical predicate to obtain the consistency loss; The degree of satisfaction of the logical rule is calculated based on the first-order logic formula and the truth probability of each logical predicate. By utilizing a learnable rule weight gating mechanism, the satisfaction of the logical rules is weighted and aggregated to obtain the logical constraint loss of the logical rules; The defect probability is calculated based on the satisfaction of the logical rules and differential block localization is performed. The classification loss of defect prediction is calculated based on the defect probability. Based on the total predicate prediction loss, the logical constraint loss, the consistency loss, and the defect prediction classification loss, the constraint weights of the logical rules are dynamically adjusted to balance and fit the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rules in the logical rule base. A structured explanation report is generated based on the defect probability and the differential block location.

2. The rule-driven software defect prediction method according to claim 1, characterized in that, The neural predicate network employs a shared encoder plus multiple prediction heads architecture. Furthermore, the total predicate prediction loss is obtained by mapping code segments to the truth probabilities of each logical predicate using the neural predicate network, and a dedicated prediction head is trained for each logical predicate, including: The shared encoder, based on a pre-trained code language model, receives a sequence of tokens representing code snippets and their context, and outputs a context-aware vector representation, wherein... The shared encoder has a rule-aware local context window and a predicate consistency constraint head.

3. The rule-driven software defect prediction method according to claim 1, characterized in that, The step of calculating the satisfaction degree of the logical rule based on the first-order logic formula and the truth probability of each logical predicate includes: The Lukasiewicz T-norm is used to realize the differentiability of logical operations, transforming the first-order logical formula into a continuous loss function that can participate in gradient descent, so that the rule can be used as a loss function to participate in the training of the neural network. The degree of satisfaction of the rule corresponding to the differentiable mathematical expression is calculated based on the truth probability of each logical predicate in the current code segment.

4. The rule-driven software defect prediction method according to claim 1, characterized in that, The step of calculating the defect probability based on the satisfaction of the logical rules and performing differential block localization, and calculating the classification loss for defect prediction based on the defect probability, includes: If the satisfaction level of the rule is lower than the violation determination threshold, the rule violates the corresponding rule in the logical rule.

5. The rule-driven software defect prediction method according to claim 3, characterized in that, The differential block positioning includes: The logical operation includes an existence quantifier. Each logical predicate can remain differentiable under the existence quantifier and obtains an index of the "most important evidence instance" for use in subsequent location. In the differential block localization, based on the logical predicate corresponding to the lowest satisfaction of the rule, and according to the rule of the existence quantifier, the index of the "most important evidence instance" corresponding to the logical predicate is obtained, and the most important evidence instance is obtained based on the index of the "most important evidence instance".

6. The rule-driven software defect prediction method according to claim 5, characterized in that, include: If the most important evidence instance is within the differential range, the code element corresponding to the most important evidence instance is mapped back to the differential block; If the most important evidence instance is not within the differential range, then backtrack to the most recent change point of the same object as the most important evidence instance.

7. The rule-driven software defect prediction method according to claim 1, characterized in that, The step of dynamically adjusting the constraint weights of the logical rules based on the total predicate prediction loss, the logical constraint loss, the consistency loss, and the classification loss of the defect prediction, thereby balancing and fitting the prediction head data dedicated to each round of training for each logical predicate, until it conforms to the corresponding logical rules in the logical rule base, includes: By combining the total predicate prediction loss, the logical constraint loss, and the consistency loss, prediction accuracy, rule compliance, and predicate consistency are simultaneously optimized. The defect prediction loss uses weighted cross-entropy to handle class imbalance. The consistency loss is used to ensure the output consistency of mutually exclusive predicates.

8. The rule-driven software defect prediction method according to claim 1, characterized in that, The step of generating a structured interpretation report based on the defect probability and the differential block location includes: The structured interpretation report includes the predicted value and confidence interval of the defect probability of the rule in the code snippet, a list of rules violated by the code snippet, the satisfaction score and violation intensity of the rule, the specific reason for the rule violation, the range of the located code difference block, and repair suggestions based on the rule.

9. A rule-driven software defect prediction system, characterized in that, include: A first-order logic formula conversion module is used to automatically convert logic rules in the logic rule base into first-order logic formulas. The logic rules include programming specifications and security rules, and the logic rules are represented using predicate logic. A dedicated prediction head training module is used to map code snippets to the truth probabilities of each logical predicate based on the neural predicate network, obtain the total predicate prediction loss, and train a dedicated prediction head for each logical predicate. The consistency loss acquisition module is used to perform consistency detection on each logical predicate based on the truth probability of each logical predicate, and obtain the consistency loss. The logic rule satisfaction calculation module is used to calculate the satisfaction of the logic rule based on the first-order logic formula and the truth probability of each logic predicate. The logical constraint loss acquisition module is used to obtain the logical constraint loss of the logical rule by weighted aggregation of the satisfaction of the logical rule using a learnable rule weight gating mechanism. The defect prediction classification loss calculation module is used to calculate the defect probability based on the satisfaction of the logical rules and perform differential block localization, and calculate the classification loss of defect prediction based on the defect probability. The prediction head data balancing and fitting module is used to dynamically adjust the constraint weights of the logical rules based on the total predicate prediction loss, the logical constraint loss, the consistency loss, and the classification loss of the defect prediction, thereby balancing and fitting the prediction head data dedicated to each round of training for each logical predicate until it conforms to the corresponding logical rule in the logical rule base. A structured explanation report generation module is used to generate a structured explanation report based on the defect probability and the differential block location.

10. A computer-readable storage medium storing computer instructions, wherein the computer instructions are operated to perform the rule-driven software defect prediction method according to any one of claims 1-8.