# Save Agent Job Progress on a Hosted Mac Guide

Canonical: https://figment.so/blog/mac-agent-job-checkpoints

Commit each task's result to a SQLite database in WAL mode before starting the next one, and have the runner skip rows marked done. A Figment Intel Mac VM ($25 a month) is enough for this pattern.

Save progress in a local SQLite database in WAL mode: mark each task `running` before you start it, mark it `done` in the same database as soon as it finishes, and have the runner skip every `done` row on restart. SQLite ships with macOS, needs no server, and does not corrupt its main file when a process is killed. The pattern runs well on a Figment Intel Mac VM ($25 a month), because it only needs Python, `sqlite3`, `launchd` and a local disk.

## Which Figment Mac plan fits this job?

The Intel Mac VM fits a checkpointed agent that calls HTTP APIs, writes files and keeps its state in SQLite. It has 4 shared vCPUs, 4GB of RAM and an 80GB SSD, and runs macOS Sequoia with SSH access and administrator access to your own VM. The storage includes the OS, and the checkpoint database sits next to your working files on the local disk.

| Your job needs | Plan | Price |
| --- | --- | --- |
| Python or shell tasks, SQLite state, Intel-compatible tools and Xcode 26.0 to 26.3 | [Intel Mac VM](/mac-hosting#intel-vm) | $25 a month, $2 a day, $0.15 an hour |
| Apple silicon-only binaries, Xcode 26.4 or later, or the iOS Simulator on Apple silicon | [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) | $39 a month, $6 a day, $0.40 an hour |
| A whole Mac for heavy tasks, or a job you want isolated from other customers' VMs | [Dedicated M4 Pro 48 GB](/mac-hosting#dedicated-m4-pro) | $349 a month ($299 on a 12-month term) |

VM vCPUs are shared, not reserved cores. The Intel VM cannot run arm64-only binaries or visionOS, and some iCloud features are disabled on it.

## What do I need before I start?

You need a database path on a local disk, a source of tasks, a stable task ID and a result shape.

| Input | Purpose |
|---|---|
| SQLite database path | Persistent checkpoint store. Keep it inside your project working directory on the local disk |
| Task list source | JSON file, API response, or any iterable input |
| Task identifier | A stable key per task: URL, file hash, database row ID |
| Result schema | What your job stores per task (URL scraped, file path, API result) |
| Resume flag | `--resume` or the equivalent argument your launcher passes |

The agent user only needs read and write access to the working directory. No elevated privileges are required. WAL mode needs shared memory between processes on the same host, so keep the database on a local volume and not on an SMB or NFS path.

## What does the checkpoint schema look like?

One table holds per-task state and one holds metadata. Run this once at job startup with `sqlite3 checkpoint.db < checkpoint.sql`.

```sql
-- checkpoint.sql: run once at job startup via `sqlite3 checkpoint.db < checkpoint.sql`

PRAGMA journal_mode = WAL;

CREATE TABLE IF NOT EXISTS job_progress (
    task_id     TEXT PRIMARY KEY,
    status      TEXT NOT NULL
                CHECK(status IN ('pending', 'running', 'done', 'failed')),
    result_json TEXT,                 -- per-task output (JSON text)
    started_at  TEXT,                 -- ISO-8601 UTC, e.g. 2026-11-10T14:00:00Z
    finished_at TEXT,
    attempt     INTEGER DEFAULT 1
);

CREATE TABLE IF NOT EXISTS job_meta (
    key   TEXT PRIMARY KEY,
    value TEXT
);

INSERT OR IGNORE INTO job_meta (key, value) VALUES ('schema_version', '1');
```

WAL means SQLite writes committed changes to a separate `-wal` file and moves them into the main database during a checkpoint. If the process is killed, the first new connection runs a recovery pass under an exclusive lock and replays committed WAL frames, so the main file is never left partly written. The default auto-checkpoint fires when the WAL reaches 1,000 pages (about 4 MB), and `PRAGMA wal_checkpoint(TRUNCATE)` forces a full checkpoint and truncates the WAL file to zero. See the [SQLite Write-Ahead Logging documentation](https://www.sqlite.org/wal.html) and [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint).

## How do I write a runner that resumes?

Initialize the schema, seed pending tasks, then loop over every task that is not done, marking each one before and after it runs.

```python
#!/usr/bin/env python3
"""
agent_runner.py — checkpoint-aware job runner
Usage: python3 agent_runner.py --tasks tasks.json [--resume]
"""
import argparse, json, sqlite3, sys
from datetime import datetime, timezone

DB_PATH = "checkpoint.db"

def now_utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

def init_db(conn):
    with open("checkpoint.sql") as f:
        conn.executescript(f.read())
    conn.commit()

def seed_tasks(conn, tasks):
    """Idempotent on resume: existing rows are untouched."""
    conn.executemany(
        "INSERT OR IGNORE INTO job_progress (task_id, status) VALUES (?, 'pending')",
        [(t["id"],) for t in tasks],
    )
    conn.commit()

def run_task(task_id: str) -> dict:
    """Replace with your actual work. Must return a JSON-serialisable dict."""
    return {"processed": task_id, "ts": now_utc()}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tasks", required=True)
    ap.add_argument("--resume", action="store_true")
    args = ap.parse_args()

    with open(args.tasks) as fh:
        tasks = json.load(fh)
    conn = sqlite3.connect(DB_PATH)
    conn.execute("PRAGMA journal_mode = WAL")

    init_db(conn)
    seed_tasks(conn, tasks)

    rows = conn.execute(
        "SELECT task_id FROM job_progress WHERE status != 'done' ORDER BY rowid"
    ).fetchall()

    if not rows:
        print("All tasks already done.", flush=True)
        sys.exit(0)

    processed_since_checkpoint = 0
    for (task_id,) in rows:
        conn.execute(
            "UPDATE job_progress SET status='running', started_at=? WHERE task_id=?",
            (now_utc(), task_id),
        )
        conn.commit()

        try:
            result = run_task(task_id)
            conn.execute(
                """UPDATE job_progress
                   SET status='done', result_json=?, finished_at=?
                   WHERE task_id=?""",
                (json.dumps(result), now_utc(), task_id),
            )
        except Exception as exc:
            conn.execute(
                "UPDATE job_progress SET status='failed', result_json=? WHERE task_id=?",
                (json.dumps({"error": str(exc)}), task_id),
            )
        conn.commit()

        processed_since_checkpoint += 1
        if processed_since_checkpoint >= 50:
            conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
            processed_since_checkpoint = 0

    conn.close()
    print("Job complete.", flush=True)

if __name__ == "__main__":
    main()
```

`INSERT OR IGNORE` in `seed_tasks` makes startup safe to re-run. The explicit `wal_checkpoint(TRUNCATE)` every 50 commits bounds WAL growth, so a backup sees a small, consistent file. The snippet is an illustrative example, not a benchmark. Time it against your own tasks before you rely on throughput numbers.

## How do I prove a crash resumes correctly?

Run a kill-and-replay test before you touch production data. It needs only `sqlite3` and the runner above. For the mid-run kill to land deterministically, add `import time; time.sleep(0.1)` to `run_task` while testing, then remove it.

```bash
#!/usr/bin/env bash
# test_checkpoint_resume.sh
set -euo pipefail

DB=checkpoint.db
TASKS=test_tasks.json
rm -f "$DB" "$DB-wal" "$DB-shm" "$TASKS"

python3 -c "
import json
tasks = [{'id': f'task-{i:02d}'} for i in range(10)]
print(json.dumps(tasks))
" > "$TASKS"

python3 agent_runner.py --tasks "$TASKS" &
RUNNER_PID=$!
while :; do
    done=$(sqlite3 "$DB" "SELECT COUNT(*) FROM job_progress WHERE status='done';" 2>/dev/null || echo 0)
    [[ "$done" -ge 5 ]] && break
    sleep 0.2
done
kill "$RUNNER_PID" 2>/dev/null || true
wait "$RUNNER_PID" 2>/dev/null || true

done_before=$(sqlite3 "$DB" \
    "SELECT task_id FROM job_progress WHERE status='done' ORDER BY task_id;")

python3 agent_runner.py --tasks "$TASKS" --resume

total=$(sqlite3 "$DB" "SELECT COUNT(*) FROM job_progress WHERE status='done';")
if [[ "$total" -eq 10 ]]; then
    echo "PASS: all 10 tasks done"
else
    echo "FAIL: only $total done"; exit 1
fi

done_after=$(sqlite3 "$DB" \
    "SELECT task_id FROM job_progress WHERE status='done' ORDER BY task_id;")
while IFS= read -r tid; do
    grep -qx "$tid" <<<"$done_after" || { echo "FAIL: $tid lost on resume"; exit 1; }
done <<<"$done_before"
echo "PASS: all pre-crash task IDs preserved"
```

The script asserts two things: every task finishes, and no task completed before the kill was lost on resume. Run it again before every migration or plan change.

## How much disk will the checkpoint database use?

A `job_progress` row with a small `result_json` takes roughly 100 to 200 bytes, so a million tasks fit in well under 1GB of the VM's 80GB SSD. If you store raw HTML or binary blobs in `result_json`, the database grows much faster. Write those to files and store only the path.

## How do I back up the checkpoint database?

Copy `checkpoint.db` and `checkpoint.db-wal` together, or run `PRAGMA wal_checkpoint(TRUNCATE)` first and then copy only the main file. Figment does not back up your Mac. A local database file is not a backup on its own, so copy results somewhere you control if losing progress would hurt.

## How do I start or migrate the workload?

Pick a plan on [Figment Mac hosting](/mac-hosting). Once the Mac is ready:

1. Copy `agent_runner.py` and `checkpoint.sql` to your working directory on the Mac.
2. Run `test_checkpoint_resume.sh` and confirm both PASS lines before any production data.
3. Wire the runner into `launchd` so it restarts after a crash or reboot.

To migrate a job already in progress, stop the runner cleanly, run `PRAGMA wal_checkpoint(TRUNCATE)`, then copy the single `checkpoint.db` file to the new Mac. If you cannot stop cleanly, copy `checkpoint.db`, `checkpoint.db-wal` and `checkpoint.db-shm` together. Losing the WAL loses the most recent committed frames.

---

**Related guides:**
- [Mac Agent Action Approvals](/blog/mac-agent-action-approvals)
- [Mac Agent Network Scope](/blog/mac-agent-network-scope)
- [GitHub Actions Self-Hosted Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
