Module contents
Stage 8 of 8Research 120 min

GNNs on code graphs for vulnerability detection

Apply the preceding methods to a problem close to your work: classify public C functions as vulnerable from their code property graphs. The central task is auditing duplicates, random versus temporal or project splits, and simple baselines to assess how much of a published metric holds up.

After this lesson you can

  • Extract code property graphs (AST, control flow, and data dependencies) from C functions with free tools.
  • Train a heterogeneous graph GNN and compare with bag-of-tokens and a small frozen code-language-model baseline.
  • Audit the dataset for exact and approximate duplicates, split leakage, and label noise.
  • Report results with honest splits and metrics appropriate for imbalance.

Before you start

A code graph is not proof of security

A function can be turned into a graph whose nodes represent syntax elements and whose edges express different relationships. This lesson’s task is to classify public functions by vulnerability labels; a high score calls for human review, does not prove exploitability, and does not automatically identify a fix. No customer data are used and dataset functions are not executed.

The figure shows the graph extracted from a temporal-test function selected before training and labeled positive in the corpus. The extractor recovered five structural nodes and eight relations, but not statements in the original function body. Controls filter relations and show signed attributions calculated on a trained GNN’s logit. The case file retains values, relations, residual, and graph and weight hashes. This attribution describes only the available representation: it neither locates a vulnerability in the omitted body nor establishes causality.

InteractiveRelations and attribution on an extracted graph

Function 26754, temporal test. The extractor recovered five structural nodes; the original code body is not represented. The eight original relations are drawn; the model adds their inverses. Attributions concern the logit relative to zero reference embeddings.

  • AST
  • Control
  • Data
Empty blockBLOCKMethodMETHODInput parameterPARAM_INOutput parameterPARAM_OUTReturnMETHOD_RETURN

Integrated gradients, seed 3, best epoch 3. Colors show sign and relative intensity; they do not prove causality or locate a vulnerability.

Visible relations8
Completeness residual7.70e-3
Temporal-test case fixed before training. Extraction does not represent the function body; values are integrated gradients on the available graph, not a validated localization.

The code property graph combines the abstract syntax tree (AST), control-flow graph (CFG), and data-flow or dependency relations. AST answers which expressions an instruction contains; CFG which instructions may execute next; a data dependency connects, for example, a definition to possible uses. CFG must handle branches, loops, returns, and jumps; aliases, pointers, and calls make data analysis approximate. A repeated-name extract is therefore not automatically a semantic dependency. A free analyzer such as Joern allows inspection of these relations and assumptions; when only fragments without headers or project context are available, record analysis failures and coverage rather than silently excluding them.

According to the export documentation, Joern can generate AST, CFG, and dependency graphs. To obtain a CPG’s data-flow layer, run run.ossdataflow in its console; an exported graph can contain a dependency only if analysis calculated it. Compare a few small functions with manual inspection and check edge types, direction, and multiplicity before training. An absent edge can mean analysis did not resolve a case, not that dependency is impossible.

Extraction also defines the evaluated population. A parser can recover part of an incomplete function’s tree without correctly recovering its types or macros. If it fails more often on positive functions, comparing only those it processed changes prevalence and can give an optimistic estimate. Record by split and label how many functions are received, have AST, CFG, and data available, and are excluded. Model comparisons should use the intersection of functions with all inputs available; additional analysis on each model’s full coverage answers another question and should be separate.

Relation direction matters too. If messages pass only from definition to use, a definition node receives no information about its uses in that layer. Adding the inverse relation permits that communication but creates a different type and changes the architecture. Nodes without neighbors of a relation need a well-defined convention; the equation’s self term preserves state. Sum readout can use function size as a cue, while mean attenuates that signal. Neither is intrinsically correct for all datasets: choose before inspecting results and check sensitivity to size.

Data, labels, and comparisons

Devign studies functions from C projects; PrimeVul reconstructs and audits public data and proposes chronological splits and paired evaluation. Its labels remain an approximation to a phenomenon depending on compilation context, calls, and version. A corrected function and its previous version can be nearly identical with different labels: deduplicating without retaining that conflict can erase precisely the signal of interest.

ReVeal combines code property graphs and a GNN, and its authors also build a dataset from public Chromium and Debian changes. Collection procedure, class distribution, and splits differ from PrimeVul’s. A paper’s results do not measure this cohort: changing corpus or labeling criterion can change errors and their interpretation.

