Disk Space Analysis and Cleanup with Large Language Models: A Practical Guide

    This article explains how to use large language models to build a disk space analysis and cleanup tool. It covers the common causes of full disks, how to turn a one-sentence requirement into an executable specification, key review points for generated code, a three-phase execution strategy, common pitfalls, and a practical deployment checklist.

    1. Why Full Disks Are a Frequent Failure

    In development, testing, and data analysis environments, running out of disk space is a common failure with a wide blast radius. Typical symptoms include build jobs failing abruptly, logs that can no longer be written, database temporary file creation errors, containers exiting unexpectedly, and even an operating system becoming unusable due to lack of swap space.

    The root causes usually fall into a few categories:

    • Large file accumulation: installation packages, image archives, datasets, screen recordings, and exported files that are never cleaned up.
    • Unbounded log growth: application, access, and audit logs without rotation or retention policies.
    • Out-of-control caches and temporary directories: package manager caches, build intermediates, and temporary extraction directories with no size limits.
    • Deletion without reclamation: files are deleted but a process still holds the handle, so space is not released immediately.
    • inode exhaustion: a large number of small files leads to a situation where “there appears to be plenty of space, but no new file can be created.”

    Therefore, a practical disk governance tool should not just “delete large files.” It needs a complete loop: scan, sort, locate, classify, recommend, and execute cleanup only after explicit authorization.

    2. Goal Definition: Turning a One-Sentence Requirement into an Executable Spec

    The core of the original practice is to describe the need in one natural language sentence and have the model directly produce a “disk space analysis + cleanup” program. To make the generated result reliable, the requirement description should cover the following:

    1. Runtime and language constraints: specify the operating system, runtime version, and whether zero third-party dependencies are required.
    2. Scan scope: which root directory to start from, whether to cross file systems, and whether to follow symbolic links.
    3. Output content: aggregate size by directory, Top N largest files, distribution of last modification times, and statistics by extension.
    4. Cleanup policy: report only by default; deletion must be explicitly enabled and support a dry run.
    5. Safety mechanisms: path allowlist, protected directories, minimum retention time, and confirmation before deletion.
    6. Maintainability: parameterized configuration, structured logs, and traceable errors.

    A reusable prompt skeleton example:

    1. Implement a command-line tool in Python with the following requirements:
    2. - Use only the standard library and be compatible with current mainstream operating systems;
    3. - Scan a specified directory, aggregate usage by first-level subdirectory, and output the Top 20 in descending order;
    4. - List the 20 largest files, including path, size, and last modification time;
    5. - Default to dry-run; perform deletion only when --execute is passed;
    6. - Deletion condition: file larger than 100MB and last modified more than 30 days ago;
    7. - Exclude system directories and application data directories; log and skip paths without permission;
    8. - Output both JSON and human-readable text formats.

    3. Review Focus for Generated Code: The More Capable It Is, the More Boundaries It Needs

    Models generate code efficiently, but review cannot be skipped. Check in the following order:

    • Safe path joining: prevent user input from causing out-of-bounds deletion; when necessary, convert the target path to an absolute path and validate the prefix.
    • Reversible deletion: prefer moving to a quarantine directory over direct deletion, keeping a recovery window.
    • Symbolic link handling: do not follow by default, to prevent duplicate counting and accidental damage to real data.
    • Permissions and exceptions: explicitly handle no-permission cases, locked files, and network file system timeouts.
    • Performance strategy: use streaming traversal for large directory scans to avoid loading all paths at once and bloating memory.

    Illustrative safety validation logic:

    1. def is_safe_target(path: str, allowed_root: str) -> bool:
    2. p = os.path.abspath(path)
    3. root = os.path.abspath(allowed_root)
    4. return os.path.commonpath([p, root]) == root and p != root

    4. Execution Strategy: Analyze First, Recommend Next, Clean Up Last

    It is recommended to split the tool into three phases to reduce the chance of accidental operations:

    1. Analysis phase: read metadata only, produce a report, and modify no files.
    2. Recommendation phase: generate a candidate cleanup list based on rules, annotated with estimated space to be freed and risk level.
    3. Execution phase: must be enabled by an explicit parameter; first run a dry run to print the actions to be performed, then execute and output an audit record.

    For log files, a safer approach is not to delete them directly, but to combine rotation and compression policies; for cache directories, prefer the cleanup entry points provided by the application itself to avoid breaking dependency consistency.

    5. Common Pitfalls and How to Avoid Them

    • Looking only at total space, not inodes: count the number of files and inode usage rate as well.
    • Space still shown as used after deletion: check whether a process still holds a handle to a deleted file.
    • Running directly at the root directory: limit the minimum scan depth and maximum scan duration to prevent prolonged I/O occupation.
    • Ignoring network and virtual file systems: skip or separately mark special mount points.
    • Lack of auditing: all deletion actions should record the time, path, size, and source of the operation.

    6. Engineering Considerations on the Model Service Side

    In practice, the service experience of generative models is affected by network links, concurrency quotas, context length, and inference strategies. More robust engineering practices include: templating prompts and business rules, performing static checks and sandbox execution on generated results, and accumulating high-frequency troubleshooting workflows into an internal script library. For scenarios with data compliance and low-latency requirements, it is worth evaluating deploying lightweight models in a private environment, and combining general capabilities such as the container platform, object storage, log service, and monitoring and alerting provided by Baidu AI Cloud to build a closed loop of “collect—analyze—alert—handle.”

    7. Implementation Checklist

    • Generate an initial version of the tool from a one-sentence requirement, but it must include dry-run and an allowlist.
    • Report first: produce the Top directories and large file list before deciding on a cleanup strategy.
    • Isolate cleanup actions, make them auditable and reversible.
    • Incorporate disk usage rate and inode usage rate into routine monitoring and threshold alerting.
    • Regularly review accidental deletions and alert noise, and continuously tighten the rules.