A code retrieval method based on multi-granularity hybrid index and feedback driving

By establishing multi-granularity indexes and introducing controlled graph structure bias, and combining query complexity and missing information type selection for supplementary retrieval, the problem of insufficient information in existing code retrieval methods is solved, achieving more efficient code location and recall.

CN123178574APending Publication Date: 2026-11-27XIAMEN UNIV
View PDF 0 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

Existing code retrieval methods struggle to simultaneously consider symbol semantics, file context, and code structure relationships. They also lack supplementary retrieval strategies based on query difficulty and the type of missing information, leading to a disconnect between candidate recall, feedback expansion, and final ranking.

Method used

A multi-granularity index is established for the symbol layer, file layer, and call graph. A controlled graph structure bias is introduced through weighted inverse ranking fusion. Whether to supplement the search is determined based on the confidence of dense retrieval and the query complexity. List-style rearrangement and output verification are performed within a fixed candidate set.

Benefits of technology

It improves the accuracy and controllability of code location, reduces unnecessary feedback calculations, and enhances the targeting and robustness of target recall.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178574A_ABST
    Figure CN123178574A_ABST
Patent Text Reader

Abstract

The application discloses a code retrieval method based on multi-granularity hybrid index and feedback driving, and belongs to the field of computer information retrieval and software engineering. The method analyzes a code repository to establish a symbol layer, a file layer index and a call graph; receives a natural language query, performs three-channel retrieval and weighted fusion, and adds a controlled graph structure bias after the fusion; routes according to the highest cosine similarity and a threshold value, determines information sufficiency, missing type and query complexity by using a large language model when the confidence is low, performs graph traversal or query rewriting according to the missing type, and merges and updates the candidate within a budget; and finally, the application rearranges the candidate set in a list form, checks the serial number and outputs a real file or function. The application can improve code positioning accuracy, reduce invalid feedback calculation, and is suitable for defect positioning, code understanding, function reuse and context acquisition before code generation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of computer information retrieval and software engineering technology, specifically to a code retrieval method based on multi-granularity hybrid indexing and feedback-driven approach. Background Technology

[0002] As software systems grow in scale, large code repositories typically contain a large number of source code files, classes, functions, and methods. Different code units work together to achieve business functions through calling relationships, while users often describe target functions or fault phenomena using natural language. Due to the differences in expression between natural language queries and code identifiers and function implementations, and because the target function may involve cross-file calling relationships, it is difficult to accurately locate the target code based on a single code snippet.

[0003] Existing code retrieval technologies mainly include the following categories: First, keyword retrieval. Methods like BM25 rank candidates based on word frequency and word matching, and can match explicit identifiers such as function names and type names, but are prone to missing abbreviations, synonyms, and queries lacking specific identifiers.

[0004] Second, vector semantic retrieval. Queries and code are encoded as vectors, and retrieval is performed using cosine similarity. This method can alleviate the differences in literal expression, but function-level vectors are insufficient to fully represent the file, project context, and function call relationships. It can easily lead to confusion between functions with the same name in different locations and functions with similar implementations but different responsibilities.

[0005] Third, graph structure assists in retrieval. Call graphs, inheritance graphs, and other code relationship methods are used to aid in location. Graph signals such as in-degree and PageRank can characterize the structural importance of nodes, but do not directly indicate the relevance of a node to the current query. If centrality rankings are treated as independent retrieval channels and weighted equally, a few central nodes may receive high rankings in different queries, interfering with the ranking of relevant candidates.

[0006] Fourth, large language models assist in retrieval. Large language models are used to rewrite queries, evaluate results, or rearrange candidates. Simple query rewriting does not fully utilize call relationships, and simple candidate rearrangement cannot find targets outside the candidate set; performing the same multiple rounds of supplementary retrieval on all queries increases computational load and model call overhead; directly merging expanded results with original results may also squeeze out previously correct candidates from the return range.

[0007] In summary, existing code retrieval methods struggle to simultaneously consider symbol semantics, file context, and code structure relationships. Furthermore, they lack a mechanism to select supplementary retrieval strategies based on query difficulty and the type of missing information, leading to a disconnect between candidate recall, feedback expansion, and final ranking. Therefore, a code retrieval method is needed that can jointly utilize multi-granularity information and dynamically adjust retrieval strategies based on query conditions. Summary of the Invention

[0008] This invention aims to address the problems of insufficient single-granularity information, failure to recall target code, lack of targeted supplementary retrieval, and high cost of unified feedback in existing natural language code retrieval methods. It provides a code retrieval method based on multi-granularity hybrid indexing and feedback-driven approaches. This method establishes connections between symbol layer, file layer, and layer data, introducing controlled structural bias after multi-channel candidate fusion. It determines whether to supplementary retrieval based on dense retrieval confidence and query complexity, and selects between graph traversal or query rewriting based on the type of missing information. Finally, it performs list-based rearrangement and output verification within a fixed candidate set, ensuring seamless integration of candidate recall, feedback expansion, and final ranking to improve code location accuracy and reduce unnecessary feedback calculations.

[0009] This invention provides a code retrieval method based on multi-granularity hybrid indexing and feedback-driven approach, comprising: Parse the code repository, extract code units and call relationships, and build symbol layer index, file layer index and call graph; the symbol layer index includes keyword index and symbol vector index, the file layer index includes file vector index, and the call graph uses code units as nodes and call relationships as directed edges, and saves the adjacency relationship of outgoing edges and incoming edges; The system receives natural language queries, retrieves candidates for each channel from the keyword index, symbol vector index, and file vector index, performs weighted inverse ranking fusion, and obtains fusion score and fusion ranking. Seed candidates are selected from the fusion ranking and associated with the calling graph nodes. Seed neighbor labels are calculated, and a controlled graph structure bias is added to the fusion score in combination with the graph structure signal to obtain the basic candidate ranking. The highest cosine similarity between the query vector and the candidate symbol vector in the symbol vector channel recall results is compared with a preset threshold. If it is less than the preset threshold, the top-ranked candidates in the query and basic candidate ranking are submitted to the large language model to obtain information sufficiency, missing type and query complexity, and to determine whether to perform supplementary retrieval and supplementary retrieval budget; otherwise, supplementary retrieval is skipped. If supplementary retrieval is required, perform at least one of the following based on the missing type: perform a budget-constrained traversal along the outgoing and incoming edges of the call graph using the symbols associated with the basic candidate as seeds; or generate alternative queries from a large language model and recall candidates through multi-granularity indexes; after supplementary retrieval, merge, deduplicate, and score the candidates by unique identifiers, and update the candidate set. Take the top K candidates from the basic candidate sorting or updated candidate set and assign them indices to establish an indices mapping. Submit the large language model for list-style rearrangement. The model only returns the indices within the candidate set. Parse and verify the sequence number. If it is insufficient, pad it with the original sequence. If there is an error, use the original sequence. Map the output to the real file or function based on the sequence number.

