Disk Space Analysis and Cleanup with LLMs: A Practical Guide

    This article walks through using an LLM-powered coding tool to build a disk space analysis and cleanup utility. It covers why full disks cause cascading failures, how to structure a prompt around scanning, detection, cleanup, and safety requirements, and how to review generated code across safety, correctness, performance, and maintainability. It also outlines operational hardening such as monitoring integration, tiered cleanup policies, audit trails, and handling model service constraints.

    1. Why Full Disks Are a Frequent Failure

    On development machines, build servers, test machines, and edge nodes, running out of disk space is one of the most common failure types. The symptoms are rarely a single program error. Instead, they cascade: logs cannot be written, temporary files cannot be created, database writes are interrupted, containers fail to start, and build caches become invalid. Worse, a full disk is usually a slow accumulation. By the time an alert fires, it is already hard to tell what consumed the space.

    Traditional troubleshooting relies on manually walking through directories, measuring sizes by hand, and deciding what can be deleted based on experience. This approach has three clear weaknesses:

    • Time-consuming: Recursively measuring large directories takes time, and repeatedly switching directories adds more waiting.
    • Experience-dependent: Definitions of “deletable” differ across services, so newcomers can easily delete the wrong files.
    • Not reusable: Every incident starts from scratch, with nothing accumulated.

    Handing this kind of task to an AI coding tool with code generation capabilities is a practical engineering path: describe the goal in one natural language sentence and quickly produce a small “scan + report + controlled cleanup” tool. To make it usable in real environments, however, the focus must shift from “can it be generated” to “how to generate and run it safely.”

    2. Breaking Down the Requirement: What a One-Sentence Prompt Must Contain

    Output quality does not depend on prompt length; it depends on whether the constraints are complete. A usable disk analysis and cleanup tool must cover at least four areas:

    1. Scanning: Accept a root directory, measure first- and second-level directory sizes, support sorting by size, and support exporting a report.
    2. Detection: Distinguish large files, cache directories, log directories, temporary directories, and business data directories.
    3. Cleanup: Suggest only by default, require explicit opt-in to execute, and support allowlists and blocklists.
    4. Safety: Path validation, confirmation before deletion, dry-run mode, and an operation trail.

    A reference prompt structure looks like this (illustrative):

    1. Generate a command-line tool with the following requirements:
    2. 1. Accept a root directory and output the top N subdirectories sorted by size in descending order;
    3. 2. Support --dry-run, outputting cleanup suggestions only and performing no deletion by default;
    4. 3. Deletion must require a second confirmation and be written to an operation log;
    5. 4. Protect the root directory, system directories, and mount points; recursive deletion is forbidden;
    6. 5. Include parameter validation and exception handling, with usage instructions.

    The value of this structure is that it compresses the model’s free-form space into implementation details rather than business semantics. Once the semantics are ambiguous, the generated result wavers between “delete or not delete” and still requires manual rework.

    3. Reviewing Generated Code: Safety First, Then Performance

    Review the generated result in the order of safety, correctness, performance, and maintainability, rather than running it immediately.

    3.1 Safety

    • Does it default to dry-run, with deletion controlled by an explicit switch?
    • Does it normalize paths to avoid relative-path escapes?
    • Does it exclude the root directory, critical system directories, and the current working directory?
    • Is there rollback on deletion failure, or at least a complete log?

    3.2 Correctness

    • Does large-directory measurement use streaming traversal to avoid loading the entire file list at once?
    • Are symbolic links correctly skipped to prevent duplicate counting and out-of-bounds access?
    • Are exceptions such as insufficient permissions or files in use caught and skipped, rather than crashing the whole run?

    3.3 Performance

    The bottleneck in disk traversal is usually I/O rather than CPU. Acceptable optimizations include limiting recursion depth, ignoring obviously irrelevant directories, supporting counting only specified suffixes, and outputting incremental progress. Example code:

    1. def scan(root, max_depth=3, skip_dirs=None):
    2. skip_dirs = skip_dirs or set()
    3. results = []
    4. for cur, dirs, files in os.walk(root):
    5. depth = cur[len(root):].count(os.sep)
    6. if depth >= max_depth:
    7. dirs[:] = []
    8. continue
    9. dirs[:] = [d for d in dirs if d not in skip_dirs]
    10. size = sum(get_size(os.path.join(cur, f)) for f in files)
    11. results.append((cur, size))
    12. return sorted(results, key=lambda x: x[1], reverse=True)

    3.4 Maintainability

    Clear parameter naming, a consistent log format, and standard exit codes may seem trivial, but they determine whether the tool can be integrated into scheduled jobs and monitoring/alerting systems.

    4. From “Usable” to “Operable”: Three Necessary Additions

    1. Integrate monitoring and alerting: Output scan results as structured metrics collected by the log service and monitoring/alerting system, and set utilization thresholds to avoid “fill first, investigate later.”
    2. Layer cleanup policies: Cache data can be cleaned automatically, logs can be cleaned by retention period, and business data should only be flagged, not touched, forming a tiered policy.
    3. Operation trail and audit: Who deleted what, from which directory, and when must be traceable. This is both a troubleshooting basis and a responsibility boundary.

    When running on a container platform or cloud host, cold data can also be archived to object storage, turning “deletion” into “migration” and further reducing the cost of accidental deletion.

    5. Real Constraints on the Model Service Side

    In practice, beyond generation quality, two often underestimated variables are response speed and connection stability. Some cloud vendors’ model services experience reduced throughput or dropped connections during peak periods, causing long-running tasks to fail midway. The engineering responses are not complex:

    • Split tasks into segments, breaking a large scan into multiple smaller requests;
    • Persist results to disk to avoid relying on a single long-lived connection;
    • Keep a local fallback script for critical paths;
    • Version generated results to avoid repeated generation.

    If latency and controllability requirements are higher, deploying an open-source model locally can be evaluated, or a combination of model services and container platforms from Baidu AI Cloud can be used, choosing the appropriate option per business stage.

    6. Conclusion

    The real value of “generating a disk cleanup tool from one sentence” is not the coding time saved, but turning one-off troubleshooting experience into reusable, auditable, and operable engineering assets. Writing the constraints clearly, putting safety first, and connecting results to the monitoring system is what moves AI coding from “works in a demo” to “works in production.”