As a label-noise reference, the PrimeVul study manually reviewed 50 functions labeled vulnerable by each of two techniques and reported 86% agreement for OneFunc and 92% for NVDCheck. Thus 7 and 4 of those 50 functions were not validated as vulnerable under its criterion. Calculated here with Wilson, approximate 95% intervals for those unvalidated proportions are 6.95% to 26.19% and 3.15% to 18.84%, respectively. These are samples of positives and that study’s criteria; some functions may depend on context across fragments. They are not a validated estimate of our cohort’s noise or a basis for inferring errors among negatives. In our audit, zero contradictions among identical tokenized texts also does not prove other labels correct.

GNN detection learns one representation per function. A heterogeneous layer uses parameters per relation rr and aggregates messages from each neighborhood:

hi(ℓ+1)=σ ⁣(W0hi(ℓ)+∑r∑j∈Nr(i)1ci,rWrhj(ℓ)).\begin{aligned} \vb h_i^{(\ell+1)}={}&\sigma\!\bigl(\mat W_0\vb h_i^{(\ell)}\\ &+\sum_r\sum_{j\in\mathcal N_r(i)}\frac{1}{c_{i,r}}\mat W_r\vb h_j^{(\ell)}\bigr). \end{aligned}

A node sum or mean followed by a classifier produces the function score. Declare vocabulary, inverse edges, normalization, class weights, extractor failure rate, and validation selection. Compare the GNN with a bag of tokens and embeddings from a small frozen code model plus classifier: the former identifies lexical signals, the latter supplies pretraining. If a baseline matches or exceeds the GNN, that is a useful scientific result, not something to hide. All three should use the same available examples, splits, and selection criterion.

Bag-of-tokens training must fit its vocabulary or hashing function without looking at test labels. The frozen language model receives no gradients, but its representation already contains pretraining information: if the evaluated repository appeared in its data, a later split does not guarantee absence of contamination. Record encoder version, maximum length, and percentage of truncated functions. A GNN with thousands of nodes per function and an encoder limited to a token prefix do not see exactly the same evidence; report that asymmetry alongside budgets and times. “Frozen” describes which parameters are updated, not a baseline without prior knowledge.

For the displayed case, integrated gradients traverse 64 points between zero and observed embeddings while keeping edges fixed. Component contributions are summed for one value per node: sign indicates contribution to logit change relative to that reference, not an individual probability. The sum approximates the difference between observed and reference logits; the shown residual is 0.00770, not zero. A zero embedding is a mathematical reference and need not correspond to a valid program.

Node attribution can guide inspection but does not itself establish causality. Before interpreting it, ask which score is explained, whether the method changes across seeds, and whether harmless name or formatting changes alter the map. Edges or nodes removed for a perturbation test may no longer represent a valid program. Useful inspection compares original code, patch location when available, extractor relations, and score changes under behavior-preserving transformations. This page’s attribution does not replace that evaluation.

The split is part of the hypothesis

Leakage auditing starts before training. A random function split can distribute fragments from one commit, near-identical versions, or files from one project across train and test. The model may recognize repeated patterns without generalizing to future projects. A project split tests transfer to unseen projects; a temporal split tests data after the cutoff. These are different questions and both cannot always be satisfied without discarding data. Fix tie-breaking rules and document exclusions.

An exact fingerprint of normalized tokens counts copies. For approximate similarity, form token n-gram sets and calculate Jaccard J(A,B)=∣A∩B∣/∣A∪B∣J(A,B)=|A\cap B|/|A\cup B|. MinHash estimates similarity through the proportion of matching minima; LSH proposes candidates without comparing every pair. Then verify exact Jaccard on candidates and group pairs before splitting. LSH may miss pairs: its threshold does not guarantee perfect recall, so measure false negatives on an audited sample. Do not normalize identifiers or literals in a way that erases security distinctions without explaining that effect.

The PrimeVul dataset already applies deduplication and chronological splitting. Randomly splitting its functions studies split sensitivity within that corpus but does not reconstruct leakage its authors removed. Dataset versions are not interchangeable: v0.1 adds metadata and includes only samples with certain recovered metadata. Retain project, commit, and file version and calculate hashes to repeat the audit.

