Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions .claude/skills/measure-telemetry-span/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
name: measure-telemetry-span
description: Use when measuring a Sentry performance span locally with an agent-device replay flow on iOS simulator or Android emulator.
argument-hint: "<span-name> [runs] [platform] [--boot]"
allowed-tools: Bash(.claude/skills/measure-telemetry-span/measure.sh) Read Grep Glob
---

# Measure Telemetry Span

**Pattern:** from repo root, run one command with a span name and platform → stdout is a small summary table (avg / min / max + sample ms list). The script measures whatever Git checkout is currently active: it never runs `git checkout` or otherwise switches branches. To compare this branch with `main` (or any other revision), check out each commit/branch in turn—or use two worktrees/clones—and run `measure.sh` separately, then compare the two printed summaries.

## Command

```bash
.claude/skills/measure-telemetry-span/measure.sh <span-name> [runs] [platform] [--boot]
```

| Argument | Default | Description |
| -------------- | ------- | --------------------------------------------------------------------------- |
| `<span-name>` | — | Must match `# @tag sentry-<span-name>` on a flow under `.claude/skills/agent-device/flows/tests/` (sentry-tagged QA scenarios live there; the script searches `flows/` recursively, so `flows/macros/` is also scanned for completeness). |
| `[runs]` | `10` | Measured replays after **one** warmup inside the script. |
| `[platform]` | `ios` | `ios` or `android` — must match the simulator/emulator you use. |
| `--boot` | off | Before `open`, runs `agent-device boot --platform <platform>` so a simulator/emulator is started when nothing was connected (`adb devices` empty, etc.). |

To pick a **specific** Android AVD or iOS simulator, use the same global flags `agent-device` already supports (for example `--device "Pixel_7_API_34"`) on **`boot`** and on later commands — either run `agent-device boot --platform android --device "…"` yourself before `measure.sh`, or rely on `agent-device` config (`~/.agent-device/config.json`). `--boot` inside this script only passes `--platform` through to `boot`.

**Environment:** `APP_ID` overrides app bundle (default `com.expensify.chat.dev`). If the flow declares `# @param KEY …`, set **`AD_KEY`** to pass `-e KEY=VALUE` to replay.

**Output:** table + `Samples: …ms` line; stderr has progress (`Using flow:`, runs, optional reset).

## Before you run

| Must have | Notes |
| --------- | ----- |
| `agent-device` (global install, version per repo agent-device skill) | |
| Metro on **8081** (`npm run start`) | |
| Dev build on device | |
| **iOS** | `agent-device react-devtools` attached so Hermes `console.debug` reaches logs. |
| **Android** | Span line visible in `adb logcat` at debug once you verify manually. |

If you see **no Android device** (`adb devices` empty): append **`--boot`** to the measure command, or run manually first:

`agent-device boot --platform android` (optional `--device "<AVD name>"`). For iOS, `agent-device boot --platform ios` or `agent-device ensure-simulator --boot` when you need a created simulator instance.

## Contract

- App logs: `[Sentry][<SpanName>] Ending span (<N>ms)` via `console.debug`.
- Flow file includes `# @tag sentry-<SpanName>` (same name, case-sensitive).
- Optional flow headers: `@reset <path.ad>` (run by the script after warmup and each measured replay; if absent, the script relaunches the app instead so each run starts from `@pre`); `@param` keys overridable via `AD_*` (passed as `-e KEY=VALUE` to replay).
- **Parsing:** stats take the **last** `RUNS` matching log lines from the capture. That matches one sample per measured replay only if each replay emits **one** such line for this span name. Extra matches (duplicate logs, nested/sub-spans with the same message pattern, noisy startup logging) can shift which samples are included—fix the app logging or tighten the grep if that happens.

## `@reset` and loop stability

`measure.sh` replays the **same** tagged flow every iteration. Treat `@reset` as “return to a known anchor,” not a second copy of the whole scenario:

- Prefer a **short** reset flow (tabs to Inbox, dismiss sheet, etc.). When agent-device splits **macros** vs **tests**, point `@reset` at a **macro** path so one file stays the source of truth.
- If runs are flaky locally but fine for others, walk the bring-up checklist in `.claude/skills/agent-device/SKILL.md` (Metro, dev build, device boot, iOS + DevTools for `console.debug`) before blaming selectors.

