# Network Link Conditioner Safari Regression Tests

Canonical: https://figment.so/blog/mac-network-link-conditioner-safari

Use dnctl and pfctl to apply named throttle profiles before each Playwright WebKit run, then attach performance.timing as JSON per profile. It needs sudo on a Mac you administer.

**Throttle the network with macOS's built-in `dnctl` and `pfctl` before each Playwright WebKit run, then attach `performance.timing` as JSON per profile.** A shell wrapper applies a named profile (3G, Edge, high latency, packet loss), runs your test, and always tears the rules down. You need administrator access (`sudo`) on the Mac, which you have on your own Mac or VM, and we have not run this wrapper on a Figment plan. References: Apple's [Downloads for Apple Developers](https://developer.apple.com/download/all/) (where Additional Tools for Xcode ships Network Link Conditioner) and [Playwright's BrowserContext API](https://playwright.dev/docs/api/class-browsercontext), which exposes only `setOffline` and no bandwidth throttling.

## How do I install Network Link Conditioner?

Download Apple's **Additional Tools for Xcode**. Network Link Conditioner (NLC) is a System Settings pane in that package, not part of Xcode or the Command Line Tools.

1. Sign in to [Downloads for Apple Developers](https://developer.apple.com/download/all/) and search for *Additional Tools for Xcode* matching your Xcode version.
2. Mount the `.dmg`, open the **Hardware** folder, and double-click `Network Link Conditioner.prefPane`.
3. macOS installs the pane into System Settings → Network Link Conditioner.

Each profile defines **download bandwidth**, **upload bandwidth**, **delay (ms)** and **packet loss (%)**. Built-in profiles include 3G, Edge, DSL, LTE, Wi-Fi, Very Bad Network and 100% Loss, and you can add custom ones via **Manage Profiles**. Exact numbers vary by Xcode release, so read the values from your installed pane and treat the numbers below as representative only.

## Why use pfctl and dnctl instead of the GUI?

Because the GUI has no supported command-line entry point, and Playwright offers no bandwidth or latency control on any browser, including WebKit. NLC's pane is a front end for macOS's built-in **dummynet** (`dnctl`) and **packet filter** (`pfctl`), both of which ship with macOS. The pattern is to configure a dummynet pipe with bandwidth, delay and loss, attach a pfctl anchor that redirects outbound traffic through the pipe, and tear both down on exit.

```bash
#!/usr/bin/env bash
# throttle.sh — apply a named profile, run a command, then restore the network.
set -euo pipefail

PROFILE="${1:?Usage: throttle.sh <profile> <command...>}"
shift
IFACE="$(route -n get default | awk '/interface:/ {print $2}')"
PIPE_ID=42   # pick a pipe number not in use on this host
ANCHOR="figment.conditioner"

case "$PROFILE" in
  3g)               BW="330Kbit/s"; DELAY=100;  PLR=0.00 ;;
  edge)             BW="200Kbit/s"; DELAY=400;  PLR=0.00 ;;
  high-latency-dns) BW="1Mbit/s";   DELAY=3000; PLR=0.00 ;;
  loss-10pct)       BW="1Mbit/s";   DELAY=50;   PLR=0.10 ;;
  *) echo "Unknown profile: $PROFILE" >&2; exit 2 ;;
esac

teardown() {
  sudo pfctl -a "$ANCHOR" -F rules 2>/dev/null || true
  sudo dnctl pipe "$PIPE_ID" delete 2>/dev/null || true
}
trap teardown EXIT INT TERM

sudo dnctl pipe "$PIPE_ID" config bw "$BW" delay "$DELAY" plr "$PLR"
printf 'dummynet out on %s all pipe %s\n' "$IFACE" "$PIPE_ID" \
  | sudo pfctl -a "$ANCHOR" -f -
sudo pfctl -E >/dev/null 2>&1 || true

"$@"
```

The anchor name isolates these rules from any other pfctl configuration, so `-F rules` clears only what this script added. The script stops on any failure (`set -euo pipefail`), so do not count a failed Playwright run as a timing sample.

## How do I capture window.performance.timing in Playwright WebKit?

Install Playwright's WebKit and attach the timing as JSON from a test. Playwright's WebKit build uses the same rendering engine as Safari and is the practical target for regression timing. Checks that need Safari.app itself, such as push notifications or autofill behavior, need a separate run in Safari. Touch ID needs a physical Mac.

```bash
npm install -D @playwright/test
npx playwright install webkit
```

```typescript
// safari-perf.spec.ts
import { test, expect } from '@playwright/test';

test('home page timing', async ({ page }) => {
  const url = process.env.TARGET_URL ?? 'https://your-app.example.com';
  await page.goto(url, { waitUntil: 'load' });

  const timing = await page.evaluate(() => {
    const t = performance.timing;
    return {
      ttfb:      t.responseStart          - t.navigationStart,
      domReady:  t.domContentLoadedEventEnd - t.navigationStart,
      loadEvent: t.loadEventEnd           - t.navigationStart,
    };
  });

  const profile = process.env.NLC_PROFILE ?? 'unknown';
  test.info().attach(`timing-${profile}.json`, {
    body: JSON.stringify(timing, null, 2),
    contentType: 'application/json',
  });

  expect(timing.loadEvent).toBeGreaterThan(0);
});
```

Attaching the JSON through `test.info().attach` ties the timing file to that Playwright test result, which is safer than writing into the working directory where parallel jobs can collide.

## How do I run the whole profile matrix?

Drive it from a Makefile, one output directory per profile.

```makefile
PROFILES    := 3g edge high-latency-dns loss-10pct
RESULTS_DIR := perf-results
TARGET_URL  ?= https://your-app.example.com

.PHONY: perf-all clean $(PROFILES)

perf-all: $(PROFILES)
	@node ./scripts/merge-perf.js $(PROFILES) > $(RESULTS_DIR)/combined.json

$(PROFILES):
	@mkdir -p $(RESULTS_DIR)/$@
	NLC_PROFILE=$@ TARGET_URL=$(TARGET_URL) \
	  bash throttle.sh $@ \
	    npx playwright test safari-perf.spec.ts \
	      --project=webkit \
	      --output=$(RESULTS_DIR)/$@

clean:
	rm -rf $(RESULTS_DIR)
```

`--output` sets the artifact directory for the attached `timing-*.json` files, and one directory per profile avoids overwrites. A small `scripts/merge-perf.js` can walk those directories, read each `timing-*.json` attachment and emit one merged file keyed by profile for diffing between branches.

## How do I confirm the network is back to normal?

Check that no anchor rules remain, and run the check as its own CI step.

```bash
if sudo pfctl -a "figment.conditioner" -s rules 2>/dev/null | grep -q .; then
  echo "WARNING: conditioner rules still present" >&2
  exit 1
fi
sudo dnctl list | awk '/^0{0,0}042:/ && 0' # pipe 42 absent means clean
echo "pf and dummynet restored"
```

Do not rely on force-termination to clean up. If the CI runner is killed between steps, these rules can persist until reboot. Keep the teardown idempotent (every destructive call already has `|| true`), and make this check a separate step so a dirty host fails fast instead of silently skewing the next run.

## Why run this on a hosted Mac?

Timing is sensitive to competing traffic and CPU contention. A laptop with Spotlight indexing, iCloud Drive syncs, VPN re-handshakes and browser auto-refresh cannot give you a reproducible 330 Kbps 3G budget, because the throttle applies on top of whatever else is on `en0`. A hosted Mac that runs only the processes you start gives a quieter baseline. VM vCPUs are shared, not reserved cores, so repeat each profile several times and compare medians rather than single runs.

## What is the lowest-cost Mac for throttled Safari tests?

The Intel Mac VM ($25 a month, $2 a day) is the lowest-cost fit, since the workflow needs only `pfctl`, `dnctl`, Node and Playwright WebKit, and you have administrator access to your own VM. It runs macOS Sequoia and cannot run arm64-only binaries. Choose the Apple Silicon Mac VM ($39 a month) for an arm64 baseline, or the Dedicated M4 Pro ($349 a month) when you want a whole Mac with no neighbour, which suits timing work best. See the [Mac hosting plans](/mac-hosting) and check the macOS version shown before purchase.

**Related guides:**
- [iOS Simulator Parallel Device Matrix](/blog/mac-simulator-parallel-device-matrix)
- [Safari WebRTC Permissions Test](/blog/mac-safari-webrtc-permissions-test)
- [Self-Hosted GitHub Actions Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
