Skip to content

Cloud Mac CI log retention: protect active files and prune safely

Cloud Mac CI log retention: protect active files and prune safely

Cloud Mac CI log retention: protect active files and prune safely

When the same cloud Mac handles build after build, logs can turn from troubleshooting evidence into a disk-space problem. Simply deleting large files on a schedule can destroy evidence of a failure that is still being logged. The filename may disappear while a process continues to hold the disk space. On a self-hosted macOS runner, define how logs move between states before applying a retention policy, rather than adding a cleanup command to the start of every build.

Define log states and a storage budget first

Separate logs into three states: active, completed, and left over after an abnormal exit. Use the .active suffix while a log is being written, and rename it to .log only after the normal finalization steps. Active files left behind by abnormal exits require manual review; do not delete them automatically based on age.

Create a separate directory on each machine and allow only the runner user to write to it. Do not share this directory with untrusted jobs: file checks in a cleanup script are no substitute for permission isolation. The approach below manages build output only. It does not cover system logs or redact sensitive data from logs.

The storage budget should account for three things: a cap on completed logs, the active logs that concurrent jobs may generate, and the headroom needed for build workspaces. For example, a 2 GiB cap on completed logs is a team-defined policy, not the machine's disk capacity or a service quota.

A retention period determines eligibility for deletion; it does not guarantee retention. When usage exceeds the cap, even more recent completed logs may be removed. Failure evidence that must be kept long term should first be placed in a separate archive.

Publish completed logs with a wrapper script

Save the following as ci/logged-run.sh and run it with Bash. This assumes that jobs do not leave background child processes still writing to the log. Each run gets its own file, and the original command's exit code is returned to the pipeline.

set -u
umask 077
root="$HOME/ci-build-logs"
mkdir -p "$root"
chmod 700 "$root"

if [ "$#" -eq 0 ]; then
  exit 64
fi

active="$(mktemp "$root/run.XXXXXXXX.active")" || exit 1
printf 'Build log: %s\n' "$active"

"$@" >"$active" 2>&1
rc=$?

printf '\nexit_code=%s\n' "$rc" >>"$active"
touch "$active"
mv "$active" "${active%.active}.log" || exit 1
exit "$rc"

Invoke it as bash ci/logged-run.sh xcodebuild, followed by the project's existing build arguments. The script does not enable set -e, so it can still record the exit code when a build fails. If you need a pipeline, put it in a separate script and enable pipefail there; do not pass the entire pipeline as a string argument.

Updating the modification time just before completion makes the retention period start at finalization. Renaming within the same directory makes the name change atomic, but does not guarantee durability after a power failure. This version does not stream output in real time; configure the pipeline to upload .log files on both success and failure.

Prune completed files only

Run the following Python 3 program in the directory reserved exclusively for the runner user. It first selects files older than seven days, then removes the remaining files from oldest to newest until their total size is no more than 2 GiB. It performs a dry run by default; add --apply to delete files.

import os
import stat
import sys
import time
from pathlib import Path

root = Path.home() / "ci-build-logs"
lock = root / ".prune-lock"
root.mkdir(mode=0o700, exist_ok=True)

try:
    lock.mkdir()
except FileExistsError:
    raise SystemExit("Pruning is already locked")

try:
    files = []
    for path in root.glob("run.*.log"):
        info = path.lstat()
        if stat.S_ISREG(info.st_mode):
            files.append((info.st_mtime, info.st_size, path))

    files.sort()
    cutoff = time.time() - 7 * 86400
    limit = 2 * 1024 ** 3
    total = sum(size for _, size, _ in files)
    apply = "--apply" in sys.argv[1:]

    for modified, size, path in files:
        if modified < cutoff or total > limit:
            print("DELETE" if apply else "WOULD_DELETE", path.name, size)
            if apply:
                path.unlink()
            total -= size
finally:
    lock.rmdir()

The pruning lock only prevents two cleanup processes from overlapping; it does not stop jobs from publishing new logs. The size cap therefore applies to the snapshot captured by this scan, not as a real-time hard limit. New files completed concurrently are handled on the next pass. Once a log has been renamed, it must remain immutable: do not reopen it to append more output.

The program does not recurse into subdirectories, follow symbolic links, or touch active files. If the process is forcibly terminated, it may leave the lock directory behind. Remove it only after confirming that no cleanup process is still running. Do not have a scheduled task delete the lock unconditionally.

Investigate leftover files and unreleased disk space

When you find a very old .active file, first check the job execution records, then check whether any process still has the file open:

lsof "$HOME/ci-build-logs/run.ABCDEFGH.active"
lsof +L1
df -h "$HOME/ci-build-logs"

Replace the filename in the first command with the actual leftover file. An ordinary user can see only the processes their permissions allow; ask an administrator to help check if necessary. An empty result from a single query is not enough to conclude that no process under another user is using the file.

After confirming that the job has ended and no writers remain, move the leftover file to a separate archive for abnormal exits, recording the job ID and the evidence behind your decision. Do not use truncate to forcibly reclaim space from an active log: the write offset may not reset to zero, and subsequent output will lose its preceding context.

Validate the retention policy with failure drills

First, use a test account to verify four cases: a normal command produces a .log file; a nonzero exit still has its exit code recorded; cleanup leaves .active files untouched while a long-running job is in progress; and forcibly terminating the wrapper script does not cause leftover files to be deleted automatically.

Next, create completed files that exceed the age and capacity limits, and check the deletion order against the dry-run list. Record filenames, sizes, and completion times in the cleanup audit log. A manual review of one cleanup pass is required before enabling deletion in production.

Finally, monitor active-log growth, total directory usage, and available filesystem space separately. Completed logs reaching the cap can trigger cleanup, but unusual growth in active logs calls for investigating an output loop or a stuck job. Keeping these two kinds of events separate prevents a return to “normal disk usage” from masking a failure that is still in progress.

Frequently asked questions

Why does deleting a log not immediately free disk space?

A writer may still hold the deleted file open. Check with lsof +L1, then let the owning job finish or use its cancellation procedure rather than repeatedly deleting files.

Can an active log be deleted once its retention period expires?

No. Automatic pruning should only handle completed logs. Check the job and open file handles before moving an abandoned active file into a separate recovery or deletion process.

Rent a dedicated Mac mini for your self-hosted runner

The entire machine is dedicated to one customer, with prepaid daily, weekly, monthly, or quarterly plans. After payment, find the delivery details in the console. Your team manages system updates, Xcode versions, and runner processes.

Choose a Mac mini server

Set up runner access on a dedicated node

Choose a model and billing term. After payment, find the delivery details in the console. Your team manages system updates, Xcode versions, and runner processes.