[0010] The method provided by this invention has at least the following beneficial effects: By establishing multi-granularity associations between the symbol layer, file layer, and call graph, and introducing a controlled graph structure bias after fusion of the weighted inverse ranking of keywords, symbol vectors, and file vectors, it can take into account the precise matching of identifiers, semantics, and file context, while avoiding the interference of graph centrality as an independent retrieval channel on the ranking of related candidates; it can trigger supplementary retrieval as needed based on the highest cosine similarity and query complexity, and select bidirectional call graph traversal or query rewriting according to the missing type, thereby improving the targeting of target recall within a limited budget and reducing unnecessary model calls and feedback calculations; finally, it performs list-style rearrangement and sequence number verification output within a fixed candidate set, so that candidate recall, feedback expansion, and final ranking are interconnected, thereby improving the accuracy of code location and enhancing the controllability and robustness of the output results. Attached Figure Description

[0011] Figure 1 This is a schematic diagram of the overall process of a code retrieval method based on multi-granularity hybrid indexing and feedback-driven approach provided in an embodiment of the present invention.

[0012] Figure 2 This is a schematic diagram illustrating the process of constructing a multi-granularity index and performing a three-channel fusion retrieval, as provided in an embodiment of the present invention.

[0013] Figure 3 This is a schematic diagram of the missing type-driven feedback supplementation retrieval and termination judgment process provided in an embodiment of the present invention.

[0014] Figure 4 This is a schematic diagram of the confidence routing, fixed candidate set rearrangement, and output verification process provided in an embodiment of the present invention. Detailed Implementation

[0015] To make the objectives, technical solutions, and advantages of this invention clearer, the technical solutions of this invention will be clearly and completely described below in conjunction with specific embodiments. Obviously, the described embodiments are only a part of the embodiments of this invention, and not all of them. Based on the embodiments of this invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this invention.

[0016] This method is executed by a computer device. The device's processor calls programs in memory to process the code repository, query text, index data, and candidate records; vector encoding can be accelerated by a graphics processor, and large language models can run locally or be invoked via a network interface. The offline input of the method is a specified version of the code repository, and the online input is the natural language query and retrieval scope; the output is a list of files or functions sorted by relevance, along with corresponding paths, symbol identifiers, and code snippets. File-level output is suitable for defect localization, while function-level output is suitable for implementing retrieval. All retrieval channels within a single query should use a consistent repository version and output granularity.

[0017] like Figure 1 As shown in the figure, the overall process of the code retrieval method based on multi-granularity hybrid index and feedback-driven method provided by the present invention is as follows: Enter the specified version of the code repository as the code version used for this search.

[0018] Execute step S10 to parse code units and establish a multi-granularity index: parse the source code in the specified version code repository, extract code units and their call relationships, and establish a symbol layer, file layer and call graph. The call graph saves the adjacency relationship of outgoing and incoming edges for subsequent structural bias calculation and bidirectional traversal.

[0019] Step S20 involves query-driven three-channel recall and weighted fusion: A natural language query is received, and candidates for each channel are retrieved from the keyword index, symbol vector index, and file vector index. These candidates are then weighted and fused to obtain a fused ranking. A graph structure bias is added after fusion: Seed candidates are selected from the fused ranking and associated with nodes in the calling graph. Seed neighbor labels are calculated, and a controlled graph structure bias is added to the fusion score based on the graph structure signal to obtain a basic candidate ranking. The three channels are the keyword channel, symbol vector channel, and file vector channel. The symbol layer includes the keyword channel and the symbol vector channel, and the file layer includes the file vector channel.

[0020] Execute step S30 to determine confidence and query complexity, select a route, and configure the feedback budget: Route determination is performed based on the highest density similarity of the symbol vector channels and a preset threshold, combined with query complexity. If no supplementation is needed, the basic candidates are retained, and the process proceeds directly to step S50; if supplementation is required, the process proceeds to step S40. The specific determination in step S30 can be determined by… Figure 4 Steps S31, S32, and S33 shown are implemented.

[0021] Execute step S40 to supplement and merge candidates according to the missing type: Perform a bidirectional traversal of the call graph or query rewriting based on the missing type, merge the supplemented candidates with the original candidates by unique identifier, remove duplicates, score them, and update the candidate set; end the feedback when information is sufficient or the budget is exhausted, and proceed to step S50. For details on the execution of step S40, please refer to [link to relevant documentation]. Figure 3 Steps S41 to S44 are shown.

[0022] Execute step S50 to construct a fixed candidate set and perform list-based rearrangement: select the top K candidates from the basic or updated candidate set, assign serial numbers to the candidates and establish serial number mapping, and submit the query and the serial numbered candidate list to the large language model for list-based rearrangement.

[0023] Execute step S60, verify the sequence number, remove duplicates and pad or roll back to the original order: verify the sequence number returned by rearrangement, pad it to the original order if there are insufficient valid sequence numbers, use the original order if the parsing fails or there are no valid sequence numbers, and output the real file or function according to the sequence number mapping.

[0024] In step S30, it is decided whether to execute step S40. Candidates that have been executed or skipped from step S40 proceed to step S50. If further feedback is required in step S40, the candidates are updated within the budget and the sufficiency of information is reassessed. Through the above steps S10 to S60, the candidate recall, feedback expansion, and final ranking are interconnected, thereby improving the accuracy of code location and reducing unnecessary feedback calculations.

