Developer tools · Research feature

Detecting Argument-Swap Bugs Using Context-Enhanced Code Representations

The researchers collect a new dataset of 132,739 Python source files from the top-1,000 starred GitHub repositories, yielding 3,371,244 synthetic training examples, and contribute a curated benchmark of 55 real-world argument-swap bugs manually verified from commit histories.

Adapted from research by Subrata Das, Ali Aman, Muhammad Asaduzzaman and colleagues.

arXiv preprint revision · 2026-09-15 · Attribution & reuse
In this article
Editorial illustration of stacked plates.

Authors’ overview

Names of source code elements convey rich semantic information and have been widely used in software engineering tasks such as bug detection, code completion, type prediction, and code classification. Prior studies exploit lexical similarity between method arguments and formal parameter names to detect bugs caused by incorrectly ordered arguments, typically relying on establishing mappings between method calls and their corresponding definitions. However, such mappings are often difficult to obtain in dynamically typed languages like Python. In this paper, we present BugProbe, a learning-based approach for detecting incorrectly ordered arguments in Python method calls that does not require call-to-definition mappings. Our approach leverages multiple sources of contextual information, including local context and argument usage context, and combines name-based similarity with machine learning to construct expressive representations of method arguments. We collect a new dataset of 132,739 Python source files from the top-1,000 starred GitHub repositories, yielding 3,371,244 synthetic training examples, and contribute a curated benchmark of 55 real-world argument-swap bugs manually verified from commit histories. We evaluate our approach on this dataset and show that it achieves high accuracy and consistently outperforms a state-of-the-art baseline across standard evaluation metrics. These results demonstrate that effective detection of argument-ordering bugs is possible without relying on explicit call-to-definition resolution, making the approach well suited for dynamically typed language settings.

Introduction

Argument-swap bugs are a common source of programming errors, particularly in dynamically typed languages. Such bugs occur when a developer accidentally passes arguments to a method in the wrong order. We use the term call site to refer to a location in source code where a function or method is invoked. Because swapped arguments often have compatible types, the program may continue executing without raising an error, silently producing incorrect behavior that is difficult to diagnose.

Identifier names convey valuable semantic information about program behavior. Meaningful names aid program comprehension and support tasks such as code completion and identifier name suggestion. Prior work has also observed that developers often use similar names for call site arguments and their corresponding formal parameters. As a result, the similarity between argument names and parameter names has been exploited to detect argument-swap bugs.

However, approaches based solely on lexical similarity are fragile. Developers may use semantically related but lexically different identifiers (e.g., area and region), limiting the effectiveness of string-based comparisons. To address this, Pradel et al. proposed DeepBugs, which learns vector representations (embeddings) of identifiers to detect semantic similarity even when names differ lexically.

Despite its effectiveness, DeepBugs has important limitations when applied to dynamically typed languages such as Python. First, it requires mapping call sites to their corresponding method definitions to compare argument names with formal parameter names. This mapping is challenging in dynamic languages and often infeasible when definitions reside in different files or external libraries. In our study of Python code, we found that 89% of call sites have their definitions located in different files, frequently within third-party libraries. Second, DeepBugs learns embeddings from a limited local token window around every identifier, regardless of its role. Argument-swap detection requires understanding how arguments at call sites relate to one another across broader code structures, which narrow identifier-level contexts may miss.

Detecting incorrectly ordered arguments. A number of studies have investigated the problem of identifying incorrectly ordered arguments and related defects. Pradel and Gross introduced an anomaly-based approach for detecting swapped arguments of identical types. Their method analyzes recurring call site patterns and flags calls whose argument order deviates from commonly observed naming conventions in similar contexts. Liu et al. explored the lexical similarity between argument names and formal parameter names in 60 real-world Java programs, demonstrating that name similarity can be leveraged to identify incorrectly ordered arguments and recommend corrections. Li et al. further analyzed lexical similarity distributions, name length, and causes of dissimilarity, and discussed applications such as argument renaming and argument suggestion.

Rice et al. proposed a name-based similarity matching approach to identify argument selection defects, showing that discrepancies between argument and parameter names often indicate potential bugs. Scott et al. introduced SWAPD, which combines coverage-based and statistical checking strategies to detect swapped arguments. While effective in specific scenarios, these approaches primarily rely on handcrafted heuristics or lexical similarity measures and do not employ learning-based models to capture richer contextual information.

The most closely related work to ours is DeepBugs, which formulates bug detection as a binary classification problem using learned embeddings derived from local token context. However, DeepBugs requires mapping call sites to their corresponding definitions, which is challenging in dynamically typed languages such as Python. Moreover, it relies on a narrow local context window when constructing embeddings. In contrast, our approach does not depend on call–definition mappings and incorporates multiple complementary usage contexts to construct richer representations of arguments and call sites.

Argument recommendation and completion. Our work is also related to research on argument recommendation and method call completion. Zhang et al. proposed Precise, which collects argument usage examples from existing code and matches call-site contexts against a usage database to recommend appropriate arguments. Asaduzzaman et al. introduced PARC, a parameter recommendation system that supports a broader range of parameter expression types than Precise. More recently, Nguyen et al. combined program analysis with statistical language models to recommend type-compatible arguments.