Optional: keep a tiny markdown table in your team notes mapping `SpanName` → one-line intent + `@pre` anchor; the span name still drives which `.ad` is picked — no need to repeat long repro prose in every chat.

## If something fails

| Symptom | Action |
| ------- | ------ |
| `No captured runs` | iOS: DevTools. Android: log level / package. Retry after clearing log pipeline. |
| `SESSION_NOT_FOUND` / empty `adb devices` | Use **`--boot`** on the measure script, or `agent-device boot --platform android|ios` (see `--device` if multiple AVDs/simulators). Then `open` again if needed. |
| Fewer samples than `runs` | Span not emitted or flow flaky — `agent-device replay <flow> --debug`; fix selectors (`ad-flow-author`). |

For another app bundle, export `APP_ID` before the command.
187 changes: 187 additions & 0 deletions .claude/skills/measure-telemetry-span/measure.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
#!/usr/bin/env bash
set -euo pipefail

BOOT="false"
POSITIONAL=()
for arg in "$@"; do
if [[ "$arg" == "--boot" ]]; then
BOOT="true"
else
POSITIONAL+=("$arg")
fi
done
set -- "${POSITIONAL[@]}"

SPAN="${1:?span name required}"
RUNS="${2:-10}"
PLATFORM="${3:-ios}"
APP_ID="${APP_ID:-com.expensify.chat.dev}"
LOG_PID=""
FLOW_ENV_ARGS=()
RESET_FLOW=""

if [[ "$PLATFORM" != "ios" && "$PLATFORM" != "android" ]]; then
echo "Platform must be 'ios' or 'android'." >&2
exit 1
fi

if ! [[ "$RUNS" =~ ^[0-9]+$ ]] || [[ "$RUNS" -lt 1 ]]; then
echo "Runs must be a positive integer." >&2
exit 1
fi

REPO="$(git rev-parse --show-toplevel)"
FLOWS_DIR="$REPO/.claude/skills/agent-device/flows"
FLOW=""
while IFS= read -r -d '' candidate; do
if grep -q "^# @tag[[:space:]]\+sentry-${SPAN}\$" "$candidate" 2>/dev/null; then
FLOW="$candidate"
break
fi
done < <(find "$FLOWS_DIR" -name '*.ad' -type f -print0 2>/dev/null)

if [[ -z "$FLOW" ]]; then
echo "No flow declares '@tag sentry-$SPAN'. Available:" >&2
find "$FLOWS_DIR" -name '*.ad' -type f -exec grep -h '^# @tag[[:space:]]\+sentry-' {} + 2>/dev/null | sed 's/.*sentry-//' | sort -u >&2
exit 1
fi