In the downloader’s pinned v0.1 copy, direct JSONL counts give 175797 training, 23948 validation, and 24788 test functions, with 4862, 593, and 549 positive labels respectively. These are about 2.77%, 2.48%, and 2.21% positives. They describe that corpus version, not estimated vulnerability prevalence in a particular product.

The audit program reads all three v0.1 JSONL splits and stores hashes, counts, and split assignments in concatenated train, valid, test order. It uses 128 MinHash permutations on token trigrams and checks exact Jaccard on LSH candidates; functions under three tokens use their token set instead. It groups detected pairs before splitting and compares that split with random-function, commit, project, and official temporal splits. Group-split proportions refer to groups, not necessarily functions; classes or projects may remain imbalanced. Tokenization is approximate and retains identifiers and literals; it is not a C compiler. The downloader pins the mirror and verifies published hashes before marking files complete.

Running that audit on 224533 pinned-copy functions found zero identical pairs after tokenization and 34239 candidate pairs with verified Jaccard at least 0.8. Of these pairs, 11677 crossed the random split, 7817 the official temporal split, 8691 the commit split, and 910 the project split; none crossed the split grouping detected pairs. These are pairs, not independent functions, and LSH can miss candidates: they are not an exhaustive similarity census. The result describes this already deduplicated version and stated normalization; it does not itself establish how much model precision changes.

Distinguish three counts: exact pairs, verified approximate pairs, and connected groups formed by those pairs. If A resembles B and B resembles C, grouping all three avoids separating B from either, even if A and C do not pass the threshold. They are not necessarily semantically identical. If the same text has two labels, record the conflict and provenance; do not arbitrarily decide which is true. Deduplication also changes positive count and test difficulty, so a drop across splits cannot be attributed to one cause without comparing composition.

A commit split prevents functions with the same commit identifier being separated, but does not detect copies across commits. A project split blocks that leakage family among known projects, though a project shared under several names or forks may escape grouping. A temporal split prevents training on post-cutoff samples if dates are correct and available; it can still leave old functions copied into test. The script retains the authors’ distributed chronological split instead of inventing individual dates absent from the files used.

Metrics that withstand imbalance

With TP, FP, FN, and TN, precision =TP/(TP+FP)=TP/(TP+FP) and recall =TP/(TP+FN)=TP/(TP+FN). The precision-recall curve and area beneath it show tradeoffs as threshold varies; the operating threshold is chosen on validation, never test. False-alert count and variation across seeds also matter. Break errors down by CWE only when labels exist and examples suffice; do not interpret tiny classes as precise estimates. To compare conditions report functions, positives, groups, extraction failures, exact and approximate leakage, PR-AUC, precision, recall, and variability. Do not extrapolate prevalence or cost to another organization without evidence.

Precision depends on prevalence: the same detector with stable conditional rates can generate a very different false-alert proportion in a corpus where vulnerabilities are rare. Average precision summarizes ranking as the sum of recall increments weighted by precision; it is not necessarily equal to area calculated by trapezoidal interpolation. State which you use and how ties are handled. At an operating threshold also present TP, FP, and FN counts: they turn a fraction into concrete human-review workload.

The programs report 95% Wilson intervals for precision and recall, calculated with their respective denominators for the fixed model and threshold. If there are no positive predictions, precision and its interval are undefined. These intervals use a binomial approximation with independent examples and common probability: functions from the same project or commit may be correlated, so they do not capture all between-project uncertainty or replace seed variation.

For example, among 1000 functions with 5% positives, a detector with TP=40, FN=10, FP=95, and TN=855 has precision 40/135≈0.296340/135\approx0.2963, recall 40/50=0.840/50=0.8, and accuracy 895/1000=0.895895/1000=0.895. A detector marking everything safe reaches 0.95 accuracy and zero recall: accuracy alone rewards a tool finding no positives.

Example workflow and coverage criterion

This project’s workflow processes only public-source functions and does not execute them. If you install Joern, the batch extractor invokes the frontend on temporary files, exports GraphML, and uses the converter to select one function per file. It tries C first; cases without one function are retried as C++. The REACHING_DEF relation comes from Joern: its presence depends on overlays and does not guarantee complete analysis. Retain each graph’s extension and AST, CFG, and REACHING_DEF edges; add inverses in training. Nodes outside the function AST are excluded. A function with multiple candidate methods is marked ambiguous rather than selected arbitrarily.