[0025] By employing this embodiment, through the synergy of multi-granularity indexing, controlled graph bias after fusion, supplementary retrieval based on missing type, and fixed candidate set rearrangement, it is possible to improve the accuracy of code location while reducing unnecessary feedback calculations.

[0026] like Figure 2 As shown, the multi-granularity index construction and three-channel fusion retrieval process provided in this embodiment of the invention is a... Figure 1 The further refinement of steps S10 and S20, and its overall process are as follows: Execute step S11 to parse the code repository, extract symbols and call relationships, and establish a unified identifier and symbol-file mapping: use an abstract syntax tree parsing tool to parse the source code, extract relative file paths, qualified names of functions or methods, signatures, code bodies, start and end positions, and call information; set a unique identifier for code units consisting of repository identifier, file path, and qualified symbol name, and record the mapping between symbols and their respective files; use the unified identifier to associate subsequent keyword indexes, symbol vector indexes, and graph nodes to avoid incorrect merging of symbols with the same name in different repositories or files.

[0027] Execute step S12 to establish a symbol layer index: The signature and code body of the function or method are used as symbol text. On the one hand, the text is segmented and a BM25 (Best Match 25, a keyword retrieval algorithm) keyword index is established. On the other hand, the code embedding model encodes the text into a normalized symbol vector and saves the mapping from symbol vector to symbol identifier. When the evaluation query originates from the docstring of the function, the corresponding docstring is extracted from the retrieved code text to avoid the original query text directly entering the retrieval object and causing information leakage. Here, the evaluation query refers to the query used to evaluate the retrieval effect. In this embodiment, it can also be a natural language query.

[0028] Execute step S13 to build a file-level index: For each source code file, concatenate its relative path with the qualified names of the first N symbols to form a summary text, then encode it into a normalized file vector, and save the mapping between the file vector and the file identifier, so that the context provided by the file path and the symbols in the file can participate in the retrieval.

[0029] Execute step S14 to establish a directed call graph: with functions or methods as nodes and resolvable call relationships as directed edges, when function A calls function B, a directed edge from A to B is established, and the adjacency relationships of outgoing and incoming edges are saved to support subsequent bidirectional traversal; graphs are built separately for different repositories, and fictitious connections are not made for unresolvable external calls; the normalized in-degree S1 and the PageRank signal S2 within the repository can be pre-calculated, and the reachability marker S3 of the seed neighbor related to the current query is calculated online in subsequent steps.

[0030] Step S21 is executed, involving query processing and encoding, with parallel retrieval across three channels: the query is processed for keywords and encoded into vectors, and then retrieved from the BM25 (Best Match 25) keyword index, symbol vector index, and document vector index to obtain the top candidates for each channel. The highest similarity score for the symbol vector channel is retained and denoted as the highest similarity score for the densest channel. In one embodiment, the first 100 candidates for each channel are initially selected.

[0031] Execute step S22 to unify the output granularity and merge the sorting: During file-level retrieval, symbol candidates are mapped to their respective files, and a deduplicated file sort is formed according to the first occurrence position of each file in the symbol sorting, and relevant functions are selected as representative code fragments; During function-level retrieval, the file-level results are associated with the symbols in the file through the file-symbol mapping, and a candidate sort is formed according to a preset, fixed expansion order; After unifying the candidate identifiers, a weighted reciprocal ranking is used to calculate the fusion score to obtain the fusion sort.

[0032] Execute step S23, and add graph structure bias after fusion: Select the top 5 candidates from the fusion ranking as seeds, associate them with the calling graph nodes, and calculate the seed one-hop neighbor label S3; aggregate graph signals through representative symbols or intra-file nodes for file-level candidates, and the aggregation rules remain unchanged in the same configuration; superimpose the controlled graph structure bias on the fusion score to obtain the basic score and basic candidate ranking, where the graph structure signal participates in the ranking as an additive bias after three-channel fusion, and does not form an independent RRF (Reciprocal Rank Fusion) retrieval channel.

[0033] Output the base candidate ranking, candidate relevance scores, and the highest similarity score for dense candidate candidates, and then process them in subsequent routing steps.

[0034] In this embodiment, the coverage of candidate recall is improved by associating the symbol layer, file layer and call graph and by weighted fusion of three channels; the addition of controlled graph structure bias after fusion helps to reduce the interference of query irrelevant central nodes on the sorting.

[0035] like Figure 3 As shown, the missing type-driven feedback supplementation retrieval and termination judgment process provided by this embodiment of the invention is for... Figure 1 Further refinement of step S40. Figure 3 This mainly illustrates the detailed process of step S40, while the detailed determinations for steps S32 and S33 can be found in [link to relevant documentation]. Figure 4 Corresponding description. Figure 3 In this context, "definition" indicates a missing definition, "caller" indicates a missing caller, "test" indicates a missing test, "config" indicates a missing configuration, and "doc" indicates a missing documentation; L2 represents the second level of complexity, L3 represents the third level of complexity, "sufficient" indicates information sufficiency, and "false" indicates insufficient information. The overall process is as follows: Execute steps S32 and S33, receiving the joint decision and budget, query and current candidate: only when the query complexity is at the second or third complexity level and the information sufficiency indicates that the current candidate information is insufficient, proceed to supplementary retrieval; the second complexity level corresponds to 1 hop and a maximum of 1 supplement, the third complexity level corresponds to 2 hops and a maximum of 2 supplements; define missing and caller missing as one type of label, and test missing, configuration missing and document missing as another type of label, the two types of labels are judged independently, and can be enabled at the same time.

[0036] Execute step S41 to perform a bidirectional graph traversal for structural missing features: when the missing feature type set contains definition missing features or caller missing features, use the symbols associated with the top 5 current base candidates as seeds and traverse along the outgoing and incoming edges of the call graph; outgoing edges are used to find the function called by the candidate, and incoming edges are used to find the function that calls the candidate; based on the second or third complexity level budget, the hop count is limited to one or two hops respectively, record the shortest hop distance from the candidate to the seed, and remove duplicates by unique identifier; file-level retrieval maps extended symbols to files, and function-level retrieval preserves symbol granularity.

