Using GenAI to Automatically Fix Java Resource Leaks

uber · Tech · 2024 · source Agentic: no · promotional bias: low · source-backed · extracted with prompt 0.5.6 (schema v2)

Generated from extraction.json — do not edit by hand. Every claim cites verbatim source evidence; stated means the quote directly asserts the claim, implied means it supports it indirectly.

Problem

Domain: Automated Java code repair

Uber needed to reduce manual effort fixing Java resource leaks detected by static analysis while avoiding unsafe automated changes that could introduce use-after-close or regression bugs.

Constraints:

Architecture

FixrLeak combines deterministic static analysis with GPT-4O code generation. SonarQube identifies Java resource leaks, Tree-sitter extracts the relevant function, AST checks filter out unsafe inter-procedural lifetimes, GPT-4O receives a scoped prompt for eligible intra-function leaks, the returned function replacement is applied, and automated build/test/SonarQube checks gate pull-request generation for human review.

Diagram confidence: explicit (topology described by the source).

flowchart LR
  sonarqube-leak-detector["SonarQube leak detector"] --> leak-tracking-layer["Leak tracking layer"]
  leak-tracking-layer --> tree-sitter-parser["Tree-sitter parser"]
  sonarqube-leak-detector --> ast-eligibility-filter["AST eligibility filter"]
  tree-sitter-parser --> ast-eligibility-filter
  ast-eligibility-filter --> gpt-4o-repair-generator["GPT-4O repair generator"]
  gpt-4o-repair-generator --> patch-application-layer["Patch application layer"]
  patch-application-layer --> validation-pipeline["Validation pipeline"]
  validation-pipeline --> pull-request-generator["Pull request generator"]
Drag to pan · scroll or use +/− to zoom · reconstructed from the source's described component topology

Components

Component Role Interacts with
SonarQube leak detector Identifies Java resource leaks and reports locations. Leak tracking layer, AST eligibility filter
Leak tracking layer Tracks leaks and fixes across codebase changes with deterministic hashes. SonarQube leak detector, Tree-sitter parser
Tree-sitter parser Parses Java code and extracts functions for analysis and replacement. Leak tracking layer, AST eligibility filter
AST eligibility filter Filters out leaks whose resource lifetimes are unsafe for automatic repair. SonarQube leak detector, Tree-sitter parser, GPT-4O repair generator
GPT-4O repair generator Produces try-with-resources-style code repairs for scoped eligible functions. AST eligibility filter, Patch application layer
Patch application layer Applies the generated fixed function to the codebase. GPT-4O repair generator, Validation pipeline
Validation pipeline Runs build, tests, and optional SonarQube recheck before opening review. Patch application layer, Pull request generator
Pull request generator Creates developer-reviewable pull requests for validated fixes. Validation pipeline

Data flow

SonarQube reports a resource leak with file and line metadata. FixrLeak tracks it with a deterministic hash, uses Tree-sitter to parse and extract the function, runs AST-level eligibility checks, prompts GPT-4O with the localized leak context, replaces the leaky function with the suggested fix, runs build/tests and optional SonarQube recheck, then opens a pull request for developer review.

3 supporting quotes
“The system begins by scanning resource leaks reported by SonarQube, an established static analysis tool.”summary, stated
“FixrLeak uses the Tree-sitter library to parse the code and extract the relevant function for analysis.”summary, stated
“Before submitting a pull request, FixrLeak runs multiple validation checks:”summary, stated

Why this architecture

Uber constrained the LLM to a narrow, AST-vetted repair task instead of asking it to detect and reason about every resource-leak pattern. Deterministic tools find and bound the problem, while GPT-4O handles localized patch synthesis and the build/test/review pipeline catches regressions.

3 supporting quotes
“Rather than attempting to solve all code quality issues with AI, Uber focused on a specific class of problems where generative AI could be highly effective”summary, stated
“not all problems should be handed to the AI.”summary, stated
“This multi-layer validation pipeline is essential for production LLM deployments.”summary, stated

Models used: OpenAI GPT-4O · SonarQube · Tree-sitter

Scale

Alternatives considered (roads not taken)

Use AI for leak detection as well as fixing

Rejected because: Uber used SonarQube for deterministic detection and left GenAI leak detection as future work.

“rather than relying on AI for leak detection (which would introduce additional uncertainty), FixrLeak leverages a trusted, deterministic tool for this phase.”summary, stated

Let the LLM fix all reported leaks

Rejected because: AST checks filtered cases where resource lifetime escaped the function scope.

“The system specifically filters out cases where:”summary, stated
“These scenarios typically involve resources that outlive the function's scope, where blindly applying try-with-resources could introduce use-after-close errors.”summary, stated

Use template-only repair

Rejected because: FixrLeak used a template-free LLM approach while keeping deterministic filters and validation.

“FixrLeak's improvement comes from its "template-free approach" that leverages modern LLMs' code generation capabilities”summary, stated

Patterns

tool-use-orchestration (code repair)

FixrLeak orchestrates SonarQube, Tree-sitter AST analysis, GPT-4O code generation, build/tests, and pull request creation.

