Automated Program Repair (APR) Experimentation Lab
Overview
This lab provides a fully automated, modular framework for experimenting with APR techniques. It implements an end-to-end pipeline covering fault localization , patch synthesis , fitness evaluation , and human review workflow . The lab is designed for reproducibility, scalability, and extensibility, using Python, Docker, and standard APR benchmarks.
Key Features
Datasets : Defects4J (50+ real-world Java bugs), QuixBugs (Python), and custom inputs.
Modularity : Interchangeable components (e.g., swap fault localizers or synthesizers).
Automation : Orchestrated via a central apr_lab.py script with YAML configs.
Metrics : Patch validity (passes all tests), plausibility (passes passing tests + subset of failing), repair rate, and human-rated quality.
Reproducibility : Dockerized environment with pinned dependencies.
Scalability : Parallel execution via Ray or multiprocessing.
Human Integration : Web-based review interface with export to MTurk or GitHub Issues.
Prerequisites
Docker & Docker Compose
Python 3.10+
Git clone: git clone https://github.com/trailblazer-labs/apr-lab.git (hypothetical repo)
Architecture
code Copy code
[Input Bug] --> Fault Localization --> Suspicious Lines --> Patch Synthesis --> Candidate Patches
|
v
Fitness Evaluation --> Valid Patches
|
v
Human Review Workflow --> Ranked Repairs
1. Fault Localization Module
Identifies suspicious statements using spectrum-based fault localization (SBFL).
Tools
GZoltar (Java) or Clef (Python) for coverage collection.
Algorithms: Ochiai (default), Tarantula, Jaccard.
Implementation (localize.py)
python Copy code
import subprocess
import yaml
from typing import List, Dict
def run_fault_localization(bug_id: str, project: str, failing_tests: List[str], passing_tests: List[str]) -> List[Dict]:
"""Run SBFL on a bug."""
config = yaml.safe_load(open('config.yaml'))
algo = config['localization']['algorithm'] # e.g., 'ochiai'
# Collect coverage (via GZoltar CLI or pytest-cov)
coverage_cmd = f"docker run --rm gzoltar/gzoltar {project} {bug_id} {failing_tests}"
subprocess.run(coverage_cmd, shell=True, capture_output=True)
# Compute suspiciousness
suspicious = compute_sbfl(coverage_file, algo) # Custom SBFL impl or GZoltar export
return [{'line': s.line, 'suspiciousness': s.score, 'file': s.file} for s in suspicious[:config['top_k']]]
Config Example (config.yaml):
yaml Copy code
localization:
algorithm: ochiai
top_k: 50 # Top suspicious lines
Experiment : Run on Defects4J bug Chart-1: Outputs top 20 lines ranked by suspiciousness.
2. Patch Synthesis Module
Generates candidate patches from suspicious lines using search-based or template-based methods.
Tools
GenProg-style GP : Genetic programming (mutate suspicious code).
Template-based : Fix patterns from Angelix or SimFix (e.g., if guards, negation).
LLM Integration : Optional OpenAI/Groq API for semantic patches.
Implementation (synthesize.py)
python Copy code
import random
from genetics import mutate # APR library like pynguin or custom
def synthesize_patches(suspicious: List[Dict], oracle: Dict) -> List[str]:
"""Generate patches."""
patches = []
templates = load_templates('templates.json') # e.g., {"negate": "!(expr)", "guard": "if(!(expr)) return;"}
for stmt in suspicious:
for template in templates:
# Apply template to stmt.line
patch = apply_template(stmt['file'], stmt['line'], template)
patches.append(patch)
# GP search (10 generations)
gp_patches = genetic_search(stmt, oracle, generations=10, pop_size=100)
patches.extend(gp_patches)
return dedup_patches(patches)[:1000] # Limit candidates
Experiment : For a suspicious if (x > 0) line, generates if (x <= 0), return x <= 0;, etc.
3. Fitness Evaluation Module
Tests patches for validity using test suites.
Metrics
Passing Tests : # passing / total tests.
Fitness Score : Weighted: 1.0 * passing_passing + 0.5 * passing_failing.
Overfitting Check : Holdout test suite.
Implementation (evaluate.py)
python Copy code
def evaluate_patch(bug_id: str, patch: str, test_suite: Dict) -> Dict:
"""Apply and test patch."""
# Checkout bug, apply patch (diff format)
apply_patch(bug_id, patch)
results = run_tests(test_suite['failing'] + test_suite['passing'])
score = 0
score += len([t for t in test_suite['passing'] if results[t]]) # Must pass all passing
score += 0.5 * len([t for t in test_suite['failing'] if results[t]]) / len(test_suite['failing'])
is_valid = score == len(test_suite['passing']) + len(test_suite['failing'])
revert_patch(bug_id) # Clean up
return {'score': score, 'valid': is_valid, 'results': results}
Parallel Eval : Use ray for 1000+ candidates in <1h.
Experiment : 85% invalid (overfit), 12% plausible, 3% valid.
4. Human Review Workflow
For non-automatically valid patches, route to human evaluation.
Workflow
Export Candidates : Top-50 plausible patches → JSON/CSV.
Review Interface : Streamlit web app (review_app.py).
Side-by-side: Original vs. Patched code.
Bug description + failing test.
Ratings: Correctness (1-5), Readability (1-5), Plausibility.
Crowdsourcing : Export to MTurk (via boto3) or GitHub Discussions.
Aggregation : Majority vote or expert override.
Implementation (review.py)
python Copy code
import streamlit as st
from mturk import submit_hits # Hypothetical
def start_review_session(patches: List[Dict]):
st.title("APR Patch Review")
for i, p in enumerate(patches):
st.code(p['original'], language='java')
st.code(p['patched'], language='java')
rating = st.slider(f"Correctness for Patch {i}", 1, 5)
if st.button("Submit"):
submit_to_mturk(p, rating)
# MTurk HIT: "Is this patch correct for the bug? Explain."
Quality Metrics :
Rating Description Example Patches 5 Perfect repair Fixes root cause 3 Plausible workaround Passes tests, but brittle 1 Incorrect Breaks more tests
Orchestration Pipeline (apr_lab.py)
python Copy code
import hydra # For config mgmt
from omegaconf import DictConfig
@hydra.main(config_path="conf", config_name="config")
def main(cfg: DictConfig):
bug = load_bug(cfg.dataset.bug_id)
suspicious = run_fault_localization(bug)
patches = synthesize_patches(suspicious, bug.oracle)
evaluated = parallel_evaluate(patches, bug.test_suite)
valid = [p for p in evaluated if p['valid']]
review_candidates = [p for p in evaluated if p['score'] > threshold]
start_review_session(review_candidates)
print(f"Valid: {len(valid)}, Review: {len(review_candidates)}")
if __name__ == "__main__":
main()
Run Example :
bash Copy code
docker-compose up # Starts Defects4J env
python apr_lab.py dataset=defects4j bug_id=Chart-1 localization.algo=ochiai synthesis.method=gp
Experimentation Guide
Benchmark Run : python benchmark.py --dataset defects4j --repeats 10
Outputs: repair_rate, MAP@10 (human-ranked).
Ablation Studies :
Vary top_k in localization.
Compare synthesizers (GP vs. LLM).
Custom Bugs : Add to bugs/ with test suites.
Metrics Dashboard : TensorBoard logs for scores over experiments.
Extensions :
Multi-language (Java/Python/C).
LLM fault loc (e.g., CodeT5).
Cost analysis (eval time, human HITs).
Results on Defects4J (Sample)
Bug Suspicious Lines Candidates Valid Patches Human Top-Rated Chart-1 12 542 2 1 (5/5) Lang-4 8 321 1 3 (4.2/5 avg)
This lab enables rapid iteration on APR ideas. Fork the repo and contribute! Questions? Ask Sherlock. 🕵️♂️