[0037] Execute step S42 to perform query rewriting for semantic missing data: When the set of missing data types includes test missing data, configuration missing data, or document missing data, generate 1 to 3 alternative queries in a single large language model call. The rewriting methods include synonym expression, terminology normalization, and supplementary context. Each alternative query recalls candidates through multi-granularity indexing and aggregates the results. When test, configuration, or document files need to be returned, the corresponding files are included in the searchable scope in advance. Unindexed objects cannot be returned solely by query rewriting.

[0038] Step S43 involves merging, deduplicating, and scoring supplementary candidates: Candidate records store a unique identifier, file mapping, original rank, branch origin, shortest graph hop distance, and semantic similarity; duplicate candidates are merged using the unique identifier to prevent repeated output of the same target due to multiple branch hits; the file-level implementation can use weighted reciprocal ranking to merge the original sort, rewritten sort, and graph expansion sort; in the function-level graph expansion implementation, the original candidates are still scored according to s(c) = 0.9 / rank(c); newly added one-hop candidates are scored according to s(c) = 0.5 + 0.4 × m. The score is calculated using ax(0,cos(q,c)); new second-hop candidates are scored using s(c)=0.35+0.4×max(0,cos(q,c)); the score for new graph candidates is based on the shortest jump distance to determine the base score, and adjusted in conjunction with semantic similarity; the above scoring results in higher structural base scores for first-hop candidates while retaining semantic adjustment; it is not required that all first-hop candidates rank higher than second-hop candidates; only the ranking fusion of candidates recalled by query rewriting participates in the merging, and they are not assigned non-existent graph jump distances; the parameters of the two merging implementation methods are calibrated separately.

[0039] Execute step S44 to determine if the feedback has ended: update the current candidate set after supplementation; re-evaluate the sufficiency of information if the budget allows; stop feedback when the information is sufficient, the maximum number of rounds has been reached, or no new candidates have been added, output the most recent valid ranking, and hand it over to the fixed candidate set rearrangement step for processing; the seed for the next round of traversal must still come from the current search range and the candidate source must be recorded to avoid repeated expansion; retain the most recent valid ranking when the call fails or the supplementation result is invalid.

[0040] This embodiment selects bidirectional graph traversal or query rewriting based on the missing type and terminates feedback under budget constraints, which improves the targeting of supplementary retrieval and reduces the overhead of invalid expansion.

[0041] like Figure 4 As shown, the confidence routing, fixed candidate set rearrangement, and output verification process provided by this embodiment of the invention is a... Figure 1 Further refinement of steps S30, S50 and S60. Figure 4 This mainly illustrates the detailed process of steps S30, S50, and S60. For the specific execution of step S40, please refer to [link / reference needed]. Figure 3 Steps S41 to S44. Figure 4 In this context, sufficient represents information sufficiency, missing_types represents the set of missing types, complexity represents query complexity, confidence represents the level of confidence, and reason represents the rationale for the judgment; Route A represents route A, Route B represents route B, and Route C represents route C; base represents the basic candidate ranking, Dense represents density, dense_top_conf represents the highest cosine similarity, τ represents the preset threshold, JSON represents the structured data format, L1 represents the first level of complexity, L2 represents the second level of complexity, and L3 represents the third level of complexity. The overall process is as follows: Execute step S31, input the query, base candidate ranking, and Dense highest similarity, and perform high confidence judgment: take the highest cosine similarity between the query vector and the candidate symbol vector in the symbol vector channel recall results as the Dense highest similarity, denoted as dense_top_conf, and compare it with the preset threshold τ; when the Dense highest similarity is not less than τ, proceed to Route A, skip the feedback classification and supplementary retrieval, and directly hand the base to the re-ranking step; this similarity is used for route judgment and is not used as the calibrated accuracy probability.

[0042] In step S32, when the highest similarity of the densest query is less than τ, a joint judgment is performed and the structured output is verified: the query and the paths, signatures, and representative fragments of the top 5 candidates are submitted to the large language model. In one call, structured fields such as information sufficiency, missing type set, query complexity, confidence level, and judgment reasoning are output. The structured fields output by the large language model are parsed using JSON (Structured Data Format, JavaScript Object Notation), and the field types and enumerations are verified. If parsing fails, the code fence can be removed and parsed again. If it still fails, the model call is retried at most once, and then rule-based downgrading is applied. For example, very short queries are classified as the third complexity level and are set to define missing and test missing; queries containing URLs or type signatures are classified as the second complexity level and are set to define missing; other queries are classified as the second complexity level and are set to define missing.

[0043] Execute step S33, select a route based on query complexity: when the query complexity is at the first complexity level (i.e., L1), proceed to Route B, skip the supplementary search, retain the base and proceed to step S50; when the query complexity is at the second complexity level (i.e., L2) or the third complexity level (i.e., L3), proceed to Route C; if the information sufficiency indicates that the current candidate information is sufficient, retain the base and proceed to the rearrangement step; if the information sufficiency indicates that the current candidate information is insufficient, proceed to step S40.

[0044] Execute step S40 to supplement and merge candidates according to the missing type: the second complexity level (i.e., L2) corresponds to a maximum graph hop count of 1 and a maximum search round of 2; the third complexity level (i.e., L3) corresponds to a maximum graph hop count of 2 and a maximum search round of 3, with the maximum search round including the initial search; perform a bidirectional traversal of the call graph or query rewriting according to the missing type, supplement and merge candidates, and update the candidate set. For details on the execution of step S40, please refer to [link to relevant documentation]. Figure 3 Steps S41 to S44.

[0045] Execute step S50 to construct a fixed candidate set and perform list-based rearrangement: take the first K different candidates, where K is a preset positive integer, and in one embodiment, K=20. If there are fewer than K candidates, use all candidates; assign the candidates to numbers from 1 to K according to the current sorting, and save the mapping between the numbers and the real candidate identifiers; submit the query and the candidate list with numbers to the large language model at once, requiring sorting based on comprehensive path, identifier, code implementation, and context relevance. The model returns a structured data object containing a sorting number field, and the model only returns the numbers within the current candidate set.

