Editor’s introduction
The study evaluates medical data by generating context-aware tests using large language models to identify discrepancies between observed patient data and established epidemiological patterns. This method, called Medical Data Pecking, applies principles from software testing to assess clinical plausibility, going beyond syntax checks to detect implausible data distributions. The researchers applied the framework to three datasets, where it generated dozens of tests per cohort and found mismatches between recorded data and expected clinical outcomes. These mismatches include both actual data errors and known cohort selection effects. The work demonstrates a scalable way to perform semantic auditing, offering a framework that shifts from static rule-based validation to dynamic, context-sensitive verification.
Introduction
In this work, we propose the adoption of quality assurance techniques from engineering disciplines to enhance process efficiency and ensure reliable and high-quality outcomes. Specifically, in software engineering, unit tests are typically written prior to or immediately following code implementation. Ideally, all execution paths are covered by unit tests. These local tests are designed to evaluate a specific segment of code to verify its correctness and are run frequently to identify potential bugs early and close to their origin. Consequently, automated test suites are commonly integrated into the Continuous Integration/Continuous Development (CI/CD) process.
We argue that in data-driven applications, software engineering best practices should be applied not only to the codebase but also to the data itself, as errors in either can lead to system failures or misleading conclusions. Such practices should encompass all components of the application, including the data preprocessing pipeline, where issues may affect any variable, not just those detected by downstream statistical analyses. Faults in raw data or early-stage processing can propagate unnoticed and ultimately compromise research validity.
The evaluation of data quality should consider the context of the analysis with respect to populations, geographies, specific time frames, and medical conditions. Existing quality assessment methods often neglect these contextual factors, focusing instead on syntactic completeness.
Although concordance with external datasets and prior knowledge could bridge these gaps, most current tools omit this due to the complexity of manually defining rules for every possible clinical scenario. We propose using Large Language Models (LLMs) to automate the creation of such rules for a given use case.
Recent breakthroughs in natural language processing, particularly the introduction of LLMs, are reshaping multiple domains including medical data analysis. LLMs have been applied to automate data extraction, recognize clinical phenotypes, curate concept sets, explore datasets, predict clinical risk, and manage time-sequenced events during data preprocessing. A cited study evaluated LLMs across a range of data-related tasks, demonstrating state-of-the-art performance in data imputation, integration and error detection, even without task-specific fine-tuning.
Building on these capabilities, we introduce the Medical Data Pecking approach. We propose Medical Data Pecking to add systematic semantic auditing to complement existing data validation tools. While Medical Data Pecking can perform baseline structural checks, its primary utility is the identification of Semantic Gaps - instances where data maintains structural validity yet lacks epidemiological consistency. We demonstrate this approach through a reference implementation that utilizes LLMs to dynamically generate unit tests tailored to the target population and dataset. Analogously to selective pecking behavior in birds, Medical Data Pecking scans structured health records to identify relevant data fields, flag inconsistencies, and exclude extraneous content. It applies the generated tests to the data, identifies potential issues, and reports untested fields to quantify the coverage of the test suite.
Sensitivity to Known Biases (Control Validation)
Because real-world datasets lack a gold standard answer key for data quality, we validated the tool’s discernment using a positive control approach. To do this, we examined its performance on the AoU dataset, which is known to have specific recruitment skews.
Without manual configuration, the MDPT framework correctly flagged demographic anomalies. Specifically, the generated semantic tests for gender and race distributions failed, accurately identifying the known over-representation of women and under-represented groups in the AoU cohort. This serves as a positive control, confirming that the dynamic semantic testing paradigm is capable of autonomously detecting deviations from general population priors without explicit user programming.
Uncovering Semantic Divergence
In the AoU T2D cohort, 54 of the 60 generated tests failed. Although the data were syntactically complete, the framework revealed substantial discrepancies between the observed prevalence of comorbidities and expectations derived from the literature. Similarly, in the CKD cohort, 65 of the 67 tests failed.
In the MIMIC-III dataset evaluation for CHF, the framework detected a systematic formatting issue that rendered valid data semantically invisible. The tests failed due to a mismatch in ICD-9 coding standards (omission of decimal points). While standard syntactic checks validated these strings as non-null and allegedly correct, the semantic test, expecting a specific diagnosis prevalence, dropped to near zero, triggering a failure flag. This example shows that the framework can identify semantic discrepancies that may compromise downstream analysis. Although the omission of decimal points may appear to be a trivial formatting nuance, it represents a semantic break. Consequently, valid but dot-less ICD-9 codes were not captured by standard phenotype algorithms. MDPT detected this by identifying that the observed prevalence of the disease was inconsistent with epidemiological priors.
Failure and Robustness Analysis
The pattern differed across cohorts. In the CHF cohort, zero-prevalence failures were primarily technical artifacts, mostly linked to the systematic omission of decimal points in ICD-9 codes. In the HTN cohort, these values were associated with gaps in the modeling of secondary comorbidities. In the CKD and T2D cohorts, they often reflected specification gaps during cohort construction, where relevant clinical items were overlooked in the initial cohort definition.
Discussion
In this study, we introduced Medical Data Pecking, a semantic unit testing methodology that adapts software engineering principles to medical data validation. While traditional quality assessment tools (such as OHDSI Achilles) provide extensive libraries of universal checks (e.g., ’Gender=Male cannot have pregnancy codes’), these rules are necessarily context-agnostic. A static rule library cannot capture the complexity of clinical context, such as the expected prevalence of a specific comorbidity in a distinct demographic cohort. Consequently, MDPT functions as a complementary semantic validation layer. By addressing clinical implausibility in syntactically perfect data, the framework can identify discrepancies that may not be detected by traditional integrity checks. Using MDPT we generated 23-43 semantic tests classified as correct and identified 20–43 discrepancies per cohort in data that were syntactically valid under standard checks. This demonstrates the benefit of using adaptive validation rather than a fixed set of rules. Our results suggest that syntactic completeness alone may be insufficient to establish semantic plausibility, and that verification against external evidence may reveal clinically relevant mismatches.
Sensitivity analyses indicated that the main findings were more sensitive to proportional tolerance than to the SMD cutoff. Failure rates remained largely stable across the evaluated SMD values, suggesting that proportional tolerance had the greater influence on evaluation strictness.
Consequently, it is crucial to distinguish between data errors and cohort selection biases. A high failure rate in the MDPT suite does not always imply corrupted data; rather, it quantifies the distance between the specific dataset and the general population baseline as reported in the scientific literature. For example, the high failure rate in MIMIC-III reflects its specific ICU population, which naturally deviates from outpatient epidemiological priors. Similarly, the failures observed in the SyntheticMass dataset may reflect the specific generative methodology of the Synthea engine, where certain complex clinical correlations may not have been modeled, rather than a failure of the data pipeline itself. In this setting, MDPT can help characterize representational discrepancies introduced during synthetic data generation and identify how the resulting study population differs from the general population.
The detection of formatting-induced errors in MIMIC-III highlights how clinically meaningful information can become unavailable to downstream analyses despite remaining syntactically valid in the raw data. Although the underlying code strings are present and pass syntactic checks, the omission of a decimal point can alter the encoded signal enough to make the phenotype effectively undetectable by standard algorithms. This example shows that semantic testing can identify failures that conventional syntactic checks may miss through implausible prevalence estimates. In particular, zero-prevalence failures provide a distinct diagnostic signal that suggests either a technical artifact or a mismatch between the clinical query and the level of abstraction represented in the dataset. By identifying these cases, the framework helps distinguish routine distributional differences from more fundamental incompatibilities between the intended research question and the structure of the available data.
The imperative for this dynamic validation is growing. The White House Office of the National Cyber Director advocated the development of quality metrics to evaluate software modularity, security, and automation. Similarly, the Bipartisan House AI Task Force identified data quality as a critical concern. reinforced these concerns through the STANDING Together recommendations, a global initiative to mitigate algorithmic bias in healthcare AI. In the era of Big Data, manual verification is infeasible and errors in the data pipeline propagate unnoticed, undermining the validity of downstream AI models. Our framework provides a scalable and automated approach for addressing this validity gap, offering a mechanism to operationalize these high-level policy and ethical recommendations into code.
A primary challenge in applying LLMs to quality assurance is the risk of hallucination or faulty tests. We addressed this through a tiered evidence grounding protocol reinforced by an automated verification loop. Rather than relying on the LLM’s knowledge, our system functions as a retrieval engine, anchoring every test in verifiable sources. Crucially, the system utilizes a recursive search strategy: after the initial generation, a secondary ’Auditor Agent’ independently searches for and verifies the statistics, allowing the system to self-correct and discard unsupported claims before they become unit tests. Although our evaluation showed that drug prevalence tests remain difficult to ground due to data scarcity, the stronger grounding of disease and demographic tests suggests that RAG-based architectures with independent verification cycles may support automated epidemiological validation.
In this study, we use an auditor agent to reduce major grounding errors. Nevertheless, there is still room for improvement that may be achieved by using more advanced LLMs and by conducting additional iterations of ”debate” between agents until they agree on the values reported in the document.
To maintain clinical reliability, the Medical Data Pecking framework separates generative synthesis of tests from their subsequent execution. By fixing the validated test matrix as a versioned asset within the clinical pipeline, the system provides a stable audit trail. This architecture mitigates reproducibility risks associated with evolving external APIs and helps maintain consistency of the audit over time.
As argued, testing can be used to show the presence of bugs, but never to show their absence. Our current implementation is limited by its reliance on general population benchmarks, which can obscure deviations in specific subgroups. However, this is largely a limitation of data availability rather than of the methodology itself.
Methods
The Medical Data Pecking framework consists of three main components: (i) a taxonomy of semantic unit tests, (ii) automated methods for test synthesis, and (iii) procedures for applying these tests to data. This section describes each component in turn and then presents the datasets used to evaluate MDPT, the reference implementation of the framework.
Taxonomy of Semantic Unit Tests
To systematically evaluate the extent to which data were validated for research, we propose a hierarchical taxonomy of data validation based on the software engineering principle of ”test coverage”. Traditional quality metrics primarily ensure syntactic coverage, verifying that fields adhere to correct formats. While some frameworks extend this to semantic validation, they rely on manually curated rules to detect logical errors. This approach is labor-intensive and not scalable to the complexity of medical data. In contrast, our approach introduces Semantic Data Coverage to validate the alignment of observed data with epidemiological ground truth. Specifically, we distinguish three distinct levels of validation: the syntactic (metadata) level, the distributional semantic level, and the contextual semantic (subpopulation) level.
Distributional semantic level: Tests at this level validate that population metrics align with theoretical or literature baselines. For example, the distribution of a specific laboratory test across the entire cohort is checked against its expected range. This ensures that the data are statistically plausible in aggregate.
Contextual semantic level (Subpopulation): Tests at this level analyze intra-group patterns, such as comorbidity rates or drug prevalence within specific demographic cohorts. For example, these tests might check the prevalence of hypertension in women compared to men. This level offers greater depth than population checks by detecting context-specific biases or errors that remain invisible to aggregate analysis.
Automated Test Synthesis
To support deployment in secure clinical environments, the MDPT framework utilizes a decoupled architecture that separates logic generation from data execution. The system is organized into two functionally isolated modules: the Generation Module and the Test Application Module.
Generation Module: This module operates exclusively on the study specification and the data dictionary, which describes the available database fields, their meanings, formats, and coding. The LLM utilizes this metadata to map clinical intent to the local database schema and generate executable unit tests. No raw, individual-level patient data is ever transmitted to or accessed by this module.
Test Application Module: This module resides within the user’s secure, isolated environment. It receives the generated test suite and executes it directly against the raw patient data. This separation of concerns ensures that protected health information remains within the local security perimeter while utilizing generative models for test construction.
Contextual Parameter Extraction and Grounding
To address the scalability challenge of creating context-specific unit tests, the MDPT framework employs a Retrieval-Augmented Generation (RAG) architecture. The test generation pipeline operates in two primary stages: Contextual Parameter Extraction and Automated Grounding and Evidence Verification.
Directed Prioritization: The system retrieves initial reference statistics via the Bing Search API. Through system prompting, the model is explicitly required to prioritize high-authority sources, such as government health agencies (e.g., CDC, NIH) and peer-reviewed literature, over general web results when selecting benchmarks.
Test Matrix Construction: The retrieved epidemiological benchmarks are transformed into a structured test matrix. This matrix defines the preliminary expected value ranges for each semantic test (e.g., ”The prevalence of Type 2 Diabetes in US adults is expected to be between 8% and 12%”). This automated synthesis allows the framework to generate dozens of context-aware tests from a single high-level query.
The Auditor Agent (Double-Pass Verification): To mitigate hallucination, we used an approach inspired by Self-Refine, where an ”Auditor Agent” performs a new, targeted search to verify the accuracy of the statistics proposed in the matrix. This agent is explicitly required to validate the correctness of the extracted value; it cross-references the matrix entries against newly retrieved evidence and automatically corrects the value if discrepancies are detected. In this implementation, both the Generator and Auditor utilize GPT-4o; however, independence is maintained through information decoupling, where the Auditor initiates an entirely separate search thread, and role-specific prompting. This architecture ensures that the verification pass is grounded in a fresh evidentiary context.
Execution and Statistical Validation
Magnitude of Difference: To distinguish between statistical significance and clinical relevance, particularly in large datasets where minor deviations may yield low p-values, we calculate the Standardized Mean Difference (SMD). Discrepancies are flagged only when the SMD equals or exceeds 0.2, representing a non-negligible deviation from the expected distribution.
Proportional Tolerance: For categorical prevalence (e.g., comorbidity rates), we define a tolerance margin based on prior EHR validation studies. A test passes if the ratio between the observed and expected proportion falls within the interval of 0.85 to 1.15. Ratios outside this range indicate a deviation of greater than 15% from the expected baseline and trigger a failure flag.


