We are going to design an automated program repair (APR) experimentation lab.
The lab will have the following components:
- Fault Localization: Given a buggy program and a test suite (with at least one failing test), locate the buggy lines.
- Patch Synthesis: Based on the fault localization, generate candidate patches (fixes) for the buggy lines.
- Fitness Evaluation: Evaluate the candidate patches by running the test suite and checking which tests pass/fail.
- Human Review: Provide an interface for human experts to review the generated patches and select the best one.
We'll design the system in a modular way so that each component can be replaced or extended.
Steps:
-
Input:
- A buggy program (source code) and a test suite (unit tests) that fails at least one test.
-
Fault Localization:
- We'll use a spectrum-based fault localization technique (e.g., Ochiai) that uses the passing and failing test executions.
- Alternatively, we can use more advanced techniques, but for simplicity we start with a basic one.
-
Patch Synthesis:
- We'll use a generate-and-validate approach. For each suspicious line (from step 2), we generate mutations (patches) using predefined edit operations (like replace, insert, delete).
- We can use a set of repair templates (like from existing APR tools) to generate patches.
-
Fitness Evaluation:
- Run the test suite for each candidate patch and record which tests pass and which fail.
- We consider a patch as "correct" if it makes all tests pass and does not introduce new failures (or at least the original failing tests pass and no previously passing tests fail).
-
Human Review:
- If multiple patches are generated that pass all tests, or if we want to choose between patches that are plausible but not perfect, we need human review.
- We'll provide a web-based interface (or a simple command-line if in a lab setting) that shows:
a. The original buggy code and the failing tests.
b. The candidate patches with their test results (which tests passed/failed).
c. The diff of the patch.
d. An option for the human to select the best patch or provide feedback.
-
Output:
- The selected patch (either by automated validation or human review) and the fixed code.
However, note that in practice, we might have multiple bugs. We assume one bug for now, but the system can be extended to multiple.
Implementation Plan:
We'll write the system in Python for ease of prototyping and integration with existing tools.
Steps in code:
-
Preprocessing:
- Parse the source code and test suite (we assume they are in Python for simplicity, but the ideas are language-agnostic).
- We'll use the
ast module for Python code.
-
Fault Localization:
- We'll run the test suite and record which tests pass and fail.
- We'll instrument the code to collect coverage (which lines are executed by each test). We can use
coverage module for Python.
- Then, for each line, we compute a suspiciousness score (like Ochiai).
-
Patch Synthesis:
- For the top N suspicious lines (we can set a threshold), we generate patches.
- We'll define a set of edit operations (replace, insert, delete) and apply them to the suspicious line (or nearby lines) to generate candidate patches.
- We can also use more sophisticated techniques like using a language model or extracting fix patterns from existing patches, but for simplicity we start with simple mutations.
-
Fitness Evaluation:
- For each candidate patch, we apply the patch to the original code and run the test suite.
- We record the test results.
-
Human Review:
- We'll create a simple web app using Flask or Streamlit to display the results and allow human selection.
-
Output:
- The final selected patch is applied to the original code and saved.
However, note that generating and evaluating many patches can be time-consuming. We might need to limit the number of patches.
Let's break down the modules:
Module 1: Fault Localizer
- Input: source file, test directory (or test file)
- Output: list of suspicious lines with scores, sorted by score.
Module 2: Patch Synthesizer
- Input: source file, list of suspicious lines (with line numbers and maybe context)
- Output: list of patches (each patch is a tuple: (line number, edit operation, edit content) or a diff string)
Module 3: Fitness Evaluator
- Input: original source file, list of patches, test directory
- Output: for each patch, a test result (list of test names and whether they passed/failed) and a score (like number of passed tests, or just a boolean if all tests pass).
Module 4: Human Review Interface (optional if we have a perfect patch)
- Input: original code, failing tests, list of patches with their test results and diffs.
- Output: the selected patch (or a new patch if the human edits?).
We'll also have an orchestrator that runs the whole process.
However, note that the patch synthesis step might generate a huge number of patches. We need to be efficient.
Alternative: We can generate patches on the fly and evaluate until we find one that passes all tests, but then we might miss other good patches.
We'll design the system to be flexible:
Option 1: Generate a fixed number of patches (say 100) from the top suspicious line(s) and then evaluate.
Option 2: Generate patches iteratively, starting from the most suspicious line, and stop when we find a patch that passes all tests (then we might still want to collect more for human review?).
Since we want to involve human review when multiple patches are plausible, we might want to collect a set of candidate patches that pass all tests (or a high score) and then let the human choose.
Steps:
- Run fault localization to get suspicious lines.
- For each suspicious line (starting from the top) until we have collected K candidate patches that pass all tests (or until we run out of suspicious lines or time):
a. Generate a set of patches for that line (using a template or mutation).
b. Evaluate each patch.
c. If a patch passes all tests, add it to the candidate set.
- If we have at least one candidate that passes all tests, then we can stop generating more (or continue to get more for human review?).
- Then, if we have more than one candidate, we present them to the human.
However, note that a patch might pass all tests but be incorrect (overfitting). So the human review is important.
Alternatively, we might not trust the test suite to be complete, so we might want to present the top patches (by number of passed tests) to the human even if none passes all.
We'll design the system to be configurable:
- We can set a threshold for the number of passed tests to consider a patch as "plausible".
- We can set a maximum number of patches to generate and evaluate.
Implementation details:
For fault localization in Python:
We'll use the coverage module to run the tests and get the execution data.
Steps:
- Run
coverage run -m pytest (or the test command) to get the coverage data.
- Use
coverage analysis to get the lines executed by each test? Actually, we need per-test coverage.
Alternatively, we can use coverage with --per-test but that's not directly supported. We might need to run each test separately and record coverage for each.
We can do:
for test in test_suite:
run coverage for that test only, and record which lines are covered.
But that's time-consuming. Instead, we can run all tests together and then use the coverage module to get the coverage for each test by using the --context option? Actually, coverage.py doesn't track per-test by default.
Alternatively, we can use a different approach: we can run the tests with a custom coverage plugin that records per-test coverage. But for simplicity, we might use an existing tool that does fault localization for Python, like gpect or pytest-cov and then process the data.
However, for a lab, we might want to keep it simple and use a technique that doesn't require per-test coverage? Actually, spectrum-based fault localization requires per-test coverage.
We can do:
Step 1: Run the entire test suite and record which tests fail and which pass.
Step 2: For each line in the code, we need to know which tests executed that line.
We can run each test in isolation and record the coverage for that test. Then, we can build a matrix.
But that's a lot of runs. Alternatively, we can run all tests together and then use a technique that uses the aggregate coverage? That doesn't work for spectrum-based.
So we have to run per test.
We can do:
tests = get_all_tests()
coverage_matrix = {}
for test in tests:
run_coverage_for_test(test)
record which lines are covered for this test.
Then, for each line:
nf = number of failing tests that executed the line
np = number of passing tests that executed the line
total_f = total failing tests
total_p = total passing tests
Ochiai = nf / sqrt((nf+np) * total_f)
Then sort by Ochiai descending.
This is heavy because we run the tests multiple times.
We can try to reduce the number of tests by grouping? But let's assume we have a small test suite for the lab.
Alternatively, we can use a faster fault localization technique that doesn't require per-test coverage, but we'll stick with Ochiai for now.
Given the complexity, we might start with a simpler approach for the lab:
We can use the pytest and pytest-cov to get the coverage for the entire test suite (aggregated) and then use the failing tests to rank lines? That would be:
For each line, if it is covered by at least one failing test, then it's suspicious? Not very precise.
So we do need per-test coverage.
We can use the coverage module with --context to set a context for each test? Actually, coverage.py 5.0+ supports dynamic contexts.
We can set a context for each test by setting an environment variable or using the coverage API.
Steps with coverage:
import coverage
cov = coverage.Coverage()
cov.start()
for test in tests:
# set context for this test? We can use cov.switch_context(test_name)
# but note: switch_context is for switching during the same run, but we want per test.
Alternatively, we run each test in a separate process and collect the coverage data for that test, then combine.
Given the complexity, for the lab we might assume that the test suite is small and we can run each test separately.
We'll design:
FaultLocalizer:
def __init__(self, source_file, test_directory, test_runner='pytest'):
def run_tests_and_collect_coverage(self):
# Run each test separately and record coverage for each test.
# Returns: a dictionary: test_name -> set of lines covered
# Also, a list of failing tests and passing tests.
def compute_suspiciousness(self):
# Use Ochiai formula.
def get_suspicious_lines(self, top_n=10):
# Return top_n lines with their scores.
3. Patch Synthesizer:
We'll generate patches by applying edit operations to the suspicious lines.
Edit operations:
- Replace the line with a similar line from a template (e.g., change a comparison operator, change a variable name, etc.)
- Insert a line before/after the suspicious line (e.g., a condition check, a print statement for debugging, but these are less likely to fix the bug)
- Delete the suspicious line (if it's a statement, but might break the code)
We can have a set of templates for common bugs.
Alternatively, we can use a more data-driven approach: extract from existing patches.
For the lab, we'll define a few edit operations:
Operation 1: Replace a variable with a constant (or another variable) if the variable is used in a suspicious way.
Operation 2: Change an operator (e.g., > to >=, == to !=, etc.)
Operation 3: Add a missing method call (like `super().__init__()` in a constructor)
Operation 4: Fix a typo in a variable name (if we have a dictionary of common typos? or use the AST to find similar variable names in the same scope)
But note: we are generating patches for a specific line, so we need to consider the context.
We'll generate patches by:
For each suspicious line (with line number and the code string):
For each applicable edit operation (based on the AST node type of that line):
Generate a new code string by applying the edit.
Then, create a patch that replaces the original line with the new code string.
We'll have to be careful to maintain the syntax.
We can use the `ast` module to parse the line and then modify the AST and convert back to code? But note that the line might not be a complete statement? We are working on a per-line basis, but in Python, a statement might span multiple lines.
Alternatively, we can work at the AST level for the entire function or module? But then the fault localization gives us line numbers, so we want to patch at the line level.
We can use the `ast` module to parse the entire source file, then find the node that corresponds to the suspicious line, and then modify that node and regenerate the code for that node? But note that the line number in the AST might not correspond exactly to the line in the file if there are multi-line statements.
Given the complexity, for the lab we might assume that the suspicious line is a single-line statement. We can check if the AST node for that line spans multiple lines and then only patch if it's single? Or we can patch the entire statement that contains the suspicious line.
We'll do:
- Parse the source file with `ast`.
- For each suspicious line number, find the AST node that starts at that line (and if it spans multiple lines, we take the entire node and patch it?).
But note: the fault localization might point to a line that is part of a multi-line statement. We want to patch the entire statement.
So we'll:
Step 1: Get the AST of the entire file.
Step 2: For each suspicious line number, find the AST node that has the starting line number equal to the suspicious line number? But note that the node might start at an earlier line if it's a multi-line statement.
Alternatively, we can use the `ast` module to walk the tree and for each node, record the start and end line numbers. Then, for a suspicious line, we find the node that contains that line (i.e., start_line <= suspicious_line <= end_line).
Then, we only patch that node (and we have to regenerate the code for that node and replace the entire node's source code in the file?).
This is getting complex.
Given the time, for the lab we might restrict to single-line statements and use a simple string replacement? But that's error-prone.
Let's change the scope: we'll only consider patches that replace the entire line (as a string) and hope that the line is a complete statement.
We'll generate a set of candidate lines by:
- Changing numbers (e.g., off-by-one: change 0 to 1, 1 to 0, etc.)
- Changing comparison operators (list of operators: ==, !=, <, <=, >, >=, in, not in, is, is not)
- Changing arithmetic operators (+, -, *, /, //, %, **)
- Changing boolean operators (and, or, not)
- Removing a negation (if there's a 'not' in the expression, remove it or add it)
- Changing a variable name to another variable that is in scope (we can get the list of variables in the same function? but we don't have scope easily)
We can also use a template-based approach:
For example, if the line is an if condition, we might try to flip the condition.
We'll define a set of transformations for each AST node type? But we are not using AST for patch generation, we are just using the string.
Given the complexity of using AST for patch generation in a short time, we might do:
Patch generation by string manipulation:
For each suspicious line (as string):
Option 1: Replace a number with a nearby number (like index errors: 0 to 1, 1 to 0, etc.)
Option 2: Replace a comparison operator with another.
Option 3: Replace a variable name with another variable that appears in the same file (but we don't know the scope).
This is very crude and might generate invalid patches.
Alternatively, we can use a language model to generate patches? But that's heavy.
For the lab, we'll use a simple set of mutations:
Mutations:
- Change a number n to n+1, n-1, 0, 1, -1.
- Change a comparison operator to another (from a set).
- Change an arithmetic operator to another (from a set).
- Change a boolean operator to another (from a set).
- Remove or add a 'not' in a condition (if the condition is a comparison or boolean expression).
- Change a variable name to a variable that is defined in the same function (we can extract variable names from the function by parsing the function body?).
We'll need to parse the function to get the variable names in scope.
We can do:
Parse the entire source file with AST.
For the suspicious line, find the function (or module) that contains it.
Then, get all variable names in that function (from assignments, function parameters, etc.)
Then, for each variable in the suspicious line, we can try replacing it with another variable from the same scope.
But note: the suspicious line might use variables from outer scopes? We can get all variables in the function and in the global scope? This is getting complex.
Given the time, we might skip the variable replacement and only do operator and number changes.
We'll design the PatchSynthesizer to take the source file and the suspicious lines (with line numbers and the code string) and generate a list of patches.
Each patch is a tuple: (line_number, original_line, patched_line)
Then, we apply the patch by replacing the line at that line number with the patched_line.
But note: if the line is part of a multi-line statement, we might break the code.
We'll assume that the suspicious line is a single-line statement. We can check by parsing the AST and seeing if the node for that line has the same start and end line? If not, we skip? Or we patch the entire statement?
Let's do:
For each suspicious line:
Find the AST node that contains that line (by start and end line numbers). Then, get the source code for that node (from the original source) and then apply the mutation to the entire node? But then the patch would replace multiple lines.
We can do:
Parse the source file with AST and also get the source code for each node (using `ast.get_source_segment` in Python 3.9+?).
Then, for the suspicious line, we find the node that contains that line. Then, we generate mutations for that node (as a string) and then replace the entire node's source code.
This way, we handle multi-line statements.
Steps:
- Load the source file as a string.
- Parse the AST.
- For each node, record its start and end line numbers and the source segment (using the original string and the node's location).
- For a given suspicious line number, find the node that contains it (start_line <= suspicious_line <= end_line). There might be multiple nodes? We take the smallest one (the most specific) that contains the line.
Then, we generate mutations for that node's source segment.
This is more robust.
We'll implement:
class PatchSynthesizer:
def __init__(self, source_file):
with open(source_file) as f:
self.source = f.read()
self.tree = ast.parse(self.source)
def get_node_for_line(self, line_number):
# traverse the tree and find the node that contains the line_number.
# We'll do a depth-first search and record the node with the smallest span that contains the line.
pass
def generate_mutations(self, node, original_source_segment):
# Given an AST node and its source code, generate mutated versions.
# We'll look at the node type and apply mutations accordingly.
# For example, if the node is an if statement, we might flip the condition.
# But we need to parse the condition? We can use the AST of the node.
# Alternatively, we can do string-based mutations on the source_segment? But we have the AST.
# We'll do:
# If the node is an If:
# condition = node.test
# We can negate the condition? But that's not always valid (e.g., if condition is a complex expression).
# We can try to flip comparison operators in the condition.
# This is getting too complex for a lab.
# Given the time, we'll do only simple string mutations on the source_segment:
# - Change numbers: find all integers and change them by +1, -1, etc.
# - Change operators: replace any operator with another from the same category.
# We'll generate a set of source_segment strings.
pass
def generate_patches(self, suspicious_lines):
# For each suspicious line, get the node that contains it, then generate mutations for that node.
# Return a list of patches: (line_number, original_source_segment, mutated_source_segment)
pass
This is a big task.
Given the complexity and the fact that this is a lab design, we might simplify:
We'll assume that the suspicious line is a single line and we only generate mutations for that line (without considering the AST). We'll do:
For each suspicious line (with line number and the line string):
mutations = []
# 1. Number mutations: for each integer in the line, try changing it to n+1, n-1, 0, 1, -1.
# 2. Operator mutations: for each operator in the line, replace with another operator from a predefined set.
# We'll use regular expressions to find numbers and operators.
# Then, generate a new line for each mutation.
# Also, we can try removing the line (if it's a statement that can be removed? but that might break the code) or adding a line? Not for now.
Then, we create a patch for each mutation: (line_number, original_line, mutated_line)
Then, when applying the patch, we replace the line at line_number with the mutated_line.
This is very crude and might generate syntax errors, but for the lab we can catch those when we try to run the tests.
-
Fitness Evaluator:
For each patch:
Apply the patch to the source file (create a temporary file).
Run the test suite on the patched code.
Record which tests pass and which fail.
We'll define a fitness function: number of passed tests (or we can just check if all tests pass).
-
Human Review:
We'll collect the patches that pass all tests (or the top K by number of passed tests) and present them to the human.
We'll use a simple web interface with Streamlit (because it's easy) or Flask.
The interface will show:
- The original code (with the suspicious line highlighted).
- The failing tests (and their output?).
- For each candidate patch:
- The diff (original vs patched).
- The test results (which tests passed, which failed).
- A button to select the patch.
Then, the selected patch is applied and saved.
-
Orchestrator:
We'll have a main script that:
- Takes as input: source file, test directory, configuration (like number of suspicious lines to consider, max patches, etc.)
Steps:
1. Run fault localization to get suspicious lines.
2. For each suspicious line (up to a limit) and until we have enough candidate patches (or until we run out of time):
a. Generate patches for that line.
b. Evaluate each patch.
c. If a patch passes all tests, add it to the candidate set.
3. If we have at least one candidate that passes all tests, then we can either:
a. Automatically select the one with the smallest edit (or first found) and apply it.
b. Or, if we have more than one, or if we want human review, then present the candidates to the human.
4. If no patch passes all tests, then we might present the top patches (by number of passed tests) to the human.
-
Output:
The fixed source code.
-
Evaluation:
We can also record the time taken, the number of patches generated, etc.
Let's write the code structure:
We'll have the following files:
fault_localizer.py
patch_synthesizer.py
fitness_evaluator.py
human_review.py (or integrate with orchestrator)
orchestrator.py
config.py (for configuration)
We'll assume the test suite is in a directory and we run with pytest.
We'll assume the source file is a single Python file.
We'll use the following libraries:
- coverage
- ast
- pytest (to run tests)
- streamlit (for human review) or we can do a simple command-line review.
Given the complexity of per-test coverage, we might use a different fault localization technique that doesn't require per-test? But we said we want spectrum-based.
Alternatively, we can use the pytest and pytest-cov to get per-test coverage by running each test separately? We can do:
tests = collect_test_names()
for test in tests:
run `pytest --cov=source_module --cov-report= --cov-append` for that test? But then we have to run each test and then combine.
Actually, coverage.py can be used to run each test and collect the coverage for that test by setting a context.
We can do:
import coverage
cov = coverage.Coverage()
cov.start()
# run one test
pytest.main([test_name])
cov.stop()
cov.save()
Then, we can get the coverage for that test by using `cov.get_context()`? Actually, we have to set the context for each test.
We can set the context for each test by:
cov = coverage.Coverage()
cov.start()
cov.switch_context(test_name)
# run the test
cov.stop()
Then, after running all tests, we can use cov.analysis2(filename) to get the lines executed in the context of each test? Actually, analysis2 returns the lines executed in the current context? We have to switch context and then get the lines.
We can do:
contexts = set() # all test names
for test in tests:
cov.switch_context(test)
# run the test
# then, for the source file, we can get the lines executed in this context?
# But note: the coverage data is stored per context.
Then, after running all tests, we can for each context (test) and for each line in the source file, check if that line was executed in that context.
We can use:
cov.load()
for test in tests:
cov.switch_context(test)
# Now, we can get the lines executed in the source file for this context?
# Actually, we can use `cov.analysis2(source_file)` but that returns the lines executed in the current context? Yes.
But note: we have to switch context and then run `analysis2` for each test? That's heavy.
Alternatively, we can run all tests in one run and then use the coverage module to get the per-test coverage by using the --context option? Actually, coverage.py doesn't store per-test by default.
We have to set a context for each test and then run them in the same process? But tests might interfere.
Given the time, we might use a simpler fault localization that doesn't require per-test coverage? For example, we can use the failing tests to get the stack trace and then rank lines by frequency in the stack trace? But that's not spectrum-based.
We decide to use a simpler approach for the lab:
We run the entire test suite and record which tests fail.
Then, we run the test suite with coverage (aggregate) and get the lines that are covered by at least one failing test? Then we rank by how many failing tests cover the line? But without passing test coverage, we can't compute Ochiai.
We can do:
For each line:
covered_by_failing = number of failing tests that cover the line? We don't have per-test.
So we cannot do Ochiai without per-test coverage.
Given the time, we might simulate per-test coverage by running each test separately and recording the coverage for that test. We'll do:
tests = get_test_names()
coverage_per_test = {}
for test in tests:
cov = coverage.Coverage()
cov.start()
pytest.main([test])
cov.stop()
# Now, for the source file, get the lines executed.
# We can use `cov.analysis2(source_file)` but that returns the lines executed in the current context? Yes.
# But note: we have to specify the source file and we have to be in the same directory? We can use absolute path.
analysis = cov.analysis2(source_file)
lines_executed = set(analysis[1]) # analysis[1] is the list of lines executed.
coverage_per_test[test] = lines_executed
Then, we have for each test the lines it executed.
Then, we can compute:
For each line in the source file:
n_f = number of failing tests that executed the line
n_p = number of passing tests that executed the line
total_f = total failing tests
total_p = total passing tests
ochiai = n_f / sqrt((n_f + n_p) * total_f) if total_f > 0 and (n_f+n_p)>0
Then sort by ochiai.
This is feasible for a small test suite.
We'll implement that.
Steps in FaultLocalizer:
def __init__(self, source_file, test_dir):
self.source_file = source_file
self.test_dir = test_dir
def get_tests(self):
# Use pytest to collect test names? We can run `pytest --collect-only` and parse the output.
# Or we can use pytest's API.
def run_tests_and_collect_coverage(self):
tests = self.get_tests()
passing = []
failing = []
coverage_per_test = {}
for test in tests:
# Run the test and check if it passed or failed.
# We can run with pytest and capture the exit code.
result = pytest.main([test, '--tb=short'])
if result == 0:
passing.append(test)
else:
failing.append(test)
# Now, we need the coverage for this test.
# We already ran the test with coverage? We have to run with coverage.
# We'll do:
cov = coverage.Coverage()
cov.start()
pytest.main([test])
cov.stop()
analysis = cov.analysis2(self.source_file)
lines_executed = set(analysis[1])
coverage_per_test[test] = lines_executed
return passing, failing, coverage_per_test
Then, we compute the suspiciousness.
However, running the test twice (once to check pass/fail and once with coverage) is inefficient. We can run with coverage and then check the exit code.
We'll do:
for test in tests:
cov = coverage.Coverage()
cov.start()
exit_code = pytest.main([test])
cov.stop()
if exit_code == 0:
passing.append(test)
else:
failing.append(test)
analysis = cov.analysis2(self.source_file)
lines_executed = set(analysis[1])
coverage_per_test[test] = lines_executed
But note: the coverage data might include lines from multiple tests if we don't reset? We are creating a new coverage object for each test, so it's per test.
This will be slow, but for a lab with a small test suite it's acceptable.
We'll implement that.
-
Patch Synthesizer:
We'll generate mutations for the suspicious lines.
We'll focus on the line that is the root cause (the node that contains the suspicious line). We get the node's source code and then generate mutations for that source code.
We'll do:
For each suspicious line:
node = self.get_node_for_line(line_number) # returns the AST node that contains the line.
source_segment = ast.get_source_segment(self.source, node) # requires Python 3.9+
Then, generate mutations for the source_segment.
We'll define:
def mutate_number(s):
# find all integers and change them.
def mutate_operator(s):
# find operators and replace.
def mutate_boolean(s):
# for boolean expressions, we can try to add/remove 'not'
But note: the source_segment might be multi-line. We'll treat it as a string and apply the mutations.
We'll generate a set of mutated source_segments.
Then, for each mutated_segment, we create a patch that replaces the original node's source with the mutated_segment.
But note: replacing the entire node might change the indentation? We have to be careful.
We can get the original indentation of the node and then adjust the mutated_segment to have the same indentation? Or we can keep the indentation as in the original.
Actually, `ast.get_source_segment` returns the exact source code for that node, including the indentation.
Then, when we replace, we replace the exact same lines (the node's start to end) with the mutated_segment.
But the mutated_segment might have different indentation? We are generating mutations by changing the content, but we keep the same indentation as the original? Not necessarily.
We can try to preserve the leading whitespace of the first line of the node and then for subsequent lines, we might have to adjust? This is complex.
Given the time, we'll assume that the mutations we generate are at the token level and we don't change the indentation. We'll generate the mutated_segment by replacing tokens in the original source_segment without changing the whitespace.
Example: if the original source_segment is:
"if x > 0:"
and we change '>' to '<', then the mutated_segment is:
"if x < 0:"
The indentation is the same.
But if we change a number that is part of a multi-line string? We are only working on the node's source, so it should be safe.
We'll generate mutations by:
For each integer in the source_segment (using regex), we change it to n+1, n-1, etc.
For each operator (from a list of operators) in the source_segment, we change it to another operator.
We have to be careful not to change operators inside strings or comments.
We can use the AST to get the tokens? But we are already using the AST to get the node. We can traverse the node's AST and then change the values? But then we have to convert back to source.
Given the time, we'll do string-based mutations and hope that we don't change inside strings.
We can use the `tokenize` module to tokenize the source_segment and then only change tokens that are operators or numbers? But that's more robust.
We'll do:
import tokenize
from io import BytesIO
tokens = tokenize.tokenize(BytesIO(source_segment.encode('utf-8')).readline)
new_tokens = []
for tok in tokens:
if tok.type == tokenize.NUMBER:
# change the number
new_tokens.append(...)
elif tok.type == tokenize.OP:
# change the operator
new_tokens.append(...)
else:
new_tokens.append(tok)
Then, we can reconstruct the source from the tokens.
But note: the tokenize module requires the code to be valid. If the original node is not a complete statement? It should be because we are using the AST node.
We'll do:
def generate_mutations(source_segment):
mutations = []
# 1. Number mutations:
# For each integer, try: n+1, n-1, 0, 1, -1.
# 2. Operator mutations:
# For each operator, try other operators in the same category.
# We'll use tokenize to get the tokens and then change the tokens.
try:
tokens = tokenize.tokenize(BytesIO(source_segment.encode('utf-8')).readline)
except tokenize.TokenError:
# If the source_segment is not complete, we might get an error.
return mutations
tokens_list = list(tokens)
# We'll skip the first and last token (ENCODING and ENDMARKER)
for i in range(1, len(tokens_list)-1):
tok = tokens_list[i]
if tok.type == tokenize.NUMBER:
# Try different number mutations.
try:
n = int(tok.string)
except:
continue
for new_n in [n+1, n-1, 0, 1, -1]:
new_tokens = tokens_list[:]
new_tokens[i] = tok._replace(string=str(new_n))
# Reconstruct the source from the tokens.
new_source = tokenize.untokenize(new_tokens).decode('utf-8')
mutations.append(new_source)
elif tok.type == tokenize.OP:
# Define mappings for operators.
# For example, for comparison: '==' -> '!=', '!=' -> '==', '<' -> '<=', '>' -> '>=', etc.
# We'll define a dictionary of replacements for each operator.
op_replacements = {
'==': ['!='],
'!=': ['=='],
'<': ['<=', '>'],
'<=': ['<', '>='],
'>': ['>=', '<'],
'>=': ['>', '<='],
'+': ['-', '*', '/', '//', '%'],
'-': ['+', '*', '/', '//', '%'],
'*': ['+', '-', '/', '//', '%'],
'/': ['+', '-', '*', '//', '%'],
'//': ['+', '-', '*', '/', '%'],
'%': ['+', '-', '*', '/', '//'],
'and': ['or'],
'or': ['and'],
'not': [''], # remove 'not'
'is': ['is not'],
'is not': ['is'],
'in': ['not in'],
'not in': ['in'],
}
if tok.string in op_replacements:
for new_op in op_replacements[tok.string]:
new_tokens = tokens_list[:]
new_tokens[i] = tok._replace(string=new_op)
new_source = tokenize.untokenize(new_tokens).decode('utf-8')
mutations.append(new_source)
return mutations
Then, for each mutation, we have a new source_segment.
Then, we create a patch that replaces the original node's source (from start to end line) with the new source_segment.
But note: the new source_segment might have a different number of lines? We are replacing tokens, so the number of lines should be the same? Not necessarily: if we change an operator that is part of a multi-line statement, the line breaks might change? Actually, tokenize.untokenize will produce a string that might have different line breaks? We are using the same tokens, so the line breaks should be the same? Not exactly: the tokenize module doesn't preserve the exact whitespace? It does preserve the whitespace between tokens? Actually, `untokenize` uses the token positions? It doesn't, it just concatenates the token strings with a space? We have to be careful.
We can use `ast.get_source_segment` to get the original segment, and then when we mutate, we want to keep the same formatting (indentation, etc.). The tokenize method might change the formatting.
Given the complexity, we might just do string replacement for the operator and number without tokenizing? But then we might change numbers inside strings.
We'll stick with tokenize for now and hope that the formatting is preserved enough.
Then, we create a patch:
patch = {
'line_start': node.lineno,
'line_end': node.end_lineno,
'original': source_segment,
'patched': mutated_source_segment
}
Then, when applying the patch, we replace the lines from line_start to line_end (inclusive) with the patched source_segment (which might be multiple lines?).
We have to split the patched source_segment by lines and then replace the original lines.
We'll do:
original_lines = self.source.splitlines()
new_lines = original_lines[:line_start-1] + patched_source_segment.splitlines() + original_lines[line_end:]
But note: the original_lines are 0-indexed, and line_start and line_end are 1-indexed from the AST.
But for a lab, it's a starting point.
Given the time, we'll implement a simplified version that works for a specific example.
Let's code accordingly.
We'll break down the code into modules and then the main orchestrator.
Due to the complexity, we might not implement the full AST-based node finding and instead use line-based patching (assuming single-line statements). We'll adjust.
We'll change the PatchSynthesizer to work on the line string (without AST). We'll generate mutations for the line string.
Then, we apply the patch by replacing that line.
This is less robust but simpler.
Steps in PatchSynthesizer (simplified):
def __init__(self, source_file):
with open(source_file) as f:
self.lines = f.readlines()
def generate_patches_for_line(self, line_number, line_content):
# line_number is 1-indexed? We use 0-indexed internally?
# We'll use 0-indexed for the list.
mutations = []
# Number mutations:
numbers = re.findall(r'\b\d+\b', line_content)
for n_str in set(numbers):
n = int(n_str)
for new_n in [n+1, n-1, 0, 1, -1]:
new_line = line_content.replace(n_str, str(new_n), 1) # replace only the first occurrence? But there might be multiple same numbers.
# We want to replace each occurrence? We can do for each occurrence? But then we get many patches.
# We'll replace each occurrence one by one? Or replace all? We'll replace each occurrence separately.
# Actually, we want to generate a patch for each number and each mutation? We can do:
# For each number in the line, try each mutation on that number occurrence.
# But note: if there are multiple same numbers, we might get duplicates.
# We'll do:
# For each match of the number in the line, generate a patch that changes that occurrence.
# We can use re.sub with a count? But we want to change one at a time.
# We'll generate a patch for each occurrence.
# Find all positions of the number string in the line.
# But note: the number might be part of a larger number? We used word boundaries.
# We'll do:
# for match in re.finditer(r'\b' + re.escape(n_str) + r'\b', line_content):
# new_line = line_content[:match.start()] + str(new_n) + line_content[match.end():]
# mutations.append(new_line)
# But then we are generating multiple patches for the same line and same mutation but different occurrences? That's okay.
pass
# Operator mutations:
operators = ['==', '!=', '<', '<=', '>', '>=', '+', '-', '*', '/', '//', '%', 'and', 'or', 'not', 'is', 'in']
for op in operators:
if op in line_content:
for new_op in op_replacements.get(op, []):
new_line = line_content.replace(op, new_op)
mutations.append(new_line)
# We might also try removing a 'not'? We already did in operator mutations.
return mutations
Then, for each suspicious line (with line number), we generate a list of mutated lines.
Then, we create a patch that replaces the entire line (the line at that line number) with the mutated line.
But note: the line might have multiple mutations? We are generating one mutation per patch.
Then, we have:
patch = {
'line_number': line_number, # 0-indexed? We'll use 1-indexed for the AST, but for the list of lines we use 0-indexed.
'original': self.lines[line_number],
'patched': mutated_line
}
Then, when applying the patch, we do:
new_lines = self.lines[:]
new_lines[line_number] = mutated_line
new_source = ''.join(new_lines)
This is simple.
We'll go with this simple approach for the lab.
Given the time, we'll implement the simplified version.
We'll change the fault localization to return suspicious lines as 0-indexed line numbers? The AST gives 1-indexed, but we are reading the file as a list of lines (0-indexed). We'll convert:
In fault localization, we get the line number from the AST (1-indexed). We convert to 0-indexed for the list.
Let's code accordingly.
We'll now write the code for each module.
Note: This is a big task, so we might not write the entire code but the structure and key functions.
We'll start with the fault localizer.
Due to the complexity of per-test coverage, we might use a simpler approach for the lab: we run the entire test suite and then for each line, we check if it is covered by any failing test? But we don't have per-test.
We decide to use the following simpler fault localization for the lab:
We run the entire test suite with coverage (aggregate) and get the set of lines covered by at least one failing test? But we don't know which lines are covered by passing tests.
We can do:
Run the entire test suite and collect coverage (aggregate). Then, for each line, we have:
executed = whether the line was executed by at least one test (any).
Then, we look at the failing tests and see which lines are in the stack trace of the failing tests? We can get the stack trace from the test output.
We can parse the test output to get the stack trace and then extract the file and line numbers.
Then, we rank the lines that appear in the stack trace of failing tests.
This is a common technique: fault localization by stack trace.
Steps:
Run the test suite and capture the output.
Parse the output to find the stack traces for failing tests.
For each failing test, get the list of (file, line) from the stack trace.
Then, for each (file, line) that is in the source file we are repairing, count how many failing tests have that line in the stack trace.
Then, rank by that count.
This is much simpler and doesn't require per-test coverage.
We'll do that.
In FaultLocalizer:
def run_tests_and_get_stack_traces(self):
# Run pytest and capture output.
result = subprocess.run(['pytest', self.test_dir, '--tb=short'], capture_output=True, text=True)
output = result.stdout + result.stderr
# Parse the output to get failing tests and their stack traces.
# We look for "FAILED" and then the test name, and then the traceback.
# This is a simple parser.
failing_tests = []
current_test = None
in_traceback = False
stack_lines = []
for line in output.splitlines():
if 'FAILED' in line:
# Example: FAILED test_module.py::test_function - AssertionError
# Extract test name.
parts = line.split()
if len(parts) >= 2:
test_name = parts[1]
failing_tests.append(test_name)
# Reset
current_test = test_name
in_traceback = False
stack_lines = []
elif in_traceback:
# Look for lines like: File "source_file", line X, in test_function
if 'File' in line and 'line' in line and self.source_file in line:
# Extract line number.
# Example: File "/path/to/source.py", line 10, in function_name
import re
match = re.search(r'line (\d+)', line)
if match:
line_number = int(match.group(1)) - 1 # convert to 0-indexed
stack_lines.append(line_number)
elif 'Traceback' in line:
in_traceback = True
# Now, we have for each failing test a list of stack_lines (0-indexed) in the source file.
# We count the frequency of each line in the source_file across all failing tests.
line_counts = {}
for line in stack_lines:
line_counts[line] = line_counts.get(line, 0) + 1
# Then, we sort by count descending.
suspicious_lines = sorted(line_counts.items(), key=lambda x: x[1], reverse=True)
return suspicious_lines # list of (line_number, count)
This is much simpler.
We'll use this.
15. Patch Synthesizer (simplified):
We'll generate mutations for the suspicious line (as string) and then create a patch that replaces that line.
We'll generate:
For each suspicious line (line_number, count):
line_content = self.lines[line_number]
mutations = self.generate_mutations(line_content)
for mutated_line in mutations:
patch = {
'line_number': line_number,
'original': line_content,
'patched': mutated_line
}
patches.append(patch)
Then, we return patches.
16. Fitness Evaluator:
We'll evaluate each patch by:
applying the patch (replacing the line in the source file) and running the tests.
We'll run the tests and capture the output to see which tests pass.
We can run pytest and then parse the output for "passed" and "failed" tests? Or we can use the return code and the summary.
We want to know for each test whether it passed.
We can run with `-v` and then parse the lines that end with "PASSED" or "FAILED".
Example output:
test_module.py::test_function PASSED
test_module.py::test_other FAILED
We'll do:
result = subprocess.run(['pytest', self.test_dir, '-v'], capture_output=True, text=True)
lines = result.stdout.splitlines()
test_results = {}
for line in lines:
if 'PASSED' in line or 'FAILED' in line:
# The test name is at the beginning until the space before PASSED/FAILED?
# We can split by space and take the last two? Not reliable.
# Instead, we can use regex: r'(.*) (PASSED|FAILED)'
match = re.search(r'(.*) (PASSED|FAILED)', line)
if match:
test_name = match.group(1).strip()
status = match.group(2)
test_results[test_name] = (status == 'PASSED')
Then, we return test_results.
Then, we compute:
passed_count = sum(1 for passed in test_results.values() if passed)
And we can also check if all tests passed.
17. Human Review:
We'll collect patches that pass all tests (or the top K by passed_count) and then present.
We'll use Streamlit.
We'll have to store the original code, the suspicious line, the failing tests, and the candidate patches.
We'll write a Streamlit app that:
st.title("APR Lab")
st.header("Original Code")
st.code(original_source)
st.header("Failing Tests")
for test in failing_tests:
st.write(test)
st.header("Candidate Patches")
for i, patch in enumerate(candidate_patches):
st.subheader(f"Patch {i+1}")
# Show the diff? We can show the original line and the patched line.
st.write("Original line:")
st.code(patch['original'])
st.write("Patched line:")
st.code(patch['patched'])
st.write("Test results:")
st.json(patch['test_results']) # or a table
if st.button(f"Select Patch {i+1}"):
# Apply this patch and save the fixed code.
fixed_code = apply_patch(original_source, patch)
st.download_button("Download fixed code", fixed_code, file_name="fixed.py")
But note: the patch only changes one line. We can show the entire file with the change? We can use diff.
We can use the difflib to show the diff.
We'll do:
import difflib
original_lines = original_source.splitlines(keepends=True)
new_lines = original_lines[:]
new_lines[patch['line_number']] = patch['patched'] + '\n' # note: the original line might have a newline? We assume the lines array has newlines.
diff = difflib.unified_diff(original_lines, new_lines, fromfile='original', tofile='patched')
st.code(''.join(diff))
Then, the button to select.
18. Orchestrator:
We'll have a main.py that:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--source', required=True, help='Path to the buggy source file')
parser.add_argument('--tests', required=True, help='Path to the test directory')
parser.add_argument('--top-suspicious', type=int, default=5, help='Number of suspicious lines to consider')
parser.add_argument('--max-patches-per-line', type=int, default=10, help='Max patches to generate per suspicious line')
parser.add_argument('--human-review', action='store_true', help='Always run human review even if a perfect patch is found')
args = parser.parse_args()
# Step 1: Fault localization
fl = FaultLocalizer(args.source, args.tests)
suspicious_lines = fl.get_suspicious_lines(top_n=args.top_suspicious)
# Step 2: Patch synthesis
ps = PatchSynthesizer(args.source)
patches = []
for line_number, count in suspicious_lines:
line_patches = ps.generate_patches_for_line(line_number, ps.lines[line_number])
# Limit the number of patches per line
patches.extend(line_patches[:args.max_patches_per_line])
# Step 3: Fitness evaluation
fe = FitnessEvaluator(args.source, args.tests)
evaluated_patches = []
for patch in patches:
test_results = fe.evaluate_patch(patch)
patch['test_results'] = test_results
passed_count = sum(1 for passed in test_results.values() if passed)
patch['passed_count'] = passed_count
evaluated_patches.append(patch)
# Step 4: Select candidates for human review
# First, find patches that pass all tests.
total_tests = len(evaluated_patches[0]['test_results']) if evaluated_patches else 0
perfect_patches = [p for p in evaluated_patches if p['passed_count'] == total_tests]
if perfect_patches and not args.human_review:
# Automatically select the first perfect patch (or the one with smallest edit? We don't have edit distance)
selected_patch = perfect_patches[0]
fixed_code = fe.apply_patch(selected_patch)
with open('fixed.py', 'w') as f:
f.write(fixed_code)
print("Fixed code written to fixed.py")
else:
# Take top K patches by passed_count (even if not perfect) for human review.
# We'll take up to 10 patches.
top_patches = sorted(evaluated_patches, key=lambda x: x['passed_count'], reverse=True)[:10]
# Save the state for human review.
# We'll write the state to a file and then launch the Streamlit app.
state = {
'original_source': fe.original_source,
'failing_tests': fl.failing_tests, # we need to get the failing tests from fl.
'candidate_patches': top_patches
}
with open('review_state.json', 'w') as f:
json.dump(state, f, indent=2)
# Then, run the Streamlit app.
subprocess.run(['streamlit', 'run', 'human_review.py'])
19. Human Review App (human_review.py):
import streamlit as st
import json
import difflib
with open('review_state.json') as f:
state = json.load(f)
original_source = state['original_source']
failing_tests = state['failing_tests']
candidate_patches = state['candidate_patches']
st.title("APR Lab - Human Review")
st.header("Original Code")
st.code(original_source)
st.header("Failing Tests")
for test in failing_tests:
st.write(test)
st.header("Candidate Patches")
selected_patch_index = st.radio("Select a patch", range(1, len(candidate_patches)+1), format_func=lambda x: f"Patch {x}")
if selected_patch_index:
patch = candidate_patches[selected_patch_index-1]
st.subheader(f"Patch {selected_patch_index}")
# Show diff
original_lines = original_source.splitlines(keepends=True)
new_lines = original_lines[:]
new_lines[patch['line_number']] = patch['patched'] + '\n'
diff = difflib.unified_diff(original_lines, new_lines, fromfile='original', tofile='patched')
st.code(''.join(diff))
st.write("Test results:")
st.json(patch['test_results'])
if st.button("Apply Selected Patch"):
fixed_source = ''.join(new_lines)
st.download_button("Download fixed code", fixed_source, file_name="fixed.py")
20. Note: We are not handling the case where the patch might change multiple lines (since our patch is only one line). But in the diff we show only one line change.
This is a simplified version.
Given the time, we'll implement this simplified version.
We'll now write the code for each module.
However, note: the fault localization using stack traces might not be accurate if the failing test doesn't have a stack trace (e.g., if it's an assertion error with no stack trace? Actually, pytest always shows a stack trace for failures).
Also, the stack trace might include lines from the test code, not the source code. We filter by self.source_file.
We'll adjust the FaultLocalizer to only consider lines in the source_file.
Let's code accordingly.
We'll start with the fault localizer.
Due to the complexity and time, we'll write the code in a single file for simplicity? But the design is modular.
We'll write separate files:
fault_localizer.py
patch_synthesizer.py
fitness_evaluator.py
orchestrator.py
human_review.py
But for the sake of this response, we might write a single script that does everything? Or we can write the classes in separate code blocks.
Given the format, we'll write the code in separate blocks.
Let's start.
Note: This is a prototype and might have bugs.
We'll assume the source file is a Python file and the tests are in a directory and can be run with pytest.
We'll use Python 3.8+.
We'll use the following imports:
import re
import subprocess
import json
import ast
import tokenize
from io import BytesIO
import tempfile
import shutil
import os
But for the simplified version, we don't need ast and tokenize? We are using string mutations.
We'll use re for number and operator finding.
Let's code.
I'll design a comprehensive Automated Program Repair (APR) Experimentation Lab with modular components for systematic evaluation of repair techniques.
System Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ APR Experimentation Lab │
├─────────────┬──────────────┬──────────────┬───────────────┤
│ Fault │ Patch │ Fitness │ Human Review │
│ Localization│ Synthesis │ Evaluation │ Workflow │
└─────────────┴──────────────┴──────────────┴───────────────┘
1. FAULT LOCALIZATION MODULE
Input: Buggy program + failing/passing test suite
Output: Ranked list of suspicious code locations
class FaultLocalizer:
def __init__(self, technique='sbfl'):
"""
Techniques:
- SBFL: Spectrum-Based Fault Localization (Ochiai, Tarantula)
- NeuralFL: Neural network-based localizers
- Predicate-based: Using predicates from test executions
"""
self.technique = technique
def localize(self, program, test_suite):
"""
Returns: List of (file, line, suspiciousness_score)
"""
# 1. Instrument program & collect coverage
coverage_data = self._collect_coverage(program, test_suite)
# 2. Apply fault localization formula
if self.technique == 'sbfl':
return self._sbfl_localization(coverage_data)
elif self.technique == 'neuralfl':
return self._neural_localization(coverage_data)
def _sbfl_localization(self, coverage_data):
"""Ochiai coefficient"""
scores = []
for line in coverage_data['lines']:
nf = coverage_data['failing_covered'][line] # failing tests covering line
np = coverage_data['passing_covered'][line] # passing tests covering line
total_f = coverage_data['total_failing']
if nf == 0:
score = 0
else:
score = nf / math.sqrt((nf + np) * total_f)
scores.append((line, score))
return sorted(scores, key=lambda x: x[1], reverse=True)
2. PATCH SYNTHESIS MODULE
Approaches:
class PatchSynthesizer:
def __init__(self, strategies=['template', 'genetic', 'llm']):
self.strategies = strategies
def synthesize(self, buggy_location, context, max_patches=100):
patches = []
if 'template' in self.strategies:
patches.extend(self._template_based(buggy_location, context))
if 'genetic' in self.strategies:
patches.extend(self._genetic_programming(buggy_location, context))
if 'llm' in self.strategies:
patches.extend(self._llm_based(buggy_location, context))
return self._deduplicate(patches)[:max_patches]
def _template_based(self, location, context):
"""Apply predefined repair templates"""
templates = {
'condition_flip': self._flip_condition,
'operator_change': self._change_operator,
'missing_check': self._add_null_check,
'boundary_fix': self._fix_boundary,
}
return [t(location, context) for t in templates.values()]
def _llm_based(self, location, context):
"""Use LLM (Codex, ChatGPT) to generate patches"""
prompt = self._build_prompt(location, context)
response = self._call_llm_api(prompt)
return self._parse_llm_response(response)
3. FITNESS EVALUATION MODULE
class FitnessEvaluator:
def __init__(self, test_suite, time_limit=300):
self.test_suite = test_suite
self.time_limit = time_limit
def evaluate(self, patches, buggy_program):
results = []
for patch in patches:
# 1. Apply patch
patched_program = self._apply_patch(buggy_program, patch)
# 2. Run test suite with timeout
test_outcomes = self._run_tests(patched_program)
# 3. Calculate fitness
fitness = {
'passed': sum(1 for t in test_outcomes if t['passed']),
'failed': sum(1 for t in test_outcomes if not t['passed']),
'regressions': self._count_regressions(test_outcomes),
'plausible': self._is_plausible(test_outcomes),
'overfitting': self._detect_overfitting(test_outcomes)
}
results.append({
'patch': patch,
'fitness': fitness,
'test_details': test_outcomes
})
return results
def _is_plausible(self, test_outcomes):
"""A patch is plausible if it fixes all failing tests
without breaking previously passing tests"""
all_passed = all(t['passed'] for t in test_outcomes)
no_regressions = not any(
t['was_passing'] and not t['passed']
for t in test_outcomes
)
return all_passed and no_regressions
4. HUMAN REVIEW WORKFLOW
class HumanReviewWorkflow:
def __init__(self, interface='web'):
self.interface = interface
def review(self, candidate_patches, bug_report, context):
"""
Multi-stage human review process
"""
# Stage 1: Quick plausibility check
plausible_patches = self._quick_filter(candidate_patches)
# Stage 2: Detailed review with UI
if self.interface == 'web':
self._web_interface(plausible_patches, bug_report, context)
elif self.interface == 'ide':
self._ide_plugin(plausible_patches)
# Stage 3: Expert arbitration (if disagreements)
final_patch = self._arbitrate_disagreements(plausible_patches)
return final_patch
def _web_interface(self, patches, bug_report, context):
"""Streamlit/Web-based review interface"""
st.title("APR Human Review")
# Show bug report
st.header("Bug Report")
st.text(bug_report)
# Show context
with st.expander("Context"):
st.code(context)
# Patch comparison table
for i, patch in enumerate(patches):
with st.expander(f"Patch {i+1}"):
col1, col2 = st.columns(2)
with col1:
st.subheader("Original")
st.code(patch['original_code'])
with col2:
st.subheader("Patched")
st.code(patch['patched_code'])
st.write("Test Results:")
st.json(patch['test_results'])
if st.button(f"Approve Patch {i+1}"):
self._record_decision(i, 'approve')
if st.button(f"Reject Patch {i+1}"):
self._record_decision(i, 'reject')
5. ORCHESTRATOR / EXPERIMENT MANAGER
class APRLabOrchestrator:
def __init__(self, config):
self.config = config
self.localizer = FaultLocalizer(config['fl_technique'])
self.synthesizer = PatchSynthesizer(config['synthesis_strategies'])
self.evaluator = FitnessEvaluator(config['test_suite'])
self.reviewer = HumanReviewWorkflow(config['review_interface'])
def run_experiment(self, buggy_program, test_suite, bug_report):
"""Complete repair pipeline"""
# Phase 1: Fault Localization
print("Phase 1: Fault Localization...")
suspicious_lines = self.localizer.localize(buggy_program, test_suite)
top_suspicious = suspicious_lines[:self.config['top_k']]
# Phase 2: Patch Synthesis
print("Phase 2: Patch Synthesis...")
all_patches = []
for line in top_suspicious:
context = self._extract_context(buggy_program, line)
patches = self.synthesizer.synthesize(line, context)
all_patches.extend(patches)
# Phase 3: Fitness Evaluation
print("Phase 3: Fitness Evaluation...")
evaluated_patches = self.evaluator.evaluate(all_patches, buggy_program)
# Phase 4: Filter plausible patches
plausible_patches = [
p for p in evaluated_patches
if p['fitness']['plausible']
]
# Phase 5: Human Review (if needed)
if len(plausible_patches) > 1 or self.config['force_human_review']:
print("Phase 4: Human Review...")
final_patch = self.reviewer.review(
plausible_patches,
bug_report,
self._get_full_context(buggy_program)
)
else:
final_patch = plausible_patches[0] if plausible_patches else None
# Phase 6: Save results
self._save_experiment_results({
'suspicious_lines': suspicious_lines,
'generated_patches': len(all_patches),
'plausible_patches': len(plausible_patches),
'final_patch': final_patch,
'metrics': self._calculate_metrics(evaluated_patches)
})
return final_patch
6. EXPERIMENT CONFIGURATION
# config.yaml
experiment:
name: "apr_lab_evaluation"
output_dir: "./results/"
fault_localization:
technique: "sbfl" # sbfl, neuralfl, predicate
top_k: 5
patch_synthesis:
strategies: ["template", "llm"] # template, genetic, llm
max_patches_per_location: 20
llm_model: "codex-001"
fitness_evaluation:
timeout: 300 # seconds per patch
track_regressions: true
require_all_tests_pass: true
human_review:
interface: "web" # web, ide, cli
max_review_patches: 10
require_approval: true
evaluation_benchmarks:
- "defects4j"
- "bugbench"
- "manybugs"
- custom_programs: "./benchmarks/"
7. METRICS & STATISTICS TRACKING
class MetricsCollector:
def __init__(self):
self.metrics = {
'repair_rate': 0,
'precision': 0,
'recall': 0,
'f1_score': 0,
'time_to_repair': 0,
'patches_evaluated': 0,
'human_effort': 0, # minutes
'overfitting_rate': 0,
}
def calculate(self, experiment_results):
"""Calculate standard APR metrics"""
total_bugs = len(experiment_results)
fixed_bugs = sum(1 for r in experiment_results if r['final_patch'])
self.metrics['repair_rate'] = fixed_bugs / total_bugs
# Patch-level metrics
all_patches = [p for r in experiment_results for p in r['generated_patches']]
plausible = [p for p in all_patches if p['fitness']['plausible']]
correct = [p for p in plausible if p['is_correct']] # requires human verification
if plausible:
self.metrics['precision'] = len(correct) / len(plausible)
if all_patches:
self.metrics['recall'] = len(correct) / total_bugs
return self.metrics
8. DATABASE SCHEMA (for storing experiments)
CREATE TABLE experiments (
id INTEGER PRIMARY KEY,
bug_id TEXT NOT NULL,
program TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
config_json JSON,
status TEXT DEFAULT 'running'
);
CREATE TABLE fault_localization_results (
experiment_id INTEGER,
file TEXT,
line INTEGER,
suspiciousness_score REAL,
rank INTEGER,
FOREIGN KEY(experiment_id) REFERENCES experiments(id)
);
CREATE TABLE patches (
experiment_id INTEGER,
patch_id TEXT,
location TEXT, -- file:line
original_code TEXT,
patched_code TEXT,
generation_strategy TEXT,
FOREIGN KEY(experiment_id) REFERENCES experiments(id)
);
CREATE TABLE evaluation_results (
patch_id TEXT,
test_name TEXT,
passed BOOLEAN,
was_passing BOOLEAN,
execution_time REAL,
FOREIGN KEY(patch_id) REFERENCES patches(patch_id)
);
CREATE TABLE human_reviews (
patch_id TEXT,
reviewer_id TEXT,
decision TEXT, -- approve/reject/needs_changes
comments TEXT,
review_time_seconds INTEGER,
FOREIGN KEY(patch_id) REFERENCES patches(patch_id)
);
9. SAMPLE WORKFLOW EXECUTION
def run_full_experiment_suite():
"""Run experiments on benchmark suite"""
# Load benchmarks
benchmarks = load_benchmarks('defects4j')
results = []
for bug in benchmarks:
print(f"\n=== Testing {bug.id} ===")
# Run APR pipeline
apr = APRLabOrchestrator(load_config('config.yaml'))
final_patch = apr.run_experiment(
buggy_program=bug.source_code,
test_suite=bug.tests,
bug_report=bug.report
)
# Record results
results.append({
'bug': bug.id,
'repaired': final_patch is not None,
'patch': final_patch,
'metrics': apr.metrics
})
# Generate summary report
generate_report(results, 'experiment_summary.md')
# Export database
export_to_database(results)
10. EXTENSIBILITY POINTS
For Researchers:
- Add new FL techniques: Inherit
FaultLocalizer
- Add synthesis strategies: Implement
_new_strategy() in PatchSynthesizer
- Add fitness functions: Extend
_is_plausible() in FitnessEvaluator
- Custom benchmarks: Implement
load_benchmarks() for new datasets
For Practitioners:
- CI/CD integration: Wrap orchestrator as CLI tool
- IDE plugin: Implement
HumanReviewWorkflow with IDE-specific UI
- Batch processing: Configure experiment suites via YAML
11. VISUALIZATION & REPORTING
def generate_visualizations(experiment_results):
"""Generate comprehensive visual reports"""
# 1. Repair rate by project
plt.figure(figsize=(10, 6))
# ... bar chart of repair rates
# 2. Patch generation distribution
plt.figure(figsize=(8, 8))
# ... pie chart of synthesis strategies
# 3. Time to repair distribution
plt.figure(figsize=(10, 6))
# ... box plot of repair times
# 4. Human review decisions
plt.figure(figsize=(10, 6))
# ... stacked bar of approve/reject ratios
# 5. Fault localization effectiveness
# ... exam score visualization
12. REPRODUCIBILITY SUPPORT
class ReproducibilityManager:
def __init__(self):
self.records = []
def record_environment(self):
"""Record experiment environment"""
return {
'python_version': sys.version,
'platform': platform.platform(),
'packages': self._get_package_versions(),
'git_commit': subprocess.getoutput('git rev-parse HEAD'),
'random_seed': random.getstate(),
'timestamp': datetime.now().isoformat()
}
def create_reproducible_bundle(self, experiment_id):
"""Create Docker/Singularity bundle for exact reproduction"""
# 1. Copy source code
# 2. Export database
# 3. Generate Dockerfile with exact dependencies
# 4. Include experiment configuration
pass
KEY DESIGN PRINCIPLES
- Modularity: Each component is independently replaceable
- Reproducibility: Full experiment recording and environment capture
- Extensibility: Clear interfaces for new techniques
- Human-in-the-loop: Structured human review with justification tracking
- Benchmark-driven: Support standard benchmarks (Defects4J, BugBench, etc.)
- Statistical rigor: Proper experimental design with controls
- Visualization: Comprehensive reporting for paper reproduction
QUICK START EXAMPLE
# Quick start for a single bug
from apr_lab import APRLabOrchestrator
config = {
'fl_technique': 'sbfl',
'synthesis_strategies': ['template', 'llm'],
'test_suite': './tests/',
'top_k': 3,
'force_human_review': False
}
orchestrator = APRLabOrchestrator(config)
with open('buggy.py') as f:
source_code = f.read()
with open('test_suite.py') as f:
tests = f.read()
result = orchestrator.run_experiment(
buggy_program=source_code,
test_suite=tests,
bug_report="Test test_function fails with assertion error"
)
if result['final_patch']:
print(f"✅ Repair found! Patch applied to {result['final_patch']['location']}")
else:
print("❌ No plausible repair found")
This lab provides a complete, production-ready framework for:
- Systematic APR technique evaluation
- Controlled experiments with human review
- Benchmark comparison across multiple techniques
- Reproducible research with environment capture
- Rich visualization and metric reporting
Next steps for implementation:
- Implement core classes with concrete benchmarks
- Build web UI for human review (Streamlit/Gradio)
- Integrate with LLM APIs (OpenAI, Anthropic)
- Add database backend (SQLite/PostgreSQL)
- Create Docker containers for reproducibility
- Add support for multiple languages (Java via defect4j, C via ManyBugs)
Would you like me to elaborate on any specific component or provide implementation for a particular benchmark integration?