[0046] Execute step S60 to verify the sequence number, remove duplicates and fill in the blanks, or roll back to the original order: parse the sorting sequence number field, check whether each element is an integer within the valid range, and remove duplicate and out-of-bounds sequence numbers; if the number of valid sequence numbers is less than the preset target number, fill in the blanks from the candidates that have not yet been selected according to the original order of the candidate set; if the model call is abnormal, the structured data object cannot be parsed, or there are no valid sequence numbers at all, use the original order of the candidate set; restore the real file or function according to the sequence number mapping, and output the first preset target number of candidates and their paths and code snippets. In one embodiment, the preset target number is min(10,K). When the candidate set is empty, return an empty result.

[0047] By employing this embodiment, the controllability of the output results and the head hit rate are improved through confidence routing, fixed candidate set list-based rearrangement, and sequence number verification backoff.

[0048] The above embodiments, through the synergy of multi-granularity indexing, controlled graph bias after fusion, supplementary retrieval by missing type, and fixed candidate set rearrangement, can improve the accuracy of code location while reducing unnecessary feedback calculations.

[0049] In the above Figures 1 to 4 Based on the illustrated embodiments, specific implementation methods for each step are given below to further illustrate the specific implementation methods of each step.

[0050] This embodiment provides a specific implementation of a code retrieval method based on multi-granularity hybrid indexing and feedback-driven approaches. This method is executed by a computer device, whose processor calls programs stored in memory to process the code repository, query text, index data, and candidate records. Vector encoding can be accelerated by a graphics processor, and the large language model can run locally or be invoked via a network interface. The offline input of the method is a specified version of the code repository, and the online input is the natural language query and retrieval scope. The output is a list of files or functions sorted by relevance, along with corresponding paths, symbol identifiers, and code snippets. This embodiment can be combined with... Figures 1 to 4 understand.

[0051] The code repository is parsed to extract code units and call relationships, and a symbol layer index, a file layer index, and a call graph are established. The symbol layer index includes a keyword index and a symbol vector index, the file layer index includes a file vector index, and the call graph uses code units as nodes and call relationships as directed edges, saving the adjacency relationships of outgoing and incoming edges. In one embodiment, an abstract syntax tree parsing tool is used to parse the source code, extracting relative file paths, qualified names of functions or methods, signatures, code bodies, start and end positions, and call information. A unique identifier consisting of a repository identifier, file path, and qualified symbol name is assigned to each code unit, and the mapping between symbols and their respective files is recorded. The signatures and code bodies of functions or methods are used as symbolic text, segmented, and a BM25 keyword index is established, while simultaneously encoded into normalized symbol vectors by a code embedding model. For each source code file, its relative path is concatenated with the qualified names of the first N symbols to form a summary text. For example, the concatenation format could be "file path|class name.method name|function name". In one embodiment, N=20. This is encoded as a normalized file vector, saving the mapping between the file vector and the file identifier, so that the context provided by the file path and the symbols within the file can participate in the retrieval. The call graph uses functions or methods as nodes. When function A calls function B, a directed edge is established from A to B, and the adjacency relationship of the outgoing and incoming edges is saved simultaneously. Graphs are built separately for different repositories, and fictitious connections are not created for unresolved external calls. The normalized in-degree S1 and PageRank signal S2 are pre-calculated, where PageRank signal S2 is calculated using the PageRank algorithm. The seed one-hop neighbor label S3 related to the current query is calculated online in subsequent steps. The symbol vector index uses a vector of a preset dimension and the inner product index of the vector similarity search library. After vector normalization, the inner product represents the cosine similarity. When the natural language query originates from the docstring of a function, the corresponding docstring is extracted from the retrieved code text to avoid information leakage caused by the original query text directly entering the retrieval object. In one embodiment, the preset dimension is 768, the vector similarity search library is FAISS, and the inner product of the vectors after normalization represents the cosine similarity.

[0052] The system receives natural language queries, retrieves candidate channels from the keyword index, symbol vector index, and file vector index, performs weighted inverse ranking fusion, and obtains a fusion score and fusion ranking. Seed candidates are selected from the fusion ranking and associated with nodes in the call graph. Seed neighbor labels are calculated, and a controlled graph structure bias is added to the fusion score based on the graph structure signal to obtain a basic candidate ranking. In one embodiment, the query undergoes keyword processing and vector encoding. The system retrieves the top candidates for each channel from the BM25 keyword index, symbol vector index, and file vector index, retaining the highest similarity (Dense) for the symbol vector channel. For each candidate c, the fusion score is denoted as F(c), calculated as: F(c) = Σ{i∈T} w_i / (k+rank_i(c)), where T is the channel set, containing keyword, symbol semantic, and file semantic channels; i is the channel index; w_i is the preset non-negative channel weight for that channel; k is a preset smoothing constant; and rank_i(c) is the rank of candidate c in that channel. If a candidate does not appear in a channel, the channel's contribution to its fusion score is 0. In one embodiment, the preset smoothing constant k is 60, and the preset non-negative channel weights of the three channels are 0.3, 1.0, and 0.3 respectively. The top M candidates are selected from the fusion ranking as seed candidates; in one embodiment, M=5. The seed candidates are associated with the calling graph nodes, and the seed one-hop neighbor label S3 is calculated. The base score equals the fusion score plus the graph bias term, which is obtained by multiplying the graph bias magnitude by the sum of the weighted graph signals. The sum of the weighted graph signals is: the first weight multiplied by the normalized in-degree S1 of candidate c, the second weight multiplied by the PageRank signal S2 of candidate c, and the third weight multiplied by the seed one-hop neighbor label S3 of candidate c, and then added together. The graph bias magnitude, the first weight, the second weight, and the third weight are all preset non-negative parameters. In one embodiment, the graph bias magnitude is 0.008, and the ratio of the first weight, the second weight, and the third weight is 0.4:0.4:0.2, or the first weight and the second weight are 0, and the third weight is 1. The graph structure signal is used as an additive bias for ranking after the three channels are fused, and does not form an independent RRF retrieval channel. This can avoid a few central nodes from getting high rankings in different queries and reduce the interference of query-irrelevant central nodes on the ranking of relevant candidates.

