# Collecting Safari Crash Logs as Test Evidence

Canonical: https://figment.so/blog/mac-safari-crash-log-evidence

Record the test start epoch, then collect only new Safari .ips files from ~/Library/Logs/DiagnosticReports and upload a dated tarball with an always-run CI step. It needs a macOS host, not the Simulator.

**Add a shell post-step that records the test start time, collects only the new Safari `.ips` crash reports from `~/Library/Logs/DiagnosticReports`, extracts their headers, and uploads a dated `.tar.gz` as a CI artifact.** The script below does all of that on any Mac that runs your Safari tests, and it runs before the next job sweeps the directory clean.

## Where does macOS store Safari crash reports?

In `DiagnosticReports`, documented by Apple in [Diagnosing issues using crash reports and device logs](https://developer.apple.com/documentation/xcode/diagnosing-issues-using-crash-reports-and-device-logs):

- **`~/Library/Logs/DiagnosticReports/`** holds per-user crash reports. The current user process can write it, and it is the useful one for CI scripts.
- **`/Library/Logs/DiagnosticReports/`** holds system-wide reports. It needs elevated privileges and is rarely required for Safari automation.

Since macOS 12 (Monterey), crash reports use the `.ips` extension and store their payload as two-part JSON. The first line is a compact metadata header containing `bug_type`, `os_version`, `timestamp` and `incident_identifier`. The remaining lines form the larger JSON body with thread stacks, binary images and exception details. Older `.crash` files (plain text) can still appear from older tooling, so handle both extensions. Safari crash files are named with a `Safari-` prefix and a timestamp, for example `Safari-2026-11-10-141523.ips`.

## Which crash header fields should I record?

Record the five fields below. The header line of an `.ips` file is a single JSON object you can read with `python3` or `jq`.

| Field | Meaning |
|---|---|
| `os_version` | macOS version at time of crash, e.g. `"macOS 15.5 (24F74)"` |
| `timestamp` | Local crash time with timezone offset |
| `bug_type` | `309` for a standard application crash |
| `incident_identifier` | Unique UUID for this crash report |
| `name` | Process name, e.g. `"Safari"` |

Extract them with a small helper:

```bash
# header_fields.sh
IPS_FILE="$1"
python3 - "$IPS_FILE" <<'EOF'
import sys, json
with open(sys.argv[1]) as f:
    header = json.loads(f.readline())
print(json.dumps({
    "incident":   header.get("incident_identifier"),
    "timestamp":  header.get("timestamp"),
    "os_version": header.get("os_version"),
    "bug_type":   header.get("bug_type"),
    "name":       header.get("name"),
}, indent=2))
EOF
```

This is an untested example. Point it at a real `.ips` file in your own `DiagnosticReports` directory before relying on the field names.

## How do I keep only the crashes from my test run?

Record a marker epoch with `date +%s` before the first test invocation, then compare each file's modification time.

```bash
TEST_START=$(date +%s)
# ... run xcodebuild test / pytest / WebDriver ...
find ~/Library/Logs/DiagnosticReports \
  \( -name 'Safari-*.ips' -o -name 'Safari-*.crash' \) -print |
while read -r f; do
  MTIME=$(stat -f '%m' "$f")
  if [ "$MTIME" -ge "$TEST_START" ]; then
    echo "$f"
  fi
done
```

`stat -f '%m'` is the BSD form shipped on macOS and returns the modification time as a Unix epoch integer, directly comparable with the recorded `TEST_START`.

## What does the full collection script look like?

Save the script below as `scripts/collect_safari_crashes.sh`. It combines timestamp gating, header extraction, crashing-thread extraction for legacy `.crash` files and final tarball packaging.

```bash
#!/usr/bin/env bash
# collect_safari_crashes.sh
# Usage: collect_safari_crashes.sh <TEST_START_EPOCH> <OUTPUT_DIR>

set -euo pipefail

TEST_START="${1:?Provide TEST_START epoch as first argument}"
OUTPUT_DIR="${2:?Provide OUTPUT_DIR as second argument}"
DIAG_DIR="$HOME/Library/Logs/DiagnosticReports"
BUNDLE_NAME="safari-crashes-$(date -u +%Y%m%dT%H%M%SZ)"
STAGE_DIR="$(mktemp -d)"
trap 'rm -rf "$STAGE_DIR"' EXIT

found=0
while IFS= read -r f; do
  MTIME=$(stat -f '%m' "$f")
  if [ "$MTIME" -ge "$TEST_START" ]; then
    cp "$f" "$STAGE_DIR/"
    found=$((found + 1))
    echo "  Collected: $(basename "$f")"

    if [[ "$f" == *.crash ]]; then
      awk '/^Thread [0-9]+ Crashed/,/^$/' "$f" \
        > "$STAGE_DIR/$(basename "${f%.crash}").crashing-thread.txt" || true
    fi

    if [[ "$f" == *.ips ]]; then
      python3 - "$f" > "$STAGE_DIR/$(basename "${f%.ips}").header.json" <<'PYEOF' || true
import sys, json
with open(sys.argv[1]) as fh:
    try:
        header = json.loads(fh.readline())
    except json.JSONDecodeError:
        header = {}
print(json.dumps({
    "incident":   header.get("incident_identifier", "unknown"),
    "timestamp":  header.get("timestamp", "unknown"),
    "os_version": header.get("os_version", "unknown"),
    "bug_type":   header.get("bug_type", "unknown"),
}, indent=2))
PYEOF
    fi
  fi
done < <(find "$DIAG_DIR" \( -name 'Safari-*.ips' -o -name 'Safari-*.crash' \) 2>/dev/null)

if [ "$found" -gt 0 ]; then
  mkdir -p "$OUTPUT_DIR"
  ARCHIVE="$OUTPUT_DIR/${BUNDLE_NAME}.tar.gz"
  tar -czf "$ARCHIVE" -C "$STAGE_DIR" .
  echo "Archived $found crash file(s) to $ARCHIVE"
else
  echo "No new Safari crash files found."
fi
```

Design notes:

- `set -euo pipefail` plus the `EXIT` trap keeps the staging directory from leaking.
- `|| true` around the per-file extractors stops one malformed crash from blocking the archive of valid ones.
- Crashing-thread `awk` extraction runs only on plain-text `.crash` files. `.ips` files are JSON and get the structured header dump instead.
- The script exits non-zero only on the argument check, so it will not fail your CI job just because no crashes occurred.

## How do I upload the bundle in GitHub Actions and GitLab CI?

Run the collection step with an always-run guard in both. A Safari crash exits the test step non-zero, and without the guard the upload step is skipped exactly when you need the evidence.

**GitHub Actions:**

```yaml
- name: Record test start
  id: ts
  run: echo "epoch=$(date +%s)" >> "$GITHUB_OUTPUT"

- name: Run Safari tests
  run: xcodebuild test -scheme "$XCODE_SCHEME" -destination 'platform=macOS'

- name: Collect Safari crash logs
  if: always()
  run: bash scripts/collect_safari_crashes.sh "${{ steps.ts.outputs.epoch }}" crash-artefacts

- name: Upload crash bundle
  if: always()
  uses: actions/upload-artifact@v4
  with:
    name: safari-crashes-${{ github.sha }}
    path: crash-artefacts/
    retention-days: 14
```

Pass your project's real scheme in `XCODE_SCHEME`. There is no default scheme name here, and an invented one makes `xcodebuild` fail.

**GitLab CI:** `after_script` runs in a fresh shell, so variables set in `script` do not survive. Persist the epoch to a file.

```yaml
test:safari:
  script:
    - date +%s > .test_start_epoch
    - xcodebuild test -scheme "$XCODE_SCHEME" -destination 'platform=macOS'
  after_script:
    - bash scripts/collect_safari_crashes.sh "$(cat .test_start_epoch)" crash-artefacts
  artifacts:
    name: "safari-crashes-${CI_COMMIT_SHA}"
    paths:
      - crash-artefacts/
    expire_in: 14 days
    when: always
```

## How do I match a crash to a specific test case?

Record each test's start time in the test body, then align it with the `timestamp` in each crash header. The header pins the crash to the second.

```swift
func testSafariRendersCheckout() throws {
    let caseStart = ISO8601DateFormatter().string(from: Date())
    XCTContext.runActivity(named: "test-window-\(caseStart)") { _ in }
    // ... run your test ...
}
```

After the run, parse the `.xcresult` with `xcrun xcresulttool` and align the recorded `test-window-...` activities with the `timestamp` from each collected crash header. One crash file falling inside one test window is the strongest signal you get before attaching a debugger.

## Does this work in the iOS Simulator?

No, you need a macOS host. The script targets `DiagnosticReports`, which records crashes from macOS-native processes on the host. The iOS Simulator keeps its own path at `~/Library/Logs/CoreSimulator/` and captures only Simulator-process crashes, not Safari for macOS.

## What Mac does the Safari crash log script need?

Any plan runs the script, because it needs only a macOS host with Safari and a shell, and we have not run it on any plan. The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia and the Safari that Sequoia ships. The Apple Silicon Mac VM ($39 a month, $6 a day) fits arm64-only tooling or Xcode 26.4 or later. For context, [CloudMac](https://cloudmac.org/pricing) publishes a Mac mini M4 (16 GB / 256 GB) at $99.99 a month, and its home page lists $999 a year on the same configuration.

| Option | Monthly | 12-month cost |
|---|---|---|
| Figment Apple Silicon Mac VM (4 shared vCPUs, 4GB, 65GB) | $39 | $468 |
| Figment Dedicated M4 Pro 48 GB (M4 Pro, 48GB, 512GB) | $349 | $3,228 paid up front, or $3,588 on a 12-month term |
| CloudMac M4 / 16 GB / 256 GB, monthly | $99.99 | $1,199.88 |
| CloudMac, annual prepay | $83.25 effective | $999 |

Arithmetic: 12 × $39 = $468; 12 × $299 = $3,588; 12 × $99.99 = $1,199.88; $999 ÷ 12 = $83.25. Figment's VM is a virtual machine with shared vCPUs, while CloudMac lists a whole Mac mini, so the table compares price, not equal hardware. See the [Mac hosting plans](/mac-hosting) and check the macOS version shown before purchase.

## What should I read next?

- [iOS Simulator Face ID biometric test](/blog/mac-simulator-face-id-biometric-test)
- [Bluetooth permission prompt UITest](/blog/mac-bluetooth-permission-prompt-uitest)
- [GitHub Actions self-hosted runner on a Mac](/blog/mac-github-actions-self-hosted-runner)