Data Collection

We collected a dataset of Python source files by cloning the top-1,000 Python repositories from GitHub, ranked by star count. To ensure repository quality and activity, we applied the following inclusion criteria: at least two contributors, at least 100 commits, and at least one commit within the past year. We further retained only files that parse successfully under Python 3.11, ensuring compatibility with our analysis pipeline. This initial collection yielded 381,244 Python source files.

After preprocessing, the final dataset consists of 132,739 Python source files drawn from the 1,000 repositories, comprising 34,357,043 total source lines. The dataset contains 1,685,622 qualifying call sites. Each call site contributes one positive (correct) example and one negative (incorrect) example generated by swapping the first two arguments, yielding 3,371,244 total examples. Following the 5-fold cross-validation split described in Section V, 2,696,686 examples are used for training and 674,558 for testing in each fold. Table I summarizes the key statistics of the final dataset.

Call-Site Argument Arity: Our negative example generation swaps only the first two positional arguments at a call site, which raises the question of how much of the qualifying call-site population this covers. Among the 1,685,622 qualifying call sites (i.e., each call site contains two or more arguments), 1,308,770 (77.6%) have exactly two positional arguments and are therefore fully covered by our (1,2)-swap negative sampling strategy. The remaining 376,852 call sites (22.4%) have three or more positional arguments, meaning that at least one possible argument-position pair at these call sites is not exercised by our synthetic negative examples, and for which BugProbe’s generalization to higher-arity swaps remains untested. We do not further analyze whether classification difficulty correlates with call-site arity or argument position (e.g., parameters with default values, which tend to appear at the end of the parameter list), due to space limitations; we leave this to future work. We view extending negative example generation to arbitrary argument-position pairs, and evaluating whether representations learned from (1,2)-swaps transfer to higher-arity swaps, as an important future direction.

Real-World Bug Dataset: In addition to the synthetic dataset, we contribute a curated dataset of 55 real-world argument-swap bugs collected from the commit histories of the 1,000 repositories. For each repository, we mined commits that modified function call sites and identified candidate changes where the ordering of arguments had been altered. To ensure that each candidate reflected a genuine bug fix rather than a refactoring, we explicitly verified that the same commit did not also modify the corresponding function definition in a way that reordered its parameter declarations — such a co-change would indicate an intentional renaming or signature refactor rather than a correction of a misplaced argument. Remaining candidates were then manually verified by two human annotators, who examined the commit message for explicit mention of an argument-ordering mistake and inspected the surrounding code context to confirm that the original ordering constituted a defect.

Data Extraction

Local Context (LC) is a token window around the occurrence (argument or call site). We extract up to 10 tokens before and 10 tokens after the occurrence from the tokenized source line(s), filtering out common punctuation and operators.

Argument Usage Context (AUC) captures how the argument name is used earlier within the same enclosing scope (e.g., a function body). We collect token sequences from preceding lines that reference the argument name, capturing assignments, updates, and prior calls.

Latest Usage Context (LUC) consists of tokens from the closest preceding line in the same scope that mentions the argument name. This approximates the most recent usage signal, such as the last assignment or transformation before the call.

Parent Context (PC) represents the syntactic container of the call site. We identify a meaningful AST parent (e.g., loop header, conditional header, or function definition) and extract tokens from the parent’s line, capturing structural cues that influence argument semantics.

Embedding Generation

For each call site with at least two arguments, we extract the four context types (LC, AUC, LUC, and PC) for each argument. Each context instance is treated as a separate sentence composed of its constituent tokens. This process yields four context-specific corpora, one per context type, each containing token sequences derived from argument usages across the corpus.

To better preserve syntactic and semantic roles during tokenization, BugProbe optionally augments tokens with their expression type (ET). An expression-type encoded token appends a lightweight syntactic role (e.g., assignment target, call argument, binary operand) to the original identifier, allowing identical names used in different expression contexts to be distinguished during embedding learning. Table III illustrates common Python expressions and their corresponding token sequences with and without ET encoding.

We concatenate these corpora into a single training corpus and train a Word2Vec model using the Continuous Bag-of-Words (CBOW) architecture with a context window size of 5 and an embedding dimensionality of 100. By training on aggregated context signals rather than isolated identifiers, the resulting embeddings capture richer semantic relationships grounded in both lexical usage and structural code context.

Experimental Setup

Among all qualifying call sites, 1,685,622 have more than one argument and are therefore retained for our evaluation. Each call site contributes one positive and one negative example, yielding 3,371,244 total examples. Of these, 2,696,686 are used for training and 674,558 for testing across the five folds.

To evaluate the baselines, we utilize a 5-fold cross-validation strategy at the file level. Specifically, the dataset is randomly partitioned into five disjoint subsets of approximately equal size. During each fold, one subset (20% of the files) is used as the test set, while the remaining four subsets (80% of the files) are used for training. This process is repeated five times, such that each subset serves as the test set exactly once. All reported results are averaged over the five folds. For each fold, the Word2Vec embeddings are trained exclusively on that fold’s training files, ensuring no information from the test files influences the learned representations. Files containing real-world bugs from our curated benchmark are excluded from this split entirely, and therefore from Word2Vec training as well.

