Software Engineering Agents: Unlocking the Potential of Supervised Fine-Tuning

    Supervised fine-tuning can help software engineering agents learn reliable, tool-driven problem-solving workflows rather than simply generate code. This article examines how to combine real and synthetic tasks, filter demonstration trajectories, apply step-level loss masking and curriculum learning, and allocate inference-time compute. It also explains how controlled evaluation and a traceable data-validation pipeline can distinguish genuine improvements from leakage, accidental success, or larger inference budgets.

    1. The Core Challenge: Learning to Complete Engineering Tasks

    The distinction between a software engineering agent and a conventional code-completion model is not how much code it can generate at once. It is whether the model can act continuously toward a real task: understand the issue, locate relevant modules, inspect call relationships, modify multiple files, run tests, and refine the changes based on feedback.

    These tasks typically have three characteristics.

    First, the available information is incomplete. An issue description may report only a symptom, while the cause lies in argument passing, state management, or an edge case. The model must gather missing context through search and tool interactions.

    Second, changes are interdependent. Updating an interface may require corresponding changes to its implementation, callers, and tests. A locally correct edit does not guarantee that the project still satisfies its broader constraints.

    Third, success requires validation in the execution environment. Whether code runs, fixes the target issue, or introduces regressions cannot be established from text alone. Tests and, where necessary, static checks are required.

    The training objective should therefore shift from “generate a plausible code snippet” to “learn an executable, verifiable problem-solving process.” Supervised fine-tuning (SFT) is valuable in this context because high-quality demonstrations teach the model which actions to take under specific observations and how to use feedback to advance the task.

    2. Why Establish an SFT Baseline First?

    Supervised fine-tuning typically updates model parameters by predicting target sequences from paired inputs and outputs. For software engineering agents, the target need not be limited to a final patch. It can include an interaction sequence:

    Task description → Inspect files → Locate the problem → Edit code → Run tests → Read results → Revise the patch.

    This approach offers a clear training objective, supports offline data review, and makes experiments easier to reproduce. For teams with limited training resources or an immature feedback infrastructure, it is a practical starting point.

    However, using SFT does not automatically make training inexpensive or effective. Long trajectories increase context-processing costs, while generating and validating expert demonstrations also requires resources. If the dataset contains answer leakage, invalid tool calls, or unreliable success labels, training may remain stable while the model learns the wrong behavior.

    A more defensible strategy is to establish a trustworthy engineering-behavior baseline with SFT, then decide whether more complex optimization methods are needed to address the remaining weaknesses. Results from one experiment should not be generalized to every model and task.

    3. Building a Mixed Dataset: Realism and Coverage

    Real Code Changes Capture Engineering Conditions

    Real code changes reflect a project’s naming conventions, module dependencies, test organization, and compatibility requirements. They are useful for building training tasks that resemble actual engineering workloads.

    A verifiable task instance should include at least:

    • A code snapshot from before the change.
    • A clear issue description or requirement.
    • A reproducible execution environment.
    • Validation criteria for determining whether the objective has been met.
    • A verified reference change.

    The reference change should support dataset construction and quality checks, not be exposed directly to the model solving the task. Otherwise, the model may exploit answer clues rather than learn to diagnose and repair the problem.

    Real changes also need filtering. Some commits combine feature work, formatting, and bug fixes, making success criteria difficult to define. Others depend on external services and cannot be reproduced reliably. Authentic provenance alone does not make a sample suitable for training.

    Synthetic Tasks Fill Coverage Gaps

    Synthetic data can start with working code and introduce defects with clear semantics, such as boundary-condition errors, missing exception handling, incorrect state-update ordering, or inconsistent interface contracts.

    The goal is not simply to produce more failures. Each problem must be plausible and verifiable:

    1. The original version passes the relevant checks.
    2. After defect injection, the target check fails consistently.
    3. Restoring the correct behavior makes the relevant checks pass again.
    4. Obvious markers or fixed templates do not make the defect trivial to identify.

    If synthetic problems all follow the same pattern, the model may learn to recognize a dataset template rather than understand program behavior. Diversity should cover defect types, the number of affected files, localization difficulty, and repair methods.

    Real tasks provide engineering complexity; synthetic tasks fill coverage gaps. Their mix should be guided by quality and target scenarios, not volume alone.

    4. Filtering Trajectories: Correct Processes Versus Accidental Success

    An expert trajectory records more than an answer. It captures what the model observed at each step, which tools it called, the results it received, and the actions it took next.

    At a minimum, filtering should address three categories of risk.

    Prevent Answer and History Leakage

    If the task environment allows access to later change history, hidden patches, or cached files containing the answer, passing the final tests does not establish that the trajectory is valid.

    The solving environment should restrict access to answer materials, and trajectory review should examine file-reading behavior. Training and evaluation splits also require more than text deduplication. Code similarity, task provenance, and chronology matter: different descriptions of the same underlying issue should not appear across the two sets.

    Separate Tool Failures from Model Errors

    Missing dependencies, execution timeouts, and permission failures do not necessarily indicate that the model lacks repair capability. By contrast, incorrect call arguments, edits in the wrong location, or ignored test feedback may reflect model behavior problems.

    These cases should be labeled separately. Otherwise, the model may learn pointless retries from infrastructure failures or treat invalid calls as normal operations.

    Use Partially Successful Trajectories Carefully

    An unfinished trajectory may still contain useful steps, such as locating the correct module, finding reproduction conditions, or identifying a critical constraint.

    However, a useful first half does not justify treating the entire failed trajectory as an expert demonstration. A safer approach is to review the learnable segments, define clear retention boundaries, and remove subsequent actions that depend on incorrect assumptions. When correctness is difficult to establish, defer use rather than assign a high-quality label based on fluent language alone.

    5. Improving Training: Clearer Learning Signals from Useful Steps

    Step-Level Loss Masking

    The learning value of a long trajectory is uneven. User inputs, tool responses, valid actions, and erroneous attempts should not all be treated as equivalent prediction targets.

    In autoregressive training, a mask can determine which positions contribute to the loss:

    L = −Σₜ mₜ · log Pθ(yₜ | x, y<ₜ) / Σₜ mₜ

    Here, mₜ indicates whether a position contributes to training. A sample’s loss is computed only when it contains at least one supervised position. Positions corresponding to behavior the model should not imitate can be excluded from the loss.

    This requires distinguishing retained context from supervision. An incorrect action may need to remain in the context so the model can understand a later correction, without becoming a positive example to imitate.

    Masks should not be generated simply by checking whether a tool reported an error. Running a test that fails may be the correct diagnostic action. Conversely, a successful tool response does not prove that the action served the task objective. Decisions about supervision should consider the action’s purpose, the validity of the call, and subsequent verification.

    Curriculum Learning

    Curriculum learning can introduce easier tasks first, then progressively add more complex interactions. For example, training can move from local, single-file repairs to coordinated multi-file changes, followed by tasks requiring repeated validation and strategy adjustments.

    Interaction count can be one difficulty signal, but it should not be the only one. A short trajectory may require complex semantic reasoning, while a long one may consist mostly of ineffective repetition.

    More reliable difficulty dimensions include the scope of changes, the span of dependencies, problem-localization difficulty, environment complexity, and the difficulty of interpreting feedback. Basic tasks should continue to appear during training to reduce the risk of losing foundational capabilities as more complex behaviors are introduced.

    The effectiveness of curriculum learning should be tested through controlled comparisons with fixed data volume and training budgets, not inferred merely from a declining training loss.

    6. Inference-Time Scaling: Spend Compute on the Actual Bottleneck

    After training, additional inference-time compute may improve task performance. Two common approaches are sequential and parallel scaling.

    Sequential Scaling: More Validation Opportunities Along One Path

    Sequential scaling gives an agent more interaction rounds. It is useful when a task has not yet completed the diagnosis, modification, and testing cycle.

    More rounds do not necessarily mean more progress. A model may repeat searches, repeatedly edit the same area, or even damage a correct result. Progress monitoring and stopping rules are therefore necessary.

    Useful progress signals include new reproduction conditions, a narrower failure scope, improved test results, and convergence of the patch. If several rounds produce no meaningful progress, consider stopping or switching the solution path rather than extending the trajectory indefinitely.

    Parallel Scaling: Explore Different Repair Strategies

    Parallel scaling generates multiple candidates for the same task. It is useful when several plausible hypotheses exist, but its value depends on candidate diversity, not just candidate count.

    If every candidate follows the same incorrect diagnosis, repeated generation is unlikely to help. Exploration can vary the problem hypothesis, search focus, or repair scope while keeping permissions and validation requirements consistent.

    One practical budget strategy is to first check whether a single path fails because it lacks enough interaction rounds, then decide whether to increase the sequential budget. When choosing among alternative approaches becomes the main bottleneck, evaluate the benefits of parallel exploration. This is a strategy to test experimentally, not a universal ordering.

    Candidate Selection: Prioritize Execution Evidence

    Candidate evaluation can produce either direct scores or written reviews with selection rationales. Scores simplify ranking; written reviews make the reasoning behind a choice more visible. Both can still be influenced by training bias or superficial features.

    Selection should prioritize target tests, regression tests, and engineering constraints, with model review used as supporting evidence. A complete explanation, a short patch, or a natural-looking change cannot replace execution evidence.

    Passing tests should not be the sole criterion either. With insufficient coverage, a candidate might achieve apparent success by deleting checks, weakening assertions, or hardcoding outputs. Review must establish whether the repair genuinely satisfies the requirement.

    7. Evaluation Design: Separate Training Gains from Inference Gains

    To identify the source of an improvement, hold the base model, task set, tool permissions, and inference budget fixed where applicable, and compare:

    • Standard SFT versus step-level masked training.
    • Randomly mixed training versus curriculum learning.
    • A single trajectory versus an increased interaction budget.
    • A single candidate versus multiple candidates with selection.
    • Different data sources and filtering rules.

    Beyond task-resolution rate, record average interaction rounds, execution time, tool-call failure rate, patch size, and regression failures. Training-cost accounting should include data generation, environment validation, model training, and failed runs that must be repeated—not just the resources consumed by one training run.

    Performance reports must also define their statistical conventions. An increase of several percentage points in resolution rate is different from a relative increase of the same percentage. Without a complete evaluation configuration, specific performance figures or claims of superiority should not be carried over to other settings.

    8. Implementation: Build a Traceable Data and Validation Loop

    A practical rollout can proceed in five steps.

    Step 1: Build a small, trustworthy task set.
    Prioritize reproducible environments, clear success criteria, and leakage prevention. Each sample should be explainable and traceable.

    Step 2: Collect and review interaction trajectories.
    Distinguish valid behavior, correctable mistakes, and environment failures, then establish consistent quality labels.

    Step 3: Train an SFT baseline.
    Under fixed evaluation conditions, introduce loss masking, curriculum learning, and data-mix adjustments one at a time. Avoid changing too many factors simultaneously.

    Step 4: Analyze failure categories.
    Separate failures into diagnosis errors, editing errors, insufficient validation, improper tool use, and other relevant categories. Add data targeted to those weaknesses.

    Step 5: Optimize the inference budget.
    Configure sequential interactions, parallel candidates, and selection mechanisms according to the failure distribution rather than expanding every task’s budget uniformly.

    Throughout the process, execute code in isolated environments, restrict unnecessary network and file access, handle sensitive information in source code appropriately, and record dataset versions, environment configurations, and evaluation results.

    Conclusion

    Unlocking the potential of supervised fine-tuning for software engineering agents is not primarily about accumulating more trajectories. It is about making demonstrations reliable: tasks must be reproducible, processes must be free of leakage, supervision must be selective, and results must be verifiable.

    Mixed datasets, trajectory filtering, step-level loss masking, curriculum learning, and inference-time scaling form a coherent technical approach. Their actual benefits still require controlled evaluation. For development teams, establishing a trustworthy data and validation loop before increasing training complexity or inference budgets offers more engineering value than pursuing unverified performance claims.