[0053] The highest cosine similarity between the query vector and candidate symbol vectors in the symbol vector channel recall results is compared with a preset threshold τ. If it is less than the preset threshold τ, the top-ranked candidates in the query and basic candidate ranking are submitted to the large language model to obtain information sufficiency, missing type, and query complexity, and to determine whether to perform supplementary retrieval and its budget; otherwise, supplementary retrieval is skipped. In one embodiment, the maximum cosine similarity between the query vector and each candidate symbol vector in the symbol vector channel recall results is taken as the highest cosine similarity and compared with the preset threshold τ, where τ = 0.55 in one embodiment. When the highest cosine similarity is not less than τ, feedback classification and supplementary retrieval are skipped, and the process directly proceeds to the re-ranking step. When the highest cosine similarity is less than τ, the paths, signatures, and representative code snippets of the top P candidates in the query and basic candidate ranking are submitted to the large language model. In one embodiment, P=5. A structured field is output in a single call, including: information sufficiency indicator, missing type set, and query complexity. The information sufficiency indicator indicates whether the current candidate information is sufficient. The missing type set includes definition missing, caller missing, test missing, configuration missing, and document missing. The query complexity is set to a first complexity level (L1), a second complexity level (L2), or a third complexity level (L3). The first complexity level indicates a clear query intent requiring no supplementation; the second complexity level indicates a shallower supplementation retrieval; and the third complexity level indicates a deeper or multi-round supplementation. In one embodiment, the confidence level is a value between 0 and 1. The structured fields output by the large language model are parsed using JSON, and the field types and enumerations are validated. If parsing fails, code fences can be removed and parsing can be repeated. If it still fails, the model call will be retried at most once, after which rule-based degradation will be applied. This similarity score is used for routing decisions and is not considered as a calibrated accuracy probability. The confidence level and highest cosine similarity returned by the model represent the model's judgment and vector similarity, respectively, and the two are not interchangeable.

[0054] When determining the supplementary retrieval budget, the first maximum number of graph hops for the second complexity level (L2) is 1, and the first maximum number of retrieval rounds is 2; the second maximum number of graph hops for the third complexity level (L3) is 2, and the second maximum number of retrieval rounds is 3; the maximum number of retrieval rounds includes the initial retrieval. When the query complexity is the first complexity level (L1), the supplementary retrieval is skipped, the basic candidate ranking is retained, and the re-ranking step is entered; when the query complexity is the second complexity level (L2) or the third complexity level (L3), if the information sufficiency indicator indicates that the current candidate information is sufficient, the basic candidate ranking is retained; if the information sufficiency indicator indicates that the current candidate information is insufficient, the supplementary retrieval is performed according to the missing type set. Each supplement is constrained by the remaining rounds and the number of graph hops; feedback stops when the information is sufficient, the maximum number of rounds is reached, or no new candidates are added; the seed for the next round of traversal must still come from the current retrieval range and the candidate source is recorded to avoid repeated expansion; when the call fails or the supplementary result is invalid, the most recent valid ranking is retained.

[0055] If supplementary retrieval is required, at least one of the following is performed according to the missing type: a budget-constrained traversal along the outgoing and incoming edges of the call graph using the symbols associated with the basic candidate as seeds; or generating alternative queries from a large language model and recalling candidates through multi-granularity indexing; after supplementary retrieval, merging, deduplication, and scoring by unique identifier, and updating the candidate set. In one embodiment, when the missing type set contains definition missing or caller missing, the symbols associated with the first Q candidates of the basic candidate are used as seeds, and in one embodiment, Q=5, and the call graph is traversed along the outgoing and incoming edges; outgoing edges are used to find the functions called by the candidate, and incoming edges are used to find the functions that call the candidate; the budget is constrained to one hop or two hops according to the second complexity level (i.e., L2) or the third complexity level (i.e., L3), respectively, and the shortest hop distance from the candidate to the seed is recorded, and deduplication is performed by unique identifier; when the retrieval granularity is at the file level, the extended symbols are mapped to files; when the retrieval granularity is at the function level, the symbol granularity is preserved. When the missing type set includes test missing, configuration missing, or document missing, a preset number of alternative queries are generated in a single large language model call. One example generates 1 to 3 alternative queries. Rewriting methods include synonym expression, terminology normalization, and supplementary context. Each alternative query recalls candidates and aggregates results through multi-granularity indexing. When test, configuration, or document files need to be returned, the corresponding files are pre-included in the searchable scope; unindexed objects cannot be returned solely through query rewriting. When two types of missing data exist simultaneously, graph traversal and query rewriting are performed concurrently. If a branch has no results, the other branch and the original candidates are retained.

[0056] After supplementary retrieval, candidate records retain unique identifiers, file mappings, original rankings, branch sources, shortest graph hop distances, and semantic similarity. Duplicate candidates are merged using unique identifiers to prevent the same target from being repeatedly output due to multiple branch hits. The file-level implementation uses a weighted inverse ranking fusion to merge the original sorting, rewritten sorting, and graph expansion sorting. In the function-level graph expansion implementation, the score of the original top-preset number of candidates is s(c) = 0.9 / rank(c), and in one embodiment, the preset number is 100. The score of a newly added one-hop candidate is s(c) = 0.5 + 0.4 × max(0, cos(q, c)). The score of a newly added two-hop candidate is s(c) = 0.35 + 0.4 × max(0, cos(q, c)). The above scores give one-hop candidates a higher structural base score while retaining semantic adjustment, and do not require all one-hop candidates to be ranked before two-hop candidates. Only the ranking fusion of candidates recalled by query rewriting participates in the merging, and they are not assigned non-existent graph hop distances. The parameters of the two merging implementations are calibrated separately. The current candidate set is updated after supplementation, and the sufficiency of information is reassessed when the budget allows.