Results

Tables IV and V report the performance of DeepBugs and BugProbe on mapped call sites and on the complete dataset, respectively. On mapped call sites, BugProbe consistently outperforms DeepBugs, achieving an accuracy of 87.8% compared to 84.6%, corresponding to an absolute improvement of 3.2 percentage points (3.8% relative), alongside higher per-class precision, recall, F1-score, and improved AUC. The performance gap becomes more pronounced when considering all call sites: BugProbe attains an accuracy of 91.1%, compared to 81.8% for DeepBugs, yielding an absolute improvement of 9.3 percentage points (approximately 11.4% relative). Similar gains are observed across precision, recall, and F1-score, with BugProbe improving F1-scores by approximately 9 percentage points across classes, and increasing AUC from 92.0 to 97.5. When isolating only the unmapped call sites, the gap widens further, with BugProbe achieving an accuracy improvement of 10.2 percentage points over DeepBugs. These results demonstrate that BugProbe not only outperforms DeepBugs when call–definition mappings are available, but also remains robust and highly effective in their absence.

Motivation

BugProbe represents call sites and their arguments using multiple complementary sources of contextual information, each capturing a different aspect of how arguments are defined, manipulated, and consumed. Local lexical context provides immediate syntactic cues but is often insufficient for subtle errors such as argument swaps; argument usage context models how values flow through assignments prior to a call; parent and latest usage contexts encode structural information from enclosing constructs; and lightweight type information differentiates literals and primitives, particularly when swapped arguments share the same static type.

Although each source is individually informative, their relative contributions remain unclear. BugProbe can also incorporate expression-typed (ET) token encoding to distinguish identifiers by syntactic role, at the cost of added complexity. This motivates an empirical investigation into the individual and combined impact of these feature groups, and whether ET encoding yields benefits beyond standard tokenization.

Results

Combining callee-level local context with argument local context (M3) leads to a large performance gain. M3 achieves an F1-score of 89.98% and an AUC of 97.08% without ET encoding, improving F1 by approximately 27.9 percentage points over M1. Adding longer-range contextual information through argument usage context and parent/latest usage context (M4) yields an F1-score of 90.61% and an AUC of 97.23%, which is within 0.1 percentage points of the full model. The complete BugProbe configuration (M5) achieves the highest overall performance, with an F1-score of 90.71% and an AUC of 97.26%, confirming that each additional context source contributes incremental but measurable improvements.

Expression-typed (ET) token encoding provides consistent but modest gains across most configurations. The largest absolute improvement is observed for M1 (from 62.07% to 67.86% F1, a gain of 5.79 percentage points), while gains for context-rich models such as M4 and M5 are smaller (approximately 0.5 percentage points). These results suggest that while ET encoding does not fundamentally change model behavior, it provides useful syntactic disambiguation that complements contextual information and slightly improves detection accuracy.

Threats to Validity

Internal validity. Our primary evaluation relies on synthetic negative examples generated by swapping the first two arguments of call sites. While widely adopted in prior work, not all synthetic swaps necessarily correspond to real bugs, and some swapped calls may remain semantically correct. Since the same generation procedure is applied to all evaluated approaches, this threat does not bias the comparative results. We further evaluate BugProbe on a curated benchmark of 55 real-world argument-swap bugs, which directly assesses detection on organically occurring defects and substantially mitigates the above-mentioned concern, though at 55 bugs it remains small relative to the synthetic set and results should be read as indicative rather than statistically comprehensive.

External validity. Our experiments use a large corpus of open-source Python projects from GitHub. While the dataset spans diverse domains, results may not generalize to proprietary codebases or other languages, particularly those with stronger static typing or different naming conventions. Python nonetheless remains a challenging and widely used dynamically typed language, making it a meaningful target for this study.

Conclusion validity. BugProbe relies on Word2Vec embeddings, chosen to ensure a fair comparison with DeepBugs; alternative embedding architectures may yield different results. Our findings on pre-trained embeddings are therefore specific to the evaluated models rather than a general limitation of pre-trained representations.

Conclusion

In this paper, we investigate the problem of detecting incorrectly ordered arguments in Python programs and propose BugProbe, a machine learning–based approach for identifying argument-ordering bugs. BugProbe frames the task as binary classification and uses learned representations derived from multiple contextual signals, including local lexical context, argument usage patterns, structural context, and lightweight type information, capturing both local and long-range dependencies relevant to argument ordering. Evaluations on synthetic and real-world bug datasets show that BugProbe consistently outperforms DeepBugs and other baseline techniques. Crucially, BugProbe requires no explicit mappings between call sites and their definitions, making it well suited to dynamically typed languages where such mappings are often unavailable. An ablation study further shows that combining multiple contextual feature groups is key to strong performance, while expression-typed token encoding yields modest but consistent gains.

In future work, we plan to explore richer type information from static type inference tools, extend BugProbe to other semantic bug patterns, and compare its effectiveness against large language models (LLMs) and additional baselines such as SWAPD and NALIN for source-code bug detection.