python download_primevul.py --root datos/PrimeVul
python audit.py --root datos/PrimeVul --output auditoria.json
python select_cohort.py --root datos/PrimeVul --output datos/cohorte --full-splits auditoria.splits.json
python extract_cpg.py --root datos/cohorte --joern ruta/a/joern-cli --output grafos --batch-size 100
python cpg_coverage.py --root datos/cohorte --graphs grafos --splits datos/cohorte/cohort.splits.json --output cobertura.json
python cpg_structural_audit.py --root datos/cohorte --graphs grafos --splits datos/cohorte/cohort.splits.json --long-threshold 200 --inspect-index 26754 --output estructura.json

The reproducible cohort selection defaults to 30000 functions without replacement, proportionally within each official split and without using labels to choose functions. It requires identified project and commit, retains source-corpus indices, and projects assignments from the full audit. Thus a pair detected in the entire corpus remains in the same group even when only part is selected. All records in this version have project and commit; individual dates are absent, so the official temporal split is retained rather than invented.

With seed 20261126 the cohort has 23488 train functions with 651 positives, 3200 validation with 83, and 3312 test with 84. Before training, size 12000 had been tested, whose temporal test contained only 24 positives; it was expanded to 30000 for a more informative denominator. This class-composition-informed decision preceded model comparison. The manifest records hashes and composition; final extractor coverage and intervals must be recalculated on the actually available intersection.

Projecting full-corpus assignments retains each detected group. Before coverage filtering, test has 72 positives in the random split, 73 similarity-grouped, 84 temporal, 40 project, and 81 commit. Project test contains 1615 functions from 71 projects; sizes differ because entire groups are assigned. Forty positives still imply considerable uncertainty, which can grow if some extraction fails.

Audit output contains each example’s assignment and file hashes; it also saves an index checkpoint and detected pairs. After interruption repeat the command with --resume using only your own trusted checkpoint: it is a Python pickle file. Extraction saves a manifest with hashes, coverage, and completed batches and also supports resumption. Index and extraction time and storage can be considerable. In a deliberately small preliminary test with the first ten functions of each split, the first attempt produced 14 graphs and the second recovered 15 of 16 missing. This sample is biased by order and class: it detects integration failures, not general coverage or semantic validity.

Batch size can alter context seen by the analyzer. In a check on the same 300 functions, one batch of 300 and three of 100 recovered the same 284 indices. For 283, node and edge multisets with labels and text matched; one differed by four nodes and sixteen edges on each side. Matching summaries does not prove isomorphism or semantic equivalence. The laboratory retains batches of 100 and records size instead of treating both extractions as interchangeable without further checks.

Another diagnostic randomly selected 50 positive and 50 negative functions from each split with seed 14: 300 total. This sample is balanced by design and does not reproduce corpus prevalence. The audit found four pairs with verified Jaccard at least 0.8 among LSH candidates; three crossed the official temporal split and none crossed the detected-pair-grouped split. Exhaustive checking of all 44850 sample pairs found exactly those four, with no LSH false negatives in this sample. There are only four positive pairs in that check: they cannot precisely estimate corpus recall. Threshold and tokenization matter, and LSH may miss candidates in other data.

In that same sample the extractor obtained 279 of 300 graphs. Positive coverage was 43/50, 44/50, and 45/50 in train, validation, and test; negative coverage was 49/50, 50/50, and 48/50. Three graphs lacked REACHING_DEF edges; Joern warned it omitted analysis of one function with more than 4000 definitions. Missing edges do not automatically identify that cause, but require retaining the warning and reviewing code. Total extracted graphs alone does not show whether coverage loss affects both classes equally.

Subsequent extraction of the fixed 30000-function cohort recovered 28062 graphs. In this cohort’s official temporal split, coverage was 21365/22837 negatives and 605/651 positives in training; 2937/3117 and 71/83 in validation; and 3013/3228 and 71/84 in test. The coverage report retains counts for all five splits by class and relation, with file hashes. Presence of a relation does not guarantee complete analysis; coverage concerns extracted graphs, not label correctness or detector performance.

To separate grouping from removal, a deduplicated selection of the random split was also fixed, with its protocol and counts. The cohort has 623 detected approximate pairs with both endpoints selected; 568 have both graphs. Components are formed over all 30000 functions, including when an intermediate function has no graph. After restricting to 28062 with coverage, priority goes to test, then validation, then training; within that split the smallest cohort index per label of each component is retained. There are 27609 functions: train 21870 with 544 positives, validation 2844 with 88, and test 2895 with 69. Of 107 covered mixed-label components, 56 retain both labels in the same split; this rule does not decide which is correct. No detected component crosses retained splits, but LSH may have missed other pairs. 55 detected opposite-label pairs within one split are retained.