[0057] Take the top K candidates from the basic candidate sorting or updated candidate set and assign them indices to establish an indice mapping. Submit the list to the large language model for list-style rearrangement. The model only returns the indices within the candidate set. Parse and verify the indices. If there are not enough, pad them in the original order. If there is an error, use the original order. Output the real file or function according to the indice mapping. In one embodiment, the top K distinct candidates are selected from the basic candidate sorting or the updated candidate set. In one embodiment, K=20. If there are fewer than K candidates, all candidates are used. File-level candidates are represented as file paths and function fragments related to the query. Function-level candidates are represented as repositories, files, qualified function names, and code fragments. Candidates are assigned serial numbers from 1 to K according to the current sorting, and the mapping between serial numbers and actual candidate identifiers is saved. The query and the serialized candidate list are submitted to the large language model at once, requiring sorting based on path, identifier, code implementation, and context relevance. The model returns a structured data object containing a sorting serial number field, such as a JSON object of the form {"ranking":[3,1,5,...]}. The model only returns serial numbers within the current candidate set and cannot generate file paths or introduce candidates from outside the set. The sorting sequence number field is parsed, and each element is checked to see if it is an integer within the valid range. Duplicate and out-of-bounds sequences are removed. If the number of valid sequences is less than the preset target number, the remaining sequences are filled from the unselected candidates according to the original order of the candidate set. If the model call is abnormal, the structured data object cannot be parsed, or there are no valid sequences at all, the original order of the candidate set is used. The real file or function is restored based on the sequence number mapping, and the first preset target number of candidates, their paths, and code snippets are output. In one embodiment, the preset target number is min(10,K). When the candidate set is empty, an empty result is returned. By using sequence number verification, deduplication, out-of-bounds removal, insufficient filling, abnormal original order rollback, and sequence number mapping restoration, the output is kept within the range of real candidates, improving the controllability and robustness of the result range. Fixing the candidate set and sequence number verification limits the range of output objects and can prevent the model from generating non-existent candidates; however, rearranging the fixed set and then truncating the first 10 results may still change the original hit situation of the first 10.

[0058] For the specific implementation of each step in this embodiment, please refer to [link / reference]. Figures 2 to 4 Corresponding description.

[0059] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. For those skilled in the art, various improvements, equivalent substitutions, or modifications can be made without departing from the principles of the present invention, and these improvements, equivalent substitutions, or modifications should also be considered within the scope of protection of the present invention. The terminology used in this specification is only for describing specific embodiments and does not constitute a limitation of the present invention. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A code retrieval method based on multi-granularity hybrid indexing and feedback-driven approach, characterized in that, include: Analyze the code repository, extract code units and call relationships, and build symbol layer index, file layer index and call graph; The symbol layer index includes a keyword index and a symbol vector index, the file layer index includes a file vector index, and the call graph uses code units as nodes and call relationships as directed edges, and saves the adjacency relationship between outgoing and incoming edges. The system receives natural language queries, retrieves candidates for each channel from the keyword index, symbol vector index, and file vector index, performs weighted inverse ranking fusion, and obtains the fusion score and fusion ranking. Seed candidates are selected from the fusion ranking and associated with the calling graph nodes. Seed neighbor labels are calculated, and a controlled graph structure bias is added to the fusion score in combination with the graph structure signal to obtain the basic candidate ranking. The highest cosine similarity between the query vector and the candidate symbol vector in the symbol vector channel recall results is compared with a preset threshold. If it is less than the preset threshold, the top-ranked candidates in the query and basic candidate ranking are submitted to the large language model to obtain information sufficiency, missing type and query complexity, and to determine whether to perform supplementary retrieval and supplementary retrieval budget; otherwise, supplementary retrieval is skipped. If supplementary retrieval is required, perform at least one of the following based on the missing type: perform a budget-constrained traversal along the outgoing and incoming edges of the call graph using the symbols associated with the basic candidate as seeds; or generate alternative queries from a large language model and recall candidates through multi-granularity indexes; after supplementary retrieval, merge, deduplicate, and score the candidates by unique identifiers, and update the candidate set. Take the top K candidates from the basic candidate sorting or updated candidate set and assign them indices to establish an indices mapping. Submit the large language model for list-style rearrangement. The model only returns the indices within the candidate set. Parse and verify the sequence number. If it is insufficient, pad it with the original sequence. If there is an error, use the original sequence. Map the output to the real file or function based on the sequence number.

2. The method according to claim 1, characterized in that, The establishment of the symbol layer index includes: The source code is parsed using an abstract syntax tree parser to extract relative file paths, qualified names of functions or methods, signatures, code bodies, start and end positions, and call information; Set a unique identifier for each code unit, consisting of a repository identifier, file path, and symbol qualified name, and record the mapping between symbols and their respective files; The signature and code body of a function or method are treated as symbolic text, segmented, and a keyword index is created. The code embedding model encodes symbolic text into normalized symbol vectors and saves the mapping from symbol vectors to symbol identifiers; The symbol vector index uses a vector of preset dimensions and an inner product index of vector similarity search library. After vector normalization, the inner product represents the cosine similarity. When the natural language query originates from the document string of a function, the corresponding document string is extracted from the retrieved code text.

3. The method according to claim 1, characterized in that, The establishment of the file layer index includes: For each source code file, its relative path is concatenated with the qualified names of the first N symbols to form a summary text, where N is a preset positive integer; The abstract text is encoded into a normalized file vector, and the mapping between the file vector and the file identifier is saved.

4. The method according to claim 1, characterized in that, The establishment of the call graph includes: Using functions or methods as nodes and resolvable call relationships as directed edges, when function A calls function B, a directed edge is established from A to B; Save the adjacency relationship between outgoing and incoming edges to support bidirectional traversal; Pre-calculate the normalized in-degree S1 and the node weight ranking signal S2; The step of selecting seed candidates from the fusion sort includes: selecting the top M candidates from the fusion sort as seed candidates, associating the seed candidates with nodes in the call graph, and calculating the seed one-hop neighbor tag S3, where M is a preset positive integer.

