Files
sanderling/cmd/internal-tools/campaign/campaign_test.go
pj 76dce1a75e experiment instrumentation: step budgets, arm labels, campaign runner (#72)
* feat(cli): add --max-steps for step-bounded runs

runner.Options.MaxSteps already worked but was unreachable from the command
line. A step budget is what makes two generators comparable: one making a
model call per step and one drawing from a PRNG are not comparable per second.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* feat(trace): record arm membership and host in meta.json

meta.json recorded the seed but not which picker ran, how it was configured,
what budget it was given, or which machine produced it. A directory of runs
cannot be attributed to an experiment cell without those, which makes any
factorial computed from such a directory unanalysable after the fact.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* feat(cli): add --arm and populate run meta from it

Model and instructions are recorded only when the LLM picker is the one that
will actually run, so a spec declaring generator = llm() that is run under the
seeded picker does not label its trace with a model it never called.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* feat(campaign): sweep seeds for one experiment cell

campaign.json lists the seeds a sweep intended to run and is written before
the first run, so a host that dropped runs shows up as missing seeds rather
than as a smaller sample. Seed 0 is rejected: sanderling test reads it as
"derive a seed from the clock", which is why conformance/gates.sh controls
nothing today.

Each run contributes one runs.jsonl line carrying steps to first violation by
origin step, the step that armed the failed obligation, so the survival
analysis never reopens a trace.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(runner): no silent generator fallback, and llm on web

--generator llm against a spec declaring no generator = llm(...) logged a
warning and ran the seeded picker. For a comparison campaign that is silent
arm corruption: the run completes, the directory looks correct, and the wrong
policy drove it. It is now fatal.

pickSources also returned the V8 source for both action and extractor on web
before it looked at the generator, so the llm policy was unreachable there.
The two axes are now independent: the driver picks the extractor source, the
flag picks the action source, and llmSource composes with either because the
runner populates the candidate list and screenshot on every platform.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(chrome): make the hierarchy dump agree with the web runtime

Three facts differed between the dump the goja host reads and the DOM the V8
host reads, so the two enumerated different candidates on one page.

scrollable was never emitted, and worker.go reads exactly that attribute while
targets.ts requires it for scrolls, so the goja host could not offer a single
web scroll. clickable tested el.onclick, which React assigns to its root
container for event delegation, making the whole viewport a tap target here and
in no other enumeration. Both now resolve through the selector sets in
pkg/spec/src/web-runtime.ts.

The dump also rooted at body while collectTargets walks querySelectorAll("*"),
so the goja host never saw html, where page-level scrolling lives. It now roots
at documentElement and skips the head subtree, which is all zero-bounds and
would otherwise carry script and title text into the trace.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(conformance): give the gate reproducible seeds

SEED defaulted to 0 and sanderling test reads --seed 0 as "derive a seed from
the clock", so the tunable controlled nothing and a gate failure could not be
re-run. SEEDS now takes one explicit non-zero seed per run, recorded in the
results table so a failing row names its stream.

The five runs stay on five different streams: a gate that scored one path five
times would catch less than one that scores five.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(chrome): emit editable as a plain boolean

editable was emitted as `isEditable || null`, and an absent field sends
internal/hierarchy into the native fallback, which reads any class name
containing "EditText" as an Android text widget. On web that is just a CSS
class, so a page styling a div with it was editable to the goja host and not to
the web runtime, and the model policy could be offered typing into a div.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(spec): leave the head subtree out of the web target walk

collectTargets walked querySelectorAll("*") while the hierarchy dump skips head,
so the two hosts enumerated different element sets on every page with a <head>.
No candidate changes: builtinCandidates pushes only for targets acceptsTarget
admits, and head elements have no positive bounds, so the list the draw ranges
over is untouched. What changes is that targetIndex now means the same thing on
both hosts.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* test(chrome): compare the facts both hosts derive from one DOM

The existing parity harness hand-authors the facts on both sides, so it proves
that given identical facts both hosts select identical candidates, and says
nothing about the two code paths that derive those facts from a real page. Four
divergences lived in that blind spot and it passed throughout.

This drives one real page and compares clickable, enabled, editable, scrollable
and positiveBounds element by element, plus the element sets themselves, which
is what catches a host that omits html or includes head. Reverting any of the
four fixes makes it fail naming the element and the fact.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* chore(make): run the browser packages one at a time

Both launch Chrome and launching two at once has failed with "Launch: context
canceled".

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* style: remove every em-dash and en-dash

Eighteen occurrences across fourteen files. Each sentence was repunctuated to
suit what the dash was doing rather than swapped for a hyphen, which produces
comma splices. The minus sign in folio-web's ledger is a minus sign and stays.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(chrome): honor the caller context in Launch

Launch and clearState ran against d.tabCtx, so a target that accepts the
connection and never answers wedged the process past its own --duration and
through SIGTERM, needing SIGKILL. Unattended that is a campaign worker lost for
the rest of the sweep with no diagnostic.

The browser is still allocated against d.tabCtx first, because chromedp starts
Chrome under whichever context calls Run first and allocating under a caller
deadline would kill the browser when Launch returns. Everything after
allocation goes through runCtx.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* fix(sidecarassets): publish the extracted jar through a rename

Extract wrote a 96 MB jar with a plain WriteFile into a temp path every
sanderling process on the host shares. On a cold host several concurrent
workers all miss the checksum and all write the same path, and O_TRUNC lets one
spawn a JVM against another's half-written archive. A fresh experiment host is
exactly a cold host.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* feat(campaign): kill a run that outlives --run-timeout

A wedged run holds its worker for the rest of the sweep, and on an unattended
host nothing else will send it a signal. Defaults to three times --duration and
must exceed it. A killed run is recorded as timed_out rather than as a generic
failure, so the analysis can tell a lost cell from a real crash.

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX

* style(test): gofmt browser_test.go

Claude-Session: https://claude.ai/code/session_01A5KmftdEJ49A9z5mF5ESrX
2026-08-12 22:20:31 +05:30

363 lines
12 KiB
Go

package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/priyanshujain/sanderling/internal/trace"
)
func testConfiguration(t *testing.T, outputDirectory string, extra ...string) config {
t.Helper()
arguments := append(baseArguments(), "--output", outputDirectory)
configuration, err := parseArguments(append(arguments, extra...), io.Discard)
if err != nil {
t.Fatal(err)
}
return configuration
}
// versionAnswering wraps a test executor so every fake answers `sanderling
// version`, which the campaign probes before it writes the manifest.
func versionAnswering(executor commandExecutor) commandExecutor {
return func(ctx context.Context, binary string, arguments []string, output io.Writer) (int, error) {
if len(arguments) > 0 && arguments[0] == "version" {
fmt.Fprintln(output, "stub-version")
return 0, nil
}
return executor(ctx, binary, arguments, output)
}
}
func readRecords(t *testing.T, campaignDirectory string) []runRecord {
t.Helper()
file, err := os.Open(filepath.Join(campaignDirectory, recordsFileName))
if err != nil {
t.Fatal(err)
}
defer file.Close()
var records []runRecord
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var record runRecord
if err := json.Unmarshal(scanner.Bytes(), &record); err != nil {
t.Fatalf("decode %q: %v", scanner.Text(), err)
}
records = append(records, record)
}
if err := scanner.Err(); err != nil {
t.Fatal(err)
}
return records
}
func writeFakeRun(t *testing.T, arguments []string, steps []trace.Step) {
t.Helper()
writeRunDirectory(t, argumentValue(arguments, "--output"), "20260101-000000", steps)
}
func TestRunCampaign_WritesManifestBeforeAnyRun(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory)
var stdout bytes.Buffer
executor := versionAnswering(func(_ context.Context, _ string, arguments []string, _ io.Writer) (int, error) {
if _, err := os.Stat(filepath.Join(directory, manifestFileName)); err != nil {
t.Errorf("manifest missing when the first run started: %v", err)
}
writeFakeRun(t, arguments, []trace.Step{observedStep(1)})
return 0, nil
})
if err := runCampaign(context.Background(), configuration, executor, &stdout); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(filepath.Join(directory, manifestFileName))
if err != nil {
t.Fatal(err)
}
var recorded manifest
if err := json.Unmarshal(body, &recorded); err != nil {
t.Fatal(err)
}
if !slices.Equal(recorded.Seeds, []int64{1, 2, 3}) {
t.Errorf("intended seeds: got %v", recorded.Seeds)
}
if recorded.SanderlingVersion != "stub-version" {
t.Errorf("version: got %q", recorded.SanderlingVersion)
}
if recorded.Host == "" {
t.Error("host was not recorded")
}
}
func TestRunCampaign_RecordsPerRunSummary(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory, "--seeds", "1-3")
var stdout bytes.Buffer
executor := versionAnswering(func(_ context.Context, _ string, arguments []string, output io.Writer) (int, error) {
fmt.Fprintln(output, "stub run log")
steps := []trace.Step{observedStep(1), observedStep(2), observedStep(3)}
if argumentValue(arguments, "--seed") == "2" {
violating := observedStep(3)
violating.Violations = []string{"listNeverEmpty"}
violating.Witnesses = map[string]trace.Witness{
"listNeverEmpty": {Reason: "list emptied", Step: 2, DetectedStep: 3},
}
steps[2] = violating
}
writeFakeRun(t, arguments, steps)
return 0, nil
})
if err := runCampaign(context.Background(), configuration, executor, &stdout); err != nil {
t.Fatal(err)
}
records := readRecords(t, directory)
if len(records) != 3 {
t.Fatalf("records: got %d, want 3", len(records))
}
for _, record := range records {
if record.Steps != 3 {
t.Errorf("seed %d steps: got %d, want 3", record.Seed, record.Steps)
}
if record.RunDirectory != fmt.Sprintf("seed-%d/20260101-000000", record.Seed) {
t.Errorf("seed %d run directory: got %q", record.Seed, record.RunDirectory)
}
if record.TraceError != "" {
t.Errorf("seed %d trace error: %s", record.Seed, record.TraceError)
}
violated := record.FirstViolationOriginStep != nil
if violated != (record.Seed == 2) {
t.Errorf("seed %d violation: got %v", record.Seed, record.FirstViolationOriginStep)
}
if record.Seed != 2 {
continue
}
if *record.FirstViolationOriginStep != 2 || *record.FirstViolationDetectedStep != 3 {
t.Errorf("seed 2 violation steps: origin %d detected %d",
*record.FirstViolationOriginStep, *record.FirstViolationDetectedStep)
}
if !slices.Equal(record.ViolatedProperties, []string{"listNeverEmpty"}) {
t.Errorf("seed 2 properties: got %v", record.ViolatedProperties)
}
}
log, err := os.ReadFile(filepath.Join(directory, "seed-1", "sanderling.log"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(log), "stub run log") {
t.Errorf("per-run log: got %q", log)
}
if !strings.Contains(stdout.String(), "seed=2") {
t.Errorf("progress output missing seed 2: %q", stdout.String())
}
}
func TestRunCampaign_DistributesSeedsAcrossDeviceWorkers(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory, "--seeds", "1-9", "--devices", "device-a,device-b,device-c")
var mutex sync.Mutex
assignments := map[int64]string{}
var inFlight atomic.Int32
var releaseOnce sync.Once
var timedOut atomic.Bool
release := make(chan struct{})
executor := versionAnswering(func(_ context.Context, _ string, arguments []string, _ io.Writer) (int, error) {
if inFlight.Add(1) >= 3 {
releaseOnce.Do(func() { close(release) })
}
select {
case <-release:
case <-time.After(5 * time.Second):
timedOut.Store(true)
}
seed, err := strconv.ParseInt(argumentValue(arguments, "--seed"), 10, 64)
if err != nil {
t.Errorf("seed argument: %v", err)
}
mutex.Lock()
if previous, seen := assignments[seed]; seen {
t.Errorf("seed %d ran twice (%s then %s)", seed, previous, argumentValue(arguments, "--device"))
}
assignments[seed] = argumentValue(arguments, "--device")
mutex.Unlock()
writeFakeRun(t, arguments, []trace.Step{observedStep(1)})
return 0, nil
})
if err := runCampaign(context.Background(), configuration, executor, io.Discard); err != nil {
t.Fatal(err)
}
if timedOut.Load() {
t.Fatal("three device workers never ran concurrently")
}
if len(assignments) != 9 {
t.Fatalf("seeds run: got %d, want 9", len(assignments))
}
used := map[string]int{}
for seed, device := range assignments {
if !slices.Contains(configuration.devices, device) {
t.Errorf("seed %d ran on unknown device %q", seed, device)
}
used[device]++
}
if len(used) != 3 {
t.Errorf("devices used: got %v, want all three", used)
}
if got := len(readRecords(t, directory)); got != 9 {
t.Errorf("records: got %d, want 9", got)
}
}
func TestRunCampaign_ContinuesAfterFailingRun(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory, "--seeds", "1-3")
executor := versionAnswering(func(_ context.Context, _ string, arguments []string, output io.Writer) (int, error) {
if argumentValue(arguments, "--seed") == "2" {
fmt.Fprintln(output, "error: device offline")
return 1, nil
}
writeFakeRun(t, arguments, []trace.Step{observedStep(1)})
return 0, nil
})
err := runCampaign(context.Background(), configuration, executor, io.Discard)
if err == nil || !strings.Contains(err.Error(), "1 of 3 runs failed") {
t.Fatalf("expected a failure summary, got %v", err)
}
records := readRecords(t, directory)
if len(records) != 3 {
t.Fatalf("a failing run must not abort the campaign: got %d records", len(records))
}
for _, record := range records {
if record.Seed == 2 {
if record.ExitCode != 1 {
t.Errorf("seed 2 exit code: got %d, want 1", record.ExitCode)
}
if record.TraceError == "" {
t.Error("seed 2 produced no trace; that should be recorded")
}
continue
}
if record.ExitCode != 0 {
t.Errorf("seed %d exit code: got %d", record.Seed, record.ExitCode)
}
}
}
func TestRunCampaign_RefusesToReuseACampaignDirectory(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory)
if err := os.WriteFile(filepath.Join(directory, manifestFileName), []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
executor := versionAnswering(func(context.Context, string, []string, io.Writer) (int, error) {
t.Error("no run should start in a directory that already holds a campaign")
return 0, nil
})
if err := runCampaign(context.Background(), configuration, executor, io.Discard); err == nil {
t.Fatal("expected a refusal to reuse the campaign directory")
}
}
func TestRunCampaign_AbortsWhenVersionProbeFails(t *testing.T) {
directory := t.TempDir()
configuration := testConfiguration(t, directory)
executor := func(_ context.Context, _ string, arguments []string, output io.Writer) (int, error) {
if arguments[0] != "version" {
t.Error("a run started despite an unusable binary")
}
fmt.Fprintln(output, "no such command")
return 2, nil
}
if err := runCampaign(context.Background(), configuration, executor, io.Discard); err == nil {
t.Fatal("expected the campaign to abort before writing a manifest it cannot attribute")
}
if _, err := os.Stat(filepath.Join(directory, manifestFileName)); err == nil {
t.Error("manifest was written despite an unusable binary")
}
}
func TestRunCampaign_UnreadableTraceIsNotASuccessfulCampaign(t *testing.T) {
campaignDirectory := filepath.Join(t.TempDir(), "cell")
configuration := testConfiguration(t, campaignDirectory, "--seeds", "1-2")
executor := versionAnswering(func(context.Context, string, []string, io.Writer) (int, error) {
return 0, nil
})
var stdout bytes.Buffer
err := runCampaign(context.Background(), configuration, executor, &stdout)
if err == nil || !strings.Contains(err.Error(), "2 of 2 runs produced an unreadable trace") {
t.Fatalf("a campaign whose runs left no readable trace must not report success: %v", err)
}
for _, record := range readRecords(t, campaignDirectory) {
if record.TraceError == "" {
t.Errorf("seed %d: expected a trace error, got none", record.Seed)
}
}
}
func TestRunCampaign_KillsAndRecordsAWedgedRun(t *testing.T) {
campaignDirectory := filepath.Join(t.TempDir(), "cell")
configuration := testConfiguration(t, campaignDirectory,
"--seeds", "1", "--duration", "50ms", "--run-timeout", "300ms")
executor := versionAnswering(func(ctx context.Context, _ string, _ []string, _ io.Writer) (int, error) {
<-ctx.Done()
return -1, ctx.Err()
})
var stdout bytes.Buffer
if err := runCampaign(context.Background(), configuration, executor, &stdout); err == nil {
t.Fatal("a campaign whose only run was killed must not report success")
}
records := readRecords(t, campaignDirectory)
if len(records) != 1 {
t.Fatalf("want one record, got %d", len(records))
}
if !records[0].TimedOut {
t.Error("a run killed by the run timeout must be recorded as timed out")
}
if !strings.Contains(stdout.String(), "timed out") {
t.Errorf("the progress line must name the outcome:\n%s", stdout.String())
}
}
func TestParseArguments_RunTimeoutMustExceedDuration(t *testing.T) {
_, err := parseArguments(append(baseArguments(),
"--output", t.TempDir(), "--duration", "5m", "--run-timeout", "1m"), io.Discard)
if err == nil {
t.Fatal("a run timeout below the duration would kill every run before it finished")
}
}
func TestParseArguments_RunTimeoutDefaultsToThreeTimesDuration(t *testing.T) {
configuration, err := parseArguments(append(baseArguments(),
"--output", t.TempDir(), "--duration", "4m"), io.Discard)
if err != nil {
t.Fatal(err)
}
if configuration.runTimeout != 12*time.Minute {
t.Errorf("run timeout default: got %s, want 12m", configuration.runTimeout)
}
}