“FixrLeak employs a multi-stage pipeline that carefully orchestrates traditional static analysis with LLM-based code generation.”summary, stated

safety-policy-enforcement (guardrails)

AST filters prevent GPT-4O from applying try-with-resources when resource lifetimes escape the function.

“A critical aspect of FixrLeak's design is its use of AST-level analysis to determine which leaks are safe to fix automatically. This represents an important lesson in responsible LLM deployment: not all problems should be handed to the AI. The system specifically filters out cases where:”summary, stated
“By focusing only on intra-function leaks where the resource's lifetime is confined to the allocating function, FixrLeak achieves higher accuracy”summary, stated

eval-driven-development (validation)

Generated fixes are gated by build, test, optional SonarQube recheck, and human code review before acceptance.

3 supporting quotes
“• Verification that the target binary builds successfully”summary, stated
“• Execution of all existing tests to confirm no regressions”summary, stated
“Finally, pull requests are generated for developer review. The text notes that "usually, all they need to do is one-click accept," suggesting high confidence in the fixes, though human oversight remains part of the workflow.”summary, stated

structured-output-contract (patching)

The LLM is prompted with a localized function and expected to return a replacement fix that can be extracted and validated.

“For leaks that pass the AST-level safety checks, FixrLeak crafts tailored prompts for OpenAI's GPT-4O model.”summary, stated
“The LLM response is processed to extract the suggested fix, which replaces the original leaky function. However, the system doesn't blindly trust the AI output. Before submitting a pull request, FixrLeak runs multiple validation checks:”summary, stated

Tradeoffs

Deterministic detection plus LLM repair

Chose Use SonarQube and AST analysis before GPT-4O generation over Use the LLM for both detection and repair.

Rationale: Trusted deterministic detection and eligibility checks reduced uncertainty before code generation.

“This hybrid approach is notable because it recognizes the limitations of both traditional tools and pure LLM solutions, combining them strategically.”summary, stated

Narrow resource-leak scope

Chose Automate intra-function resource leaks first over Attempt all Java resource-management bugs.

Rationale: Constrained scope produced higher accuracy and avoided unsafe lifetime assumptions.

“Automate targeted fixes: Focus on well-scoped, high-confidence fixes first to maximize success rates. This is essentially a guidance to "start narrow and expand" rather than attempting to solve all cases at once.”summary, stated

Pull-request review remains in the loop

Chose Generate PRs after validation over Automatically merge generated fixes.

Rationale: Human review preserved code-quality control for subtle resource-management changes.

“Finally, pull requests are generated for developer review. The text notes that "usually, all they need to do is one-click accept," suggesting high confidence in the fixes, though human oversight remains part of the workflow.”summary, stated

Gotchas (what bit them)

Blind try-with-resources fixes can introduce use-after-close bugs.

Root cause: Some resources are returned, passed as parameters, or stored in fields and therefore outlive the allocating function.

Resolution: AST-level analysis filters out escaping resource lifetimes before prompting GPT-4O.

3 supporting quotes
“• Resources are passed as parameters to the function”summary, stated
“• Resources are returned from the function”summary, stated
“• Resources are stored in class fields”summary, stated

High success depends on careful scoping.

Root cause: The hardest deprecated, inter-procedural, and failed eligible cases are excluded or remain unsolved.

Resolution: Uber started with well-scoped intra-function leaks and treats broader repair as future work.

“The true complexity lies in the remaining cases—inter-procedural leaks, deprecated code, and the 9 failures even among eligible cases.”summary, stated

AI-generated code still needs rigorous validation and review.

Root cause: LLM outputs can contain subtle errors even when they appear plausible.

Resolution: FixrLeak runs build/tests, optional static-analysis rechecks, and pull-request review.

“It acknowledges that LLM outputs, while often correct, can occasionally contain subtle errors or break assumptions elsewhere in the codebase.”summary, stated
“Integrate AI responsibly: Validate AI-generated code with rigorous testing and code review processes. Human oversight remains important even with high-accuracy systems.”summary, stated

Evaluation

Uber measured FixrLeak through SonarQube leak counts, AST eligibility filtering, successful automated fixes, build/test validation, optional SonarQube rechecks, and developer review.

Metrics: 124 leaks identified · 102 eligible cases · 93 successful automated fixes · 91% success on eligible cases · 75% of non-deprecated leaks fixed automatically

3 supporting quotes
“The case study provides concrete metrics on FixrLeak's performance at Uber:”summary, stated
“This represents approximately 91% success rate on eligible cases, and 75% of all non-deprecated leaks being fixed automatically.”summary, stated
“• Optional recheck with SonarQube to confirm the resource leak has been resolved”summary, stated

Outcomes

The evaluated deployment began with 124 SonarQube-detected Java resource leaks, filtered to 102 eligible cases, and fixed 93 automatically.

“The system is deployed as a continuous process that "runs periodically on the Java codebase and will quickly generate fixes for resource leaks introduced in the future,"”summary, stated
“Overall, FixrLeak represents a mature, pragmatic application of LLMs to a well-defined software engineering problem”summary, stated