To reconstruct that mask from files generated by audit.py and select_cohort.py, use the component projector. It reads only integer sequences from the audit checkpoint using pickletools, verifies report crossings and source and split hashes, and does not execute file objects. The full checkpoint may occupy substantial space; the distributed selection permits direct inspection of indices and hash.

This construction uses labels to retain conflict representatives and inspects test code to remove its components from training. It is a transductive audit fixed before measuring this condition, not a simulation of deployment where future test is unknown. It also changes training composition: 42 train positives are removed in this cohort. Comparison must declare that change and not attribute every difference solely to avoided leakage.

python dedup_components.py --full-checkpoint audit-checkpoint.pkl --full-audit audit.json --full-splits audit.splits.json --cohort-root datos/cohorte --eligible elegibles.json --output dedup-random-eligible.json --report dedup-report.json

A reproducible structural audit, with counts by split and class, found at least one <empty> block in 14673 graphs; that marker alone can also appear in legitimately empty blocks. In 583 graphs all nodes are method, block, parameter, or return types; 191 correspond to sources longer than 200 characters, a threshold fixed before counting. In temporal test these are 2 of 71 covered positives and 33 of 3013 negatives. These are inspection indicators, not automatic proof of parser error or of a vulnerability’s presence or absence.

For example, the test case fixed for attribution has 5104 characters in the original function, but its recovered graph contains only five structural nodes and no body statements. Importance calculated on that graph describes what the model received, not a validated cause localization or explanation of omitted code.

When extracting embeddings for that sample, 135 of 300 functions exceeded 512 tokens and were truncated. The count includes all 300 selected, not only 279 with graphs. Within the CPG intersection, truncation was 11/49 negatives and 25/43 positives in training; 11/50 and 25/44 in validation; 16/48 and 31/45 in test. This is a concrete reason to check whether encoder and GNN see the same program portion; these proportions cannot be generalized to the full corpus because selection overrepresents positives. Full comparison should report truncation by split and class.

The relational GNN, bag-of-tokens, frozen CodeBERT extraction, and embedding classifier scripts share corpus indices and verify data hashes. The coverage report counts graphs and presence of each relation by split and class; it does not interpret presence as complete-analysis guarantee. The GNN writes indices with graphs to --eligible-output; pass them as --eligible to both baselines to compare the same population. Embedding extraction records how many functions are truncated to 512 tokens and resumes by batch; if the frozen model saw projects during pretraining, freezing weights does not remove that contamination. Keep results, coverage, and extraction errors by split and label with the table, and do not present improvement on a few cases as deployment evidence.

The GNN sums embeddings of node class and up to eight code tokens using 8192 hash buckets; it uses three relational layers of width 64, three relations and their inverses, and node averaging. The bag represents token presence, not frequency, in 65536 buckets and learns logistic regression; collisions are possible. CodeBERT produces the initial-token vector with maximum length 512 and a trainable linear head. By default all three optimize unweighted binary cross-entropy with Adam at rate 0.001; the bag adds weight decay 10−510^{-5}. These are different budgets and the frozen encoder adds pretraining: comparison measures particular systems, not an isolated graph-structure advantage.

To avoid holding every graph in RAM, the cache builder traverses JSONL and saves contiguous tensors with offsets and hashes; it also needs the offset reader, binary format, and binary reader in the same folder. Use Python 3.11 or later, PyTorch, PyG, NumPy, and psutil. Conversion can resume with the same command: it verifies saved prefixes and rejects different data or code. The trainer accepts --cache, checks source and hashes, and retains example order; without it, raw graphs are loaded in memory.

In the cohort of 28062 graphs, tensors and index occupied 1.10 GB on disk. Conversion took 75.3 s after 12.7 s indexing; reading the 21970 temporal-training graphs took 2.71 s after file verification. These are measurements on this machine under shared load: reading excludes GNN, gradients, and validation and does not predict training time or peak RAM. Each of the 28062 binary graphs was compared with its source in features, edges, types, and labels.