RESET_DECL=$(grep -E '^# @reset[[:space:]]+' "$FLOW" | sed -E 's/^# @reset[[:space:]]+//' | head -1 || true)
if [[ -n "$RESET_DECL" ]]; then
if [[ "$RESET_DECL" = /* ]]; then
RESET_FLOW="$RESET_DECL"
else
RESET_FLOW="$REPO/$RESET_DECL"
fi

if [[ ! -f "$RESET_FLOW" ]]; then
echo "Reset flow does not exist: $RESET_FLOW" >&2
exit 1
fi
fi

TMP_DIR="$(mktemp -d)"
DURATIONS_FILE="$TMP_DIR/durations.txt"

cleanup() {
if [[ -n "$LOG_PID" ]]; then
kill "$LOG_PID" 2>/dev/null || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# Flow `# @param KEY description` headers: only AD_<KEY> overrides are passed via `-e KEY=VALUE`.
append_flow_env_from_ad_vars() {
local param_lines line key env_key
param_lines=$(grep -E '^# @param[[:space:]]+[A-Za-z_][A-Za-z0-9_]*' "$FLOW" || true)
if [[ -z "$param_lines" ]]; then
return
fi

while IFS= read -r line; do
key=$(echo "$line" | sed -E 's/^# @param[[:space:]]+([A-Za-z_][A-Za-z0-9_]*).*/\1/')
env_key="AD_${key}"
if [[ -n "${!env_key:-}" ]]; then
FLOW_ENV_ARGS+=("-e" "$key=${!env_key}")
echo "Replay param: $key from $env_key" >&2
fi
done <<< "$param_lines"
}

start_log() {
local out="$1"
if [[ "$PLATFORM" == "ios" ]]; then
xcrun simctl spawn booted log stream --level debug \
--predicate "eventMessage CONTAINS \"[Sentry][$SPAN] Ending span\"" > "$out" &
else
adb logcat -c
adb logcat '*:D' > "$out" &
fi
echo $!
}

reset_if_needed() {
if [[ -n "$RESET_FLOW" ]]; then
echo "Resetting with: $RESET_FLOW" >&2
agent-device replay "$RESET_FLOW" >&2
return
fi

# No @reset declared: relaunch the app so the next replay starts from the flow's @pre state
# instead of the previous run's @post state (Codex review r3191676565).
agent-device open "$APP_ID" --platform "$PLATFORM" --relaunch >&2
sleep 5
if [[ "$PLATFORM" == "android" ]]; then
wait_until_android_ui_ready
fi
}

# After --relaunch on Android, UIAutomator often returns Snapshot: 0 nodes briefly; warmup replay then fails @pre.
wait_until_android_ui_ready() {
local snapshot
for _ in $(seq 1 60); do
snapshot="$(agent-device snapshot 2>/dev/null || true)"
if [[ "$snapshot" == *'"Home"'* && "$snapshot" == *'"Inbox'* ]]; then
return
fi
sleep 1
done

echo "Warning: Android UI not ready after 60s (no Home/Inbox tabs); proceeding anyway." >&2
}

measure_current_branch() {
local raw="$TMP_DIR/capture.log"

if [[ "$BOOT" == "true" ]]; then
echo "Booting $PLATFORM target (agent-device boot)..." >&2
agent-device boot --platform "$PLATFORM" >&2
fi

agent-device open "$APP_ID" --platform "$PLATFORM" --relaunch >&2
sleep 5
if [[ "$PLATFORM" == "android" ]]; then
wait_until_android_ui_ready
fi

LOG_PID=$(start_log "$raw")
agent-device replay "$FLOW" ${FLOW_ENV_ARGS[@]+"${FLOW_ENV_ARGS[@]}"} >&2 # warmup
Comment thread
BartekObudzinski marked this conversation as resolved.
Resolved
reset_if_needed
sleep 1

for i in $(seq 1 "$RUNS"); do
echo "Run $i/$RUNS" >&2
agent-device replay "$FLOW" ${FLOW_ENV_ARGS[@]+"${FLOW_ENV_ARGS[@]}"} >&2
reset_if_needed
sleep 1
done

kill "$LOG_PID" 2>/dev/null || true
LOG_PID=""

# Last N numeric durations: assumes one "[Sentry][<span>] Ending span (Nms)" line per measured replay (see SKILL.md Contract).
grep "\\[Sentry\\]\\[$SPAN\\] Ending span" "$raw" | grep -oE "Ending span \(([0-9]+)ms\)" | grep -oE '[0-9]+' | tail -n "$RUNS" || true
}
Comment thread
Julesssss marked this conversation as resolved.
Resolved

echo "Using flow: $FLOW" >&2
if [[ -n "$RESET_FLOW" ]]; then
echo "Using reset flow: $RESET_FLOW" >&2
fi
append_flow_env_from_ad_vars
measure_current_branch > "$DURATIONS_FILE"

awk '
{ b[++bn]=$1; bs+=$1; if(!bmin||$1<bmin)bmin=$1; if($1>bmax)bmax=$1 }
END {
if (!bn) { print "No captured runs."; exit 1 }
ba=bs/bn
printf "| Metric | value |\n"
printf "|--------|-------|\n"
printf "| Runs | %5d |\n", bn
printf "| Avg | %4.0fms |\n", ba
printf "| Min | %4dms |\n", bmin
printf "| Max | %4dms |\n", bmax
printf "\nSamples: "
for (i=1; i<=bn; i++) printf "%sms%s", b[i], (i<bn ? ", " : "\n")
}' "$DURATIONS_FILE"
Loading