All researchPapers

Training AI to Write Safer Code Without Sacrificing Correctness

A training framework focuses on small code repairs to improve the security of AI-generated code while preserving or improving functional correctness.

Joe JurczykBy Joe Jurczyk

What they studied

AI coding tools can generate code that contains security vulnerabilities. The authors describe a difficult trade-off: approaches designed to make generated code more secure can also reduce its ability to work correctly. For builders, both qualities matter. Code needs to perform its intended task without introducing avoidable security risks.

The authors investigate whether security and correctness can be improved together. Their starting observation is that security patches and functional bug fixes in real software share a structural pattern: both often involve small, localized changes rather than complete rewrites.

They introduce HPO, short for Hunk-Constrained Direct Preference Optimization. It is a model-training framework that combines security hardening with functional correction. Its training objective gives different weights to code segments, directing learning toward the logic involved in repairs. It also includes an automated pipeline for generating training data.

What they found

In experiments covering multiple models and programming languages, HPO improved security while preserving or enhancing functional correctness. The authors report security improvements of up to 28 percentage points.

That figure is the largest reported improvement, not a claim that every tested model or language improved by that amount. The abstract does not identify the individual models, languages, benchmarks, or security measures, so it does not establish how much benefit a particular coding tool would receive.

Why it matters for builders

This research is relevant to the models behind AI coding assistants, rather than a prompting technique you can apply directly. Its practical promise is that training focused on localized repairs could help reduce the tension between safer code and working code.

For beginners choosing or evaluating AI coding tools, the useful takeaway is to look for evidence of both security and functional correctness. These results support improving those goals together, but they do not establish that generated code is vulnerability-free or ready for production without review.

Source: "Hunk-Constrained DPO: Segment-Level Optimization for Secure and Correct LLM Code Generation" (2026-09-15, ACM Transactions on Software Engineering and Methodology). This is our summary of the paper's abstract — read the original for full details.

There's more detail at the original source.

Open the source
Share this: Facebook X

Related reading

Newsletter

Weekly vibe-coding tips — coming soon

We're getting this ready. Leave your email and we'll let you know the moment it launches. No fluff, unsubscribe whenever.