python build_cpg_cache.py --root datos/cohorte --graphs grafos --graph-manifest grafos/manifest.json --splits datos/cohorte/cohort.splits.json --output cache-cpg
python train_cpg.py --root datos/cohorte --graphs grafos --graph-manifest grafos/manifest.json --splits datos/cohorte/cohort.splits.json --partition official_temporal --cache cache-cpg --threads 1 --device cpu --eligible-output elegibles.json --checkpoint cpg-temporal.pt --output cpg-temporal.json --predictions-prefix cpg-temporal

For example, for the temporal split and the same graph-covered subset, after extraction and audit:

python train_cpg.py --root datos/cohorte --graphs grafos --graph-manifest grafos/manifest.json --splits datos/cohorte/cohort.splits.json --partition official_temporal --eligible-output elegibles.json --checkpoint cpg-temporal.pt --output cpg-temporal.json --predictions-prefix cpg-temporal
python train_tokens.py --root datos/cohorte --splits datos/cohorte/cohort.splits.json --partition official_temporal --eligible elegibles.json --checkpoint tokens-temporal.pt --output tokens-temporal.json --predictions-prefix tokens-temporal
python embed_codebert.py --root datos/cohorte --model modelos/codebert --output codebert.npy
python train_codebert.py --root datos/cohorte --features codebert.npy --splits datos/cohorte/cohort.splits.json --partition official_temporal --eligible elegibles.json --checkpoint codebert-temporal.pt --output codebert-temporal.json --predictions-prefix codebert-temporal
python compare_results.py cpg-temporal.json tokens-temporal.json codebert-temporal.json --output comparacion-temporal.json
python errors_by_cwe.py --root datos/cohorte --splits datos/cohorte/cohort.splits.json --eligible elegibles.json --predictions cpg-temporal-seed0.json --output cpg-cwe-seed0.json

The removal variant uses original random assignments and fixed selection, without replacing the similarity-grouped split. Download the trainer with explicit selection alongside cpg_binary_store.py and the selection, and pass the same file to both baselines:

python train_cpg_dedup.py --root datos/cohorte --graphs grafos --graph-manifest grafos/manifest.json --splits datos/cohorte/cohort.splits.json --partition random --cache cache-cpg --threads 1 --device cpu --eligible-input dedup-random-eligible.json --eligible-output dedup-usados.json --checkpoint cpg-random-dedup.pt --output cpg-random-dedup.json --predictions-prefix cpg-random-dedup
python train_tokens.py --root datos/cohorte --splits datos/cohorte/cohort.splits.json --partition random --eligible dedup-random-eligible.json --checkpoint tokens-random-dedup.pt --output tokens-random-dedup.json --predictions-prefix tokens-random-dedup
python train_codebert.py --root datos/cohorte --features codebert.npy --splits datos/cohorte/cohort.splits.json --partition random --eligible dedup-random-eligible.json --checkpoint codebert-random-dedup.pt --output codebert-random-dedup.json --predictions-prefix codebert-random-dedup

To compare on exactly the same test, also retain random-split predictions without this removal with prefixes cpg-random, tokens-random, and codebert-random. The paired bootstrap filters both conditions to 2895 retained indices and applies 2000 label-stratified resamples with the same indices for all models. Its intervals are conditional on these four trainings and class counts; treating functions as independent does not capture project correlation.

python paired_bootstrap.py --results resultados --selection dedup-random-eligible.json --splits datos/cohorte/cohort.splits.json --output comparacion-pareada.json

By default all three classifiers use four seeds and up to 30 epochs, selecting by validation average precision. The comparator checks source hashes, assignments, and coverage and rejects incomplete or different-population results; it retains intervals and counts for each seed. To compare splits repeat with random, grouped_near, project, and commit, using distinct output files and checkpoints. The encoder can be extracted once for all. The local CodeBERT path must contain weights and tokenizer from revision 3b0952feddeffad0063f274080e3c23d75e7eb39; hashes are stored in metadata. Check model terms before distribution: the consulted card does not state a weight license. All three trainings save per-epoch checkpoints and accept --resume with the same configuration, data, and script version. For the cached GNN also keep the binary reader unchanged: the original trainer verifies the manifest and main script but does not itself hash the imported module. The explicit-selection variant does include that hash in its checkpoint.

For CodeBERT extraction, --device cpu or --device cuda fixes device and --threads controls PyTorch threads. Recorded identity includes both choices and program hash: changing any requires a new extraction. Also keep batch size on resumption; this version does not check it in metadata and different batches can produce small numerical differences. This option tunes execution to the machine without confusing embeddings generated under different configurations.