5. The method according to claim 1, characterized in that, Weighted reciprocal ranking fusion and incorporation of controlled graph structure bias include: For each candidate c, a fusion score is calculated as follows: for each of the three channels—keyword, symbol semantics, and document semantics—the preset non-negative channel weight of that channel is used as the numerator, and the preset smoothing constant is added to the candidate's rank in that channel to obtain the denominator. The ratio of the numerator to the denominator is then calculated to obtain the channel score for that channel. The channel scores of the three channels are summed to obtain the fusion score for that candidate. If a candidate does not appear in a certain channel, the contribution of that channel to its fusion score is 0. The basic score is calculated according to the basic scoring formula. The basic score is equal to the fusion score plus the graph bias term. The graph bias term is obtained by multiplying the graph bias magnitude by the sum of the weighted graph signals. The sum of the weighted graph signals is: the first weight multiplied by the normalized in-degree S1 of candidate c, the second weight multiplied by the node weight ranking signal S2 of candidate c, and the third weight multiplied by the seed one-hop neighbor label S3 of candidate c, and the sum of the three. Wherein, the graph bias magnitude, the first weight, the second weight, and the third weight are all preset non-negative parameters. The graph structure signal is used as an additive bias for sorting, and does not form an independent RRF retrieval channel.

6. The method according to claim 1, characterized in that, The step of comparing the highest cosine similarity between the query vector and the candidate symbol vector in the symbol vector channel recall results with a preset threshold includes: The maximum cosine similarity between the query vector and each candidate symbol vector in the symbol vector channel recall results is taken as the highest cosine similarity. Compare the highest cosine similarity with a preset threshold; When the highest cosine similarity is not less than a preset threshold, skip the feedback classification and supplementary retrieval. When the highest cosine similarity is less than a preset threshold, the paths, signatures, and representative code snippets of the top P candidates in the query and basic candidate ranking are submitted to the large language model. In a single call, structured fields are output, including: information sufficiency identifier, missing type set, and query complexity; P is a preset positive integer. Among them, the information sufficiency indicator indicates whether the current candidate information is sufficient; the missing type set includes missing definition, missing caller, missing test, missing configuration, and missing documentation; the query complexity can be the first complexity level, the second complexity level, or the third complexity level; The structured fields output by the large language model are parsed for structured data format, and the field type and enumeration are validated. If the parsing fails, the code fence is removed and the parsing is retried. If it still fails, the model call is retried at most once, and then rule-based degradation is adopted.

7. The method according to any one of claims 1 to 6, characterized in that, The determination of whether to perform a supplementary search and the supplementary search budget includes: When the query complexity is at the first level, skip the supplementary search; When the query complexity is at the second or third complexity level, if the information sufficiency flag indicates that the current candidate information is sufficient, the basic candidate ranking is retained; if the information sufficiency flag indicates that the current candidate information is insufficient, supplementary retrieval is performed according to the missing type set. The second complexity level corresponds to the first maximum number of graph hops and the first maximum number of search rounds, and the third complexity level corresponds to the second maximum number of graph hops and the second maximum number of search rounds, wherein the maximum number of search rounds includes the initial search. Each addition is constrained by the remaining rounds and the number of graph jumps; Feedback stops when there is sufficient information, the maximum number of rounds has been reached, or no new candidates have been added; the most recent valid sorting is retained when the call fails or the supplementary results are invalid.

8. The method according to claim 7, characterized in that, Performing supplementary retrieval based on the set of missing types includes: When the missing type set contains missing definitions or missing callers, use the symbols associated with the first Q candidates of the basic candidate as seeds and traverse along the outgoing and incoming edges of the call graph. Outgoing edges are used to find candidate functions to call, and incoming edges are used to find candidate functions to call. Based on the budget corresponding to the second or third complexity level, the limit is one hop or two hops respectively. Record the shortest hop distance from the candidate to the seed and remove duplicates by unique identifier. When the retrieval granularity is at the file level, extended symbols are mapped to files; when the retrieval granularity is at the function level, symbol granularity is preserved. When the set of missing types includes test missing, configuration missing, or document missing, a preset number of alternative queries are generated in a single large language model call. Each alternative query recalls candidates and aggregates results through multi-granularity indexes. When it is necessary to retrieve test, configuration, or documentation files, the corresponding files should be included in the searchable scope in advance. When two types of missing data exist simultaneously, graph traversal and query rewriting are performed at the same time. If a branch has no result, the other branch and the original candidate are retained. Q is a preset positive integer.

9. The method according to claim 8, characterized in that, The process of merging, deduplicating, and scoring candidates after supplementary retrieval, and updating the candidate set, includes: Candidate records store a unique identifier, file mapping, original ranking, branch origin, shortest graph jump distance, and semantic similarity. Duplicate candidates are merged using a unique identifier to prevent the same target from being output repeatedly due to multiple paths hitting the target. The file-level implementation method uses a weighted inverse ranking to merge the original sort, rewritten sort, and graph-expanded sort. In the extended implementation of the function-level graph, the score of the original first preset number of candidates is the first coefficient divided by the ranking of the candidate; the score of the newly added one-hop candidate is the larger of the second coefficient plus the third coefficient multiplied by the maximum value of the cosine similarity between the query vector and the candidate vector and 0; the score of the newly added two-hop candidate is the larger of the fourth coefficient plus the third coefficient multiplied by the maximum value of the cosine similarity between the query vector and the candidate vector and 0. The current candidate set is updated after supplementation, and the sufficiency of information is reassessed when the budget allows.

10. The method according to claim 1, characterized in that, From the basic candidate sorting or updated candidate set, select the top K candidates and assign them indices to establish an indice mapping. Submit these to the large language model for list-based rearrangement, and parse and validate the indices. Based on the indice mapping, output the actual file or function, including: Select the first K distinct candidates from the basic candidate sorting or the updated candidate set, where K is a preset positive integer. If there are fewer than K candidates, use all candidates. Assign indices from 1 to K to the candidates according to the current sorting, and save the mapping from the indices to the actual candidate identifiers; Submit the query and the candidate list with sequence numbers to the large language model at once. The model is required to sort the data based on path, identifier, code implementation and context relevance. The model returns a structured data object containing a sort number field, and only returns the sequence number within the current candidate set. Parse the sorting index field, check if each element is an integer within a valid range, and remove duplicate and out-of-bounds indexes; If the number of valid serial numbers is less than the preset target number, the remaining numbers will be supplemented from the candidates that have not yet been selected, following the original order of the candidate set. When a model call fails, a structured data object cannot be parsed, or there is no valid sequence number, the original order of the candidate set is used. Restore the real file or function based on the sequence number mapping, output the preset target number of candidates and their paths and code snippets, and return an empty result when the candidate set is empty.