Disk Space Analysis and Automated Cleanup with LLM-Generated Code
This article walks through building a disk space analysis and cleanup tool by describing the requirement to a code generation LLM in natural language. It covers how to break the requirement into verifiable capabilities, how to structure a prompt around role, goal, constraints, and output format, and which parts of the generated code need review before production use. It also lists safety guardrails for destructive operations, performance considerations for million-file scans, factors for local or private inference deployment, troubleshooting steps for cloud API latency and interruptions, and an acceptance checklist. The core takeaway is that the model acts as a fast implementer while engineering judgment stays with the developer.
1. The Problem: What Is Missing When the Disk Fills Up
On development machines, test machines, and edge nodes, the system disk getting consumed by logs, build artifacts, and cache files is a routine operational problem. The impact of a full disk cascades: services fail to start because they cannot write temporary files, databases stall because they cannot flush to disk, and container runtimes error out because image layers cannot be extracted. Tracing directory sizes layer by layer by hand is slow and makes accidental deletion likely.
The traditional approach chains together a handful of built-in system commands, for example tallying directory usage level by level, filtering large files by modification time, and aggregating size by extension. The drawbacks are a high cost of memorizing command parameters, poor output readability, and limited reusability. With a code generation LLM, a single natural-language description of the need produces an analysis and cleanup program with an interactive interface, which significantly compresses the time from “we found the problem” to “we have a tool.”
It is worth stressing that the model’s value lies in translating a requirement into runnable code quickly, not in replacing engineering judgment. Generated output must be reviewed and constrained before it is used in a real environment.
2. Breaking Down the Requirement: What a Usable Disk Tool Needs
Before writing the prompt, decompose the requirement into verifiable capability items. This substantially improves generation quality:
- Capacity overview: total, used, available, and utilization for the root partition and each mount point.
- Directory drill-down: first-level subdirectories under a given path sorted by size descending, with the ability to descend level by level.
- Large file location: filter files by a size threshold and a modification time range, and output full paths.
- Type aggregation: aggregate size by extension or directory pattern to identify cleanable categories such as logs, caches, and build artifacts.
- Cleanup actions: a two-phase preview (dry-run) and execute flow, with a second confirmation before deletion and an option to recycle or back up.
- Report output: structured text or tables that are easy to paste into tickets and postmortem notes.
Spelling out these capability items noticeably improves the structural completeness of the generated code.
3. Prompt Design: From One Sentence to an Executable Spec
A vague prompt usually yields only a toy script. A reusable pattern is “role + goal + constraints + output format”:
You are a senior systems operations engineer. Implement a cross-platform disk space analysis and cleanup command-line tool.Goal: locate the directories and files consuming space, and safely clean up reclaimable content.Constraints:1) Read-only by default; deletion must be explicitly enabled and confirmed twice;2) Support an exclusion whitelist so system and business-critical paths are never touched;3) Scans of large directories must support a depth limit and timeout interruption;4) Output sorted by size descending, with units normalized to MB/GB;5) Use only the language standard library, with no additional dependencies.Output: complete runnable code + usage examples + a known limitations section.
Three techniques matter here: putting safety constraints first makes the model prioritize them; specifying “standard library only” avoids dependency installation failures; and asking for “known limitations” makes later manual gap-filling easier.
4. Review Checklist for Generated Code
Generated code cannot go straight to production. Reviews should focus on the following:
- How deletion paths are constructed: whether user input is normalized and boundary-checked, and whether a path could be composed that resolves to the root or a parent directory.
- Symlink handling: whether traversal follows symlinks, which can cause duplicate counting across file systems and even deletion of the link target.
- Permissions and exceptions: whether unreadable directories are skipped safely and summarized rather than crashing the whole run.
- Resource usage: whether large directory scans read in chunks instead of loading the entire file list at once and spiking memory.
- Concurrency and interruption: whether the tool responds to interrupt signals so a partial run does not leave inconsistent state.
A typical validation snippet:
import osdef safe_target(root: str, target: str) -> str:root_abs = os.path.abspath(root)target_abs = os.path.abspath(target)if os.path.commonpath([root_abs, target_abs]) != root_abs:raise ValueError("Target path is outside the allowed scope")if target_abs == root_abs:raise ValueError("Cleaning the root path is forbidden")return target_abs
5. Safety Guardrails: The First Principle for Cleanup Tools
The risk profile of a cleanup tool is asymmetric: a wrong analysis only costs extra time, while a wrong deletion can cause unrecoverable loss. The following guardrails should therefore be fixed in place:
- Read-only by default, with cleanup capability enabled through an explicit parameter;
- Whitelist first, with system directories, data directories, and mount point roots excluded by default;
- Two-phase execution, first printing the deletion list and total size, then executing after confirmation;
- A retention window, with a time threshold for recently modified files so content still being written is not deleted;
- An audit trail, recording time, path, size, and result for traceability.
6. Performance and Usability Tuning
Once the scan scope reaches millions of files, the interactive experience depends on three things: limiting traversal depth and allowing interruption; emitting output incrementally instead of waiting for the full result set; and caching results to avoid repeated scans. For long-running use, scanning and cleanup can be split into two independent phases, where the former runs on a schedule and produces a report, and the latter is triggered after manual confirmation.
7. Local Deployment and Inference Efficiency
Deploying code generation capability locally or in a private environment is a practical requirement for many teams, driven mainly by keeping data within its own boundary, stable response latency, and avoiding interruptions from external service fluctuations. Evaluation can cover these dimensions:
- Model size and VRAM usage: parameter count determines the quantization strategy and concurrency capacity;
- Throughput and time to first token: interactive coding scenarios are more sensitive to first-token latency;
- Context length: whether a complete file plus dependency notes fit;
- Deployment form: containerized deployment eases elastic scaling and version rollback;
- Observability: call volume, failure rate, and latency distribution need to feed into logging services and monitoring and alerting systems.
For cloud deployment, inference services can run on a container platform, models and artifacts can be stored in object storage, a message queue can smooth out traffic spikes, and monitoring and alerting can enable self-healing, forming a complete loop.
8. Troubleshooting Stability with Cloud APIs
If a cloud inference endpoint is used, slowdowns and dropped connections are common complaints. Troubleshooting can follow an outside-in order:
- Locate the bottleneck: is first-token latency high, or is throughput low during output;
- Check the network path: whether connection reuse is effective and whether handshakes happen frequently;
- Review the request shape: whether very long contexts or high batch concurrency trigger queuing;
- Improve the retry strategy: use exponential backoff and idempotent design so retries do not amplify load;
- Define a fallback path: prepare a backup model or a local fallback for critical flows.
9. Acceptance and Rollout Checklist
Before delivery, complete the following acceptance checks: build large files and deep directories in a test directory and verify counting accuracy; run out-of-bounds tests against deletion paths and confirm the interception works; simulate an unreadable directory and confirm the overall flow is not interrupted; and record a timing baseline at million-element scale as a reference for later optimization.
10. Closing Thoughts
Generating a disk analysis and cleanup program from a single sentence demonstrates the efficiency value of code generation models in operations scenarios. What actually determines success is whether the requirement breakdown is clear, whether the safety guardrails are in place, whether the generated code has been rigorously reviewed, and whether the runtime environment is stable and controllable. Treat the model as an efficient implementer and keep engineering judgment on the human side, and you can solve capacity emergencies both quickly and safely.