In the cohort of 30,000 functions, 7,659 exceeded 512 tokens and were truncated. In temporal test restricted to 28,062 functions with graphs, truncation affected 54 of 71 positive functions and 739 of 3,013 negatives. These frequencies describe what the encoder received; alone they do not prove truncation causes a performance difference. Length and omitted information nonetheless form part of interpretation of this comparison.

Results across five splits

The table shows test average precision, averaged over four seeds with 30 epochs per model and validation selection. All models in each row use the same graph-covered function intersection; tests in different rows contain different functions and are not a paired comparison. Similarity grouping keeps group functions in one split, whereas deduplicated removal uses another selection.

SplitRGCNTokensCodeBERT
Temporal0.07350.05700.0721
Random0.09160.07990.0956
Similarity grouped0.12450.08580.0644
Project0.10250.03900.1148
Commit0.18910.11910.1149

Test sizes and positives are respectively: temporal 3084 and 71; random 2900 and 69; similarity grouped 2791 and 70; project 1539 and 37; commit 2661 and 75. Positives are few and classes imbalanced. Row differences mix changes in split, size, and composition: they do not themselves identify leakage’s effect or prove generalization to future projects.

Paired removal comparison

To isolate at least the change in test population, the next table evaluates both trainings on the same 2895 retained functions, with 69 positives. The random column differs slightly from the previous table because it excludes five negatives absent from the deduplicated selection. Each figure is mean average precision across four seeds.

ModelRandomDeduplicated
RGCN0.09300.0953
Tokens0.08150.1055
CodeBERT0.09730.0975

Deduplicated minus random difference is +0.0023 for RGCN, +0.0240 for tokens, and +0.0002 for CodeBERT. With 2000 class-stratified paired resamples, 95% percentile intervals are respectively [−0.0099, 0.0136], [−0.0253, 0.0734], and [−0.0040, 0.0048]. All include zero: this test establishes neither direction of change nor equality. Intervals are conditional on four models and positive count, assume independent functions, and omit within-project function correlation. Seed standard deviations in the deduplicated condition are 0.0131, 0.0026, and 0.0011 in the same order.

Removal also changed training and used test information and labels to resolve components, as explained earlier. The result cannot be attributed exclusively to avoiding leakage. RGCN seed 3 ran as a CPU replicate independent of the other three; re-evaluating its best checkpoint gave all 2895 scores exactly matching saved values. The results summary includes splits, seeds, counts, intervals, and hashes for both branches.

With --predictions-prefix, each model saves test scores by index and seed for later analysis without changing selection. The GNN trainer locally saves each seed’s best weights; this page does not distribute them. The two heads retain predictions, but final checkpoints do not separately save best weights. Thus this run cannot evaluate those already trained heads on new examples from final checkpoints. The CWE report verifies hashes, labels, and coverage and counts true and false positives and negatives in categories with at least ten examples and ten positives; it presents Wilson intervals under the binomial assumption already described. Ten positives still yield wide intervals. Categories can overlap and their sizes must not be summed. CWE labels come from case metadata and may not alone describe each function’s cause; the report does not attribute causality or treat small groups as precise estimates.

In this run’s common coverage, only CWE-787 meets those minimums in temporal test: 471 functions, 14 positive. No category meets both minimums in the other four splits. Thus absence of a breakdown means insufficient support under this criterion, not absence of errors in those categories.

Exercises

Quiz
Why can random function splitting inflate a metric when one commit contributes functions to train and test?
Numeric
With TP=40 and FP=95, what is precision? Round to four decimal places.
Quiz
Suppose a GNN exceeds the token bag on a random split and ties within uncertainty on the temporal split. What do you conclude?
Code
Implement near_duplicate_pairs(functions, threshold): receive lists of normalized tokens, represent each function by its token set, and return index pairs i < j whose MinHash similarity estimated with 128 hashes reaches threshold and whose exact Jaccard also reaches it. For each seed s from 0 to 127, calculate the minimum hashlib.sha256(f'{s}:{token}'.encode()).digest() over tokens. Two empty sets have similarity 1; only one empty, 0. This exercise compares every pair: in production LSH saves candidates but may miss pairs.
import hashlib
def near_duplicate_pairs(functions, threshold):
  ...
Shift+Enter to run

References