Code Generation for Disk Analysis Tools: Development and API Stability Practices
This article explains how to use LLM-assisted code generation to build a disk usage analysis tool, covering requirement decomposition, scan and aggregation design, cleanup safeguards, and code review and testing. It also discusses resilience for cloud model APIs through timeouts, retries, streaming, task splitting, and caching, and outlines when local deployment may be more appropriate.
1. Background: Why Large Disks Fill Up Quietly
Disk usage usually grows gradually. Dependency caches, build artifacts, container images, virtual environments, log files, and download directories in a development environment each grow a little. Individually they may not look large, but together they can consume hundreds of GB or even several TB. Operating system graphical usage tools can show a rough distribution, but scenarios that require repeated filtering, rule-based selection, and cleanup list generation often still require manually combining multiple commands.
A small tool that can perform scanning, aggregation, sorting, reporting, and cleanup suggestions therefore has clear value. Its core requirements are straightforward: find the largest directories and files, explain where the usage comes from, and execute cleanup after user confirmation.
2. Decomposing Requirements in Natural Language
The efficiency of LLM-assisted programming depends heavily on how complete the requirement description is. A prompt such as “help me write a disk cleanup tool” usually produces only a generic template. A description that includes goals, inputs, outputs, and constraints is more likely to produce a runnable solution.
It is useful to organize the prompt around four dimensions:
- Goal: Which root directory should be analyzed, and which metrics should be reported, such as total size, top N large directories, and distribution by file extension.
- Inputs and boundaries: Whether to skip symbolic links, whether to cross file systems, and which paths to exclude.
- Output format: A terminal table, a JSON file, or a list for manual review.
- Safety constraints: Read-only by default, deletion requiring a second confirmation, and no access to critical system directories.
The fourth point is the easiest to overlook. If model-generated deletion logic lacks a confirmation step, a single mistaken operation can cause data loss. The prompt should explicitly state: “Only perform statistics by default; do not delete.”
3. Key Design Points
3.1 Scanning Strategy
Recursive traversal is the most direct approach, but several details need to be handled:
- Symbolic links may form loops and should be skipped, or recorded only once.
- Directories with insufficient permissions should have exceptions captured and added to an error list; they must not interrupt the entire scan.
- Traversing large directories can take a long time, so progress information can be emitted or results reported in batches.
3.2 Aggregation and Sorting
First accumulate size by directory, then take the top N items. During accumulation, avoid counting the same file more than once. Hard links require particular attention: the same inode should be counted only once.
3.3 Cleanup Suggestions
Cleanup should be divided into two steps: first generate a candidate list, then execute after manual confirmation. Candidate rules can include “caches not accessed for more than 180 days,” “files with duplicate content,” and “intermediate artifacts from completed builds.” The more specific the rules, the lower the risk of accidental deletion.
3.4 Illustrative Code
The following language-agnostic pseudocode shows the main logic for scanning and aggregation:
function scan(root, top_n):totals = empty map // path -> accumulated byteserrors = empty listvisited_inodes = empty set // prevent duplicate counting of hard linksfor entry in walk(root, follow_symlinks = false):try:if entry.inode in visited_inodes: continuevisited_inodes.add(entry.inode)size = entry.sizefor ancestor in entry.ancestors_within(root):totals[ancestor] += sizeexcept PermissionDenied as e:errors.append((entry.path, e))ranked = sort(totals by value, descending)return ranked[0:top_n], errors
The aggregation result and the error list are returned separately, so the caller can decide how to display them. This interface separation also makes testing easier: by creating files of known sizes in a temporary directory, you can verify whether the output matches expectations.
4. Reviewing and Validating Generated Code
Model-generated code should not be put into direct use. At minimum, the following three checks should be completed:
- Run it in an isolated directory and confirm that the statistics roughly match the results from built-in system tools.
- Read every deletion-related branch one by one and confirm that there is no path that bypasses the confirmation step.
- Normalize paths to prevent relative paths or special characters from causing deletion in another location.
Test cases should cover empty directories, read-only files, symbolic link loops, and paths containing spaces and non-ASCII characters. These boundary conditions are often the parts most easily missed in a model’s first output.
5. Latency and Stability of Cloud APIs
The performance of cloud LLM APIs fluctuates with load and time of day. Common issues include:
- Generation speed is noticeably lower than in earlier experiences, and throughput decreases.
- Connections are interrupted during long outputs.
- Queueing and waiting times become longer during peak periods.
These issues can be addressed from both the client side and the invocation approach.
5.1 Timeouts and Retries
Set a reasonable timeout for each request. After a failure, retry with exponential backoff and limit the maximum number of retries to avoid amplifying transient failures.
function call_with_retry(request, max_retries = 4):delay = 1 secondfor attempt in 1..max_retries:try:return send(request, timeout = 60 seconds)except TransientError:sleep(delay + random_jitter())delay = delay * 2raise Error("Request failed repeatedly; please try again later")
Random jitter prevents many clients from retrying at the same moment, thereby reducing pressure on the server.
5.2 Streaming Output and Task Splitting
Streaming output allows users to see partial results as early as possible. After an interruption, only the unfinished portion needs to be requested again. Larger requirements should be split into smaller steps such as design, implementation, and testing, so that the impact of a single failed request is reduced.
5.3 Caching and Reuse
The same prompt and context can have their results cached. For fixed scaffolding code or templates, saving them in a local version repository is more stable than regenerating them each time and easier to audit.
6. Local Deployment Considerations
Running models locally can avoid network fluctuations and data leaving the machine, but several factors should be evaluated together:
- Hardware: The model parameter scale determines VRAM or memory requirements. Quantization can reduce footprint, but it usually affects output quality to some extent.
- Benefits: Data does not leave the local machine, network jitter does not affect response speed, and long-term invocation costs are easier to predict.
- Costs: You need to maintain the inference service, update model versions, monitor resource usage, and bear the corresponding operational time cost.
- Performance: Single-machine throughput is usually lower than that of large-scale clusters, making it more suitable for interactive use by individuals or small teams.
A practical criterion is: when invocation frequency is low and requirements change quickly, cloud APIs are more cost-effective; when data is sensitive, invocations are frequent, and there are strict stability requirements, local or private deployment is more appropriate.
7. Conclusion
The value of a small tool such as a disk cleanup utility lies in turning repetitive manual judgment into an auditable process. LLMs can significantly shorten the distance from requirements to code, but the output still needs boundary testing and security review. API latency and stability issues can be mitigated through retries, task splitting, and caching. For long-term use, the cost of cloud invocation versus local deployment should be weighed according to data sensitivity, invocation frequency, and operational capability.
