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
This commit is contained in:
pj authored and GitHub committed 2026-08-12 22:20:31 +05:30
1 parent 26b49b379a
commit 76dce1a75e
44 files changed
+3021 -87

No files matched your search

+62 -16
View File
@@ -97,19 +97,31 @@ func New() *Driver {
}
func (d *Driver) Launch(ctx context.Context, bundleID string, clearState bool, _ map[string]string) error {
// Allocate the browser against the driver's own context before anything
// caller-bound runs. chromedp starts Chrome under whichever context first
// calls Run, so allocating under a caller deadline would tie the browser
// process to this one call and kill it the moment Launch returns.
if err := chromedp.Run(d.tabCtx); err != nil {
return err
}
// Everything after allocation goes through runCtx, so a caller deadline or
// a SIGTERM aborts a launch that would otherwise wait forever on a target
// that accepts the connection and never answers.
runCtx, cancel := d.runCtx(ctx)
defer cancel()
if clearState {
if err := d.clearState(bundleID); err != nil {
if err := d.clearState(runCtx, bundleID); err != nil {
return err
}
}
if err := chromedp.Run(d.tabCtx, chromedp.Navigate(bundleID)); err != nil {
if err := chromedp.Run(runCtx, chromedp.Navigate(bundleID)); err != nil {
return err
}
// After navigation, read CSS custom properties --frame-w / --frame-h (common
// mobile-frame convention) so screenshots fit the app without grey borders.
// Falls back to the body scroll dimensions if the properties are absent.
var dims [2]int64
if err := chromedp.Run(d.tabCtx, chromedp.Evaluate(`
if err := chromedp.Run(runCtx, chromedp.Evaluate(`
(function() {
const s = getComputedStyle(document.documentElement);
const pw = parseInt(s.getPropertyValue('--frame-w'), 10);
@@ -118,7 +130,7 @@ func (d *Driver) Launch(ctx context.Context, bundleID string, clearState bool, _
const h = isNaN(ph) ? document.body.scrollHeight : ph;
return [w, h];
})()`, &dims)); err == nil && dims[0] > 0 && dims[1] > 0 {
_ = chromedp.Run(d.tabCtx, chromedp.EmulateViewport(dims[0], dims[1]))
_ = chromedp.Run(runCtx, chromedp.EmulateViewport(dims[0], dims[1]))
}
return nil
}
@@ -130,8 +142,8 @@ func (d *Driver) Launch(ctx context.Context, bundleID string, clearState bool, _
// which needs no navigation. sessionStorage is per-tab and outside that
// domain's reach; it only survives when a relaunch reuses a tab already on
// the target origin, which is the one case where script can reach it.
func (d *Driver) clearState(bundleID string) error {
if err := chromedp.Run(d.tabCtx, network.ClearBrowserCookies()); err != nil {
func (d *Driver) clearState(runCtx context.Context, bundleID string) error {
if err := chromedp.Run(runCtx, network.ClearBrowserCookies()); err != nil {
return fmt.Errorf("clear cookies: %w", err)
}
origin := securityOrigin(bundleID)
@@ -139,12 +151,12 @@ func (d *Driver) clearState(bundleID string) error {
return nil
}
clearForOrigin := storage.ClearDataForOrigin(origin, string(storage.TypeAll))
if err := chromedp.Run(d.tabCtx, clearForOrigin); err != nil {
if err := chromedp.Run(runCtx, clearForOrigin); err != nil {
return fmt.Errorf("clear storage for %s: %w", origin, err)
}
script := fmt.Sprintf(
`location.origin === %q && (sessionStorage.clear(), true)`, origin)
return chromedp.Run(d.tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.Run(runCtx, chromedp.ActionFunc(func(ctx context.Context) error {
_, exception, err := runtime.Evaluate(script).Do(ctx)
if err != nil {
return fmt.Errorf("clear session storage: %w", err)
@@ -357,6 +369,24 @@ func (d *Driver) Hierarchy(ctx context.Context) (string, error) {
script := `
(function() {
const route = window.location.hash.replace(/^#/, '').split('?')[0] || '/';
// clickable and editable are resolved through the SAME selector sets
// pkg/spec/src/web-runtime.ts uses, so the goja host (which reads this dump)
// and the V8 host (which reads the DOM directly) cannot mean different things
// by one fact on one platform. Testing el.onclick instead made every React
// root a full-viewport tap target here and nowhere else.
const NON_TEXT_INPUT_TYPES =
['button','submit','checkbox','radio','range','color','file','image','reset'];
function isEditableElement(el) {
if (el.isContentEditable) return true;
const tag = el.tagName.toLowerCase();
if (tag === 'textarea') return true;
if (tag === 'input') return !NON_TEXT_INPUT_TYPES.includes((el.type || '').toLowerCase());
return false;
}
const clickableSet = new Set(document.querySelectorAll(
'a, button, input, select, textarea, [role="button"], [onclick]'));
const editableSet = new Set(Array.from(
document.querySelectorAll('input, textarea, [contenteditable]')).filter(isEditableElement));
function buildTree(el, isRoot) {
const rect = el.getBoundingClientRect();
const attrs = {};
@@ -373,15 +403,19 @@ func (d *Driver) Hierarchy(ctx context.Context) (string, error) {
if (el.className && typeof el.className === 'string' && el.className.trim()) {
attrs['class'] = el.className.trim();
}
// The goja host reads scrollable off this attribute (internal/verifier
// worker.go targets). Without it every web element looks unscrollable there,
// so the goja-side enumeration offers no scroll while the V8 picker, which
// computes the same overflow test in web-runtime.ts, offers plenty.
if (el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth) {
attrs['scrollable'] = 'true';
}
if (isRoot) attrs['sanderling-screen'] = route;
const isClickable = !!(el.onclick || el.tagName === 'A' || el.tagName === 'BUTTON' ||
el.tagName === 'INPUT' || el.tagName === 'SELECT' ||
el.getAttribute('role') === 'button' || el.getAttribute('onclick'));
const isEditable = el.isContentEditable || tag === 'textarea' ||
(tag === 'input' && !['button','submit','checkbox','radio','range','color','file','image','reset']
.includes((el.type || '').toLowerCase()));
const isClickable = clickableSet.has(el);
const isEditable = editableSet.has(el);
const children = [];
for (const child of el.children) {
if (child.tagName === 'HEAD') continue;
children.push(buildTree(child, false));
}
return {
@@ -392,10 +426,22 @@ func (d *Driver) Hierarchy(ctx context.Context) (string, error) {
focused: document.activeElement === el || null,
checked: el.checked || null,
selected: el.selected || null,
editable: isEditable || null,
// Emitted as a plain boolean, never null: internal/hierarchy falls back to
// the native heuristic when the field is absent, which reads any class
// name containing "EditText" as an Android text widget. On web that is a
// CSS class, so a page styling a div with it made the goja host offer
// typing into a div the web runtime never calls editable.
editable: isEditable,
};
}
return buildTree(document.body, true);
// Rooted at documentElement, not body, because collectTargets in
// pkg/spec/src/web-runtime.ts walks querySelectorAll("*") and therefore sees
// html. Page-level scrolling lives on html on a standard page, so a dump
// rooted at body hides it from the goja host and the two enumerations
// disagree on exactly the page scroll. The head subtree is skipped: it is all
// zero-bounds, so it changes no eligible set, and it would otherwise pull
// script and title text into the trace and the replay view.
return buildTree(document.documentElement, true);
})()`
var result any
+253
View File
@@ -6,6 +6,7 @@ import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"net/http/httptest"
"testing"
@@ -185,6 +186,125 @@ func TestHierarchy_EditableFlag(t *testing.T) {
}
}
// TestHierarchy_ClickableMatchesTheWebRuntimeSelector pins clickable to the
// same membership test pkg/spec/src/web-runtime.ts applies. The dump used to
// test el.onclick, which React sets on its root container for event delegation,
// so the whole viewport became a tap target in this dump and in no other
// enumeration of the same page.
func TestHierarchy_ClickableMatchesTheWebRuntimeSelector(t *testing.T) {
const html = `<body>` +
`<div id="root"><button id="go">go</button></div>` +
`<textarea id="bio"></textarea>` +
`<div id="plain">text</div>` +
`<div id="rolebutton" role="button">act</div>` +
`<script>document.getElementById("root").onclick = function () {};</script>` +
`</body>`
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := d.Launch(ctx, "data:text/html,"+html, false, nil); err != nil {
t.Fatalf("Launch: %v", err)
}
dump, err := d.Hierarchy(ctx)
if err != nil {
t.Fatalf("Hierarchy: %v", err)
}
type node struct {
Attributes map[string]string `json:"attributes"`
Children []node `json:"children"`
Clickable *bool `json:"clickable"`
}
var root node
if err := json.Unmarshal([]byte(dump), &root); err != nil {
t.Fatalf("unmarshal hierarchy: %v", err)
}
clickableByID := map[string]*bool{}
var walk func(n node)
walk = func(n node) {
if id := n.Attributes["resource-id"]; id != "" {
clickableByID[id] = n.Clickable
}
for _, c := range n.Children {
walk(c)
}
}
walk(root)
isClickable := func(id string) bool {
return clickableByID[id] != nil && *clickableByID[id]
}
for _, id := range []string{"go", "bio", "rolebutton"} {
if !isClickable(id) {
t.Errorf("%q: clickable = %v, want true", id, clickableByID[id])
}
}
for _, id := range []string{"root", "plain"} {
if isClickable(id) {
t.Errorf("%q: clickable = true, want false/absent (an onclick property is not a target)", id)
}
}
}
// TestHierarchy_ScrollableAttribute covers the fact the goja host reads off the
// attributes map. The V8 picker computes the same overflow test in
// web-runtime.ts, so leaving it out of the dump made the two enumerations
// disagree on web: the model policy could never be offered a scroll the seeded
// policy could draw.
func TestHierarchy_ScrollableAttribute(t *testing.T) {
const html = `<body style="margin:0">` +
`<div id="overflowing" style="width:100px;height:100px;overflow:auto">` +
`<div style="width:100px;height:900px"></div></div>` +
`<div id="sideways" style="width:100px;height:50px;overflow:auto">` +
`<div style="width:900px;height:20px"></div></div>` +
`<div id="fits" style="width:100px;height:100px;overflow:auto">` +
`<div style="width:50px;height:50px"></div></div>` +
`</body>`
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := d.Launch(ctx, "data:text/html,"+html, false, nil); err != nil {
t.Fatalf("Launch: %v", err)
}
dump, err := d.Hierarchy(ctx)
if err != nil {
t.Fatalf("Hierarchy: %v", err)
}
type node struct {
Attributes map[string]string `json:"attributes"`
Children []node `json:"children"`
}
var root node
if err := json.Unmarshal([]byte(dump), &root); err != nil {
t.Fatalf("unmarshal hierarchy: %v", err)
}
scrollableByID := map[string]string{}
var walk func(n node)
walk = func(n node) {
if id := n.Attributes["resource-id"]; id != "" {
scrollableByID[id] = n.Attributes["scrollable"]
}
for _, c := range n.Children {
walk(c)
}
}
walk(root)
for _, id := range []string{"overflowing", "sideways"} {
if scrollableByID[id] != "true" {
t.Errorf("%q: scrollable = %q, want \"true\"", id, scrollableByID[id])
}
}
if scrollableByID["fits"] != "" {
t.Errorf("%q: scrollable = %q, want absent", "fits", scrollableByID["fits"])
}
}
// TestRunCtx_CallerCancelPropagates confirms that cancelling the caller's
// context cancels the chromedp-bound context returned by runCtx. This is the
// channel by which step deadlines and Ctrl-C reach in-flight CDP calls.
@@ -221,3 +341,136 @@ func TestRunCtx_TabCancelPropagates(t *testing.T) {
t.Fatal("derived ctx did not cancel after tab cancellation")
}
}
// TestHierarchy_RootsAtDocumentElementWithoutHead pins the dump's root to html,
// because collectTargets in pkg/spec/src/web-runtime.ts walks
// querySelectorAll("*") and therefore sees html. A dump rooted at body hides
// page-level scrolling, which lives on html on a standard page, so the two
// enumerations disagree on exactly that candidate. The head subtree stays out:
// it is all zero-bounds, so it changes no eligible set, and it would otherwise
// carry script and title text into the trace.
func TestHierarchy_RootsAtDocumentElementWithoutHead(t *testing.T) {
const html = `<html><head><title>secret title</title>` +
`<script>window.marker = 1;</script></head>` +
`<body><div id="content">hello</div></body></html>`
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := d.Launch(ctx, "data:text/html,"+html, false, nil); err != nil {
t.Fatalf("Launch: %v", err)
}
dump, err := d.Hierarchy(ctx)
if err != nil {
t.Fatalf("Hierarchy: %v", err)
}
type node struct {
Attributes map[string]string `json:"attributes"`
Children []node `json:"children"`
}
var root node
if err := json.Unmarshal([]byte(dump), &root); err != nil {
t.Fatalf("unmarshal hierarchy: %v", err)
}
if root.Attributes["tag"] != "html" {
t.Errorf("root tag: got %q, want html", root.Attributes["tag"])
}
if root.Attributes["sanderling-screen"] == "" {
t.Error("the root must still carry sanderling-screen")
}
tags := map[string]bool{}
var walk func(n node)
walk = func(n node) {
tags[n.Attributes["tag"]] = true
for _, child := range n.Children {
walk(child)
}
}
walk(root)
if !tags["body"] {
t.Error("body must appear under the root")
}
for _, tag := range []string{"head", "title", "script"} {
if tags[tag] {
t.Errorf("the head subtree must stay out of the dump, found %q", tag)
}
}
}
// TestLaunch_HonorsCallerDeadline points the driver at a listener that accepts
// the connection and never answers. Chrome has no page-load deadline of its
// own, so a Launch that ignored its caller context waited forever: an
// unattended campaign worker aimed at an unreachable target wedged with no
// diagnostic and did not even answer SIGTERM.
func TestLaunch_HonorsCallerDeadline(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer listener.Close()
held := make(chan net.Conn, 8)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
return
}
held <- conn
}
}()
defer func() {
close(held)
for conn := range held {
conn.Close()
}
}()
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
done := make(chan error, 1)
go func() { done <- d.Launch(ctx, "http://"+listener.Addr().String(), false, nil) }()
select {
case err := <-done:
if err == nil {
t.Fatal("Launch returned nil against a target that never answers")
}
if !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
t.Fatalf("Launch error = %v, want a context error", err)
}
case <-time.After(45 * time.Second):
t.Fatal("Launch ignored the caller deadline and blocked")
}
}
// TestLaunch_KeepsBrowserAliveAfterCallerContextEnds guards the trap that made
// Launch use the driver context in the first place: chromedp starts Chrome
// under whichever context runs first, so allocating under the caller's
// short-lived context would kill the browser as soon as Launch returned.
func TestLaunch_KeepsBrowserAliveAfterCallerContextEnds(t *testing.T) {
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
if err := d.Launch(ctx, "data:text/html,<body>alive</body>", false, nil); err != nil {
t.Fatalf("Launch: %v", err)
}
cancel()
var text string
if err := chromedp.Run(d.tabCtx,
chromedp.Evaluate(`document.body.textContent`, &text)); err != nil {
t.Fatalf("browser died with the caller context: %v", err)
}
if text != "alive" {
t.Errorf("body text = %q, want \"alive\"", text)
}
if err := d.Launch(context.Background(), "data:text/html,<body>again</body>", false, nil); err != nil {
t.Fatalf("second Launch after the first caller context ended: %v", err)
}
}
+343
View File
@@ -0,0 +1,343 @@
//go:build browser
package chrome
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"slices"
"testing"
"time"
"github.com/chromedp/chromedp"
"github.com/priyanshujain/sanderling/internal/bundler"
"github.com/priyanshujain/sanderling/internal/hierarchy"
)
// One page, two fact producers.
//
// Sanderling enumerates candidate actions from two independent hosts. The goja
// host reads the hierarchy dump this driver builds; the V8 host reads the live
// DOM through collectTargets in pkg/spec/src/web-runtime.ts. Both feed the SAME
// eligibility rule (pkg/spec/src/targets.ts), so the two enumerations agree only
// as far as the two producers agree on the facts.
//
// internal/verifier/host_parity_test.go and pkg/spec/test/host-parity.test.ts
// pin the other half: given identical facts, both hosts select identical
// candidates. They hand-author those facts on both sides, so neither producer is
// on their path, and three producer bugs lived in that gap: the dump emitted no
// `scrollable` attribute at all, it derived `clickable` from el.onclick (which
// React assigns to its root container, making the whole viewport a tap target
// here and nowhere else), and it rooted at document.body while the web runtime
// walks the whole document, hiding `html` and with it every page-level scroll.
//
// This test starts from one real DOM in a real browser and compares what the two
// producers derive from it, element by element. It found a fourth: the dump left
// `editable` unset rather than false, and an unset field sends the parser into
// the native EditText class-name heuristic, which reads a CSS class as an
// Android text widget.
// elementFacts is one element as a producer reports it: the tag, for readable
// failures, and every fact acceptsTarget consults.
type elementFacts struct {
tag string
clickable bool
enabled bool
editable bool
scrollable bool
positiveBounds bool
}
// factRow pairs an element's facts with the id both producers key on, kept in
// enumeration order because the order is part of the picker's parity contract.
type factRow struct {
id string
facts elementFacts
}
func TestHierarchy_DerivesTheSameFactsAsTheWebRuntime(t *testing.T) {
server := httptest.NewServer(http.FileServer(http.Dir("testdata")))
defer server.Close()
d := New()
defer d.Terminate(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
if err := d.Launch(ctx, server.URL+"/fact-parity.html", false, nil); err != nil {
t.Fatalf("Launch: %v", err)
}
dump, err := d.Hierarchy(ctx)
if err != nil {
t.Fatalf("Hierarchy: %v", err)
}
fromDump := factsFromHierarchyDump(t, dump)
fromWebRuntime := factsFromWebRuntime(ctx, t, d)
requireEveryElementNamed(t, "the hierarchy dump", fromDump)
requireEveryElementNamed(t, "the web runtime", fromWebRuntime)
requireBothPolarities(t, fromWebRuntime)
compareEnumeratedElements(t, fromDump, fromWebRuntime)
compareDerivedFacts(t, fromDump, fromWebRuntime)
}
// factsFromHierarchyDump reads the dump the way the goja host does: parse it,
// then take exactly the fields internal/verifier/worker.go targets() reads off
// each element.
func factsFromHierarchyDump(t *testing.T, dump string) []factRow {
t.Helper()
tree, err := hierarchy.Parse(dump)
if err != nil {
t.Fatalf("parse hierarchy: %v", err)
}
rows := make([]factRow, 0, len(tree.Elements))
for _, element := range tree.Elements {
rows = append(rows, factRow{
id: element.ResourceID,
facts: elementFacts{
tag: element.Attributes["tag"],
clickable: element.Clickable,
enabled: element.Enabled,
editable: element.Editable,
scrollable: element.Attributes["scrollable"] == "true",
positiveBounds: hasPositiveBounds(
element.Bounds.Width(),
element.Bounds.Height(),
),
},
})
}
return rows
}
// factsFromWebRuntime installs pkg/spec/test/dom-facts-probe.ts into the page
// and calls it. The probe is bundled through the production web bundler and
// reports what the production collectTargets derives, so the facts come from the
// shipped runtime rather than a copy of it; only the id-carrying readback is
// test-only.
func factsFromWebRuntime(
ctx context.Context,
t *testing.T,
d *Driver,
) []factRow {
t.Helper()
specSource := filepath.Join(repoRootDir(t), "pkg", "spec")
probe, err := bundler.BundleWeb(bundler.WebOptions{
EntryFile: filepath.Join(specSource, "test", "dom-facts-probe.ts"),
WebRuntimeFile: filepath.Join(specSource, "src", "web-runtime.ts"),
})
if err != nil {
t.Fatalf("bundle dom facts probe: %v", err)
}
if err := d.InstallBundle(ctx, probe.JavaScript); err != nil {
t.Fatalf("install dom facts probe: %v", err)
}
var encoded string
script := `JSON.stringify(window.__sanderlingDomFacts__())`
if err := chromedp.Run(d.tabCtx, chromedp.Evaluate(script, &encoded)); err != nil {
t.Fatalf("read web runtime facts: %v", err)
}
var wire []struct {
ID string `json:"id"`
Tag string `json:"tag"`
Clickable bool `json:"clickable"`
Enabled bool `json:"enabled"`
Editable bool `json:"editable"`
Scrollable bool `json:"scrollable"`
Width int `json:"width"`
Height int `json:"height"`
}
if err := json.Unmarshal([]byte(encoded), &wire); err != nil {
t.Fatalf("decode web runtime facts: %v", err)
}
rows := make([]factRow, 0, len(wire))
for _, item := range wire {
rows = append(rows, factRow{
id: item.ID,
facts: elementFacts{
tag: item.Tag,
clickable: item.Clickable,
enabled: item.Enabled,
editable: item.Editable,
scrollable: item.Scrollable,
positiveBounds: hasPositiveBounds(item.Width, item.Height),
},
})
}
return rows
}
// hasPositiveBounds is the positiveBounds fact of pkg/spec/src/targets.ts,
// applied to both producers so the geometry comparison cannot drift from the
// rule it stands in for.
func hasPositiveBounds(width, height int) bool {
return width > 0 && height > 0
}
// requireEveryElementNamed fails when a producer enumerates an element the
// fixture gave no id, because such an element cannot be joined and would sit in
// the comparison invisibly.
func requireEveryElementNamed(t *testing.T, producer string, rows []factRow) {
t.Helper()
for index, row := range rows {
if row.id == "" {
t.Fatalf(
"%s enumerated an unnamed <%s> at position %d; every element in "+
"testdata/fact-parity.html must carry an id to be comparable",
producer,
row.facts.tag,
index,
)
}
}
}
// requireBothPolarities keeps the comparison from going vacuous. A fixture, or
// an emulated viewport, that leaves a fact constant would compare false against
// false on every element and pass while proving nothing about that fact.
func requireBothPolarities(t *testing.T, rows []factRow) {
t.Helper()
for _, fact := range []struct {
name string
read func(elementFacts) bool
}{
{"clickable", func(f elementFacts) bool { return f.clickable }},
{"enabled", func(f elementFacts) bool { return f.enabled }},
{"editable", func(f elementFacts) bool { return f.editable }},
{"scrollable", func(f elementFacts) bool { return f.scrollable }},
{"positiveBounds", func(f elementFacts) bool { return f.positiveBounds }},
} {
var sawTrue, sawFalse bool
for _, row := range rows {
if fact.read(row.facts) {
sawTrue = true
} else {
sawFalse = true
}
}
if !sawTrue || !sawFalse {
t.Errorf(
"testdata/fact-parity.html no longer exercises %s both ways (the web "+
"runtime saw true=%v, false=%v), so comparing it proves nothing",
fact.name,
sawTrue,
sawFalse,
)
}
}
}
// compareEnumeratedElements is the check that the two producers walk the same
// document. It is what notices a producer that roots at body and never sees
// `html`, or one that enumerates the head subtree the other drops.
func compareEnumeratedElements(
t *testing.T,
fromDump, fromWebRuntime []factRow,
) {
t.Helper()
dumpIDs := enumeratedIDs(fromDump)
webIDs := enumeratedIDs(fromWebRuntime)
for _, row := range fromWebRuntime {
if !slices.Contains(dumpIDs, row.id) {
t.Errorf(
"the hierarchy dump never enumerated %q (<%s>); the web runtime does, "+
"so the goja host cannot offer a single action on it",
row.id,
row.facts.tag,
)
}
}
for _, row := range fromDump {
if !slices.Contains(webIDs, row.id) {
t.Errorf(
"the web runtime never enumerated %q (<%s>); the hierarchy dump does, "+
"so the V8 host cannot offer a single action on it",
row.id,
row.facts.tag,
)
}
}
if len(dumpIDs) == len(webIDs) && !slices.Equal(dumpIDs, webIDs) {
t.Errorf(
"the two producers enumerate the same elements in different order\n"+
" dump=%v\n web=%v",
dumpIDs,
webIDs,
)
}
}
// compareDerivedFacts compares the facts fact by fact, over every element both
// producers saw, so a failure names the element and the fact that diverged.
func compareDerivedFacts(t *testing.T, fromDump, fromWebRuntime []factRow) {
t.Helper()
webByID := map[string]elementFacts{}
for _, row := range fromWebRuntime {
webByID[row.id] = row.facts
}
for _, row := range fromDump {
web, ok := webByID[row.id]
if !ok {
continue
}
dump := row.facts
if dump.tag != web.tag {
t.Errorf(
"%q: the hierarchy dump calls it <%s>, the web runtime <%s>; the id "+
"join is resolving to different elements",
row.id,
dump.tag,
web.tag,
)
}
for _, fact := range []struct {
name string
dump bool
web bool
}{
{"clickable", dump.clickable, web.clickable},
{"enabled", dump.enabled, web.enabled},
{"editable", dump.editable, web.editable},
{"scrollable", dump.scrollable, web.scrollable},
{"positiveBounds", dump.positiveBounds, web.positiveBounds},
} {
if fact.dump != fact.web {
t.Errorf(
"%q (<%s>): the hierarchy dump derives %s=%v, the web runtime "+
"derives %s=%v",
row.id,
dump.tag,
fact.name,
fact.dump,
fact.name,
fact.web,
)
}
}
}
}
func enumeratedIDs(rows []factRow) []string {
ids := make([]string, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.id)
}
return ids
}
func repoRootDir(t *testing.T) string {
t.Helper()
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot resolve caller path")
}
return filepath.Clean(
filepath.Join(filepath.Dir(thisFile), "..", "..", ".."),
)
}
+72
View File
@@ -0,0 +1,72 @@
<!doctype html>
<html id="page">
<head id="page-head">
<meta id="page-charset" charset="utf-8" />
<title id="page-title">fact parity</title>
<style id="page-style">
:root {
--frame-w: 420px;
--frame-h: 640px;
}
body {
margin: 0;
}
#scroller {
width: 320px;
height: 120px;
overflow: auto;
}
#scroller-content {
height: 600px;
}
#sideways {
width: 320px;
height: 40px;
overflow: auto;
}
#sideways-content {
width: 900px;
height: 20px;
}
#fits {
width: 320px;
height: 120px;
overflow: auto;
}
#fits-content {
height: 40px;
}
#collapsed {
display: none;
}
#filler {
height: 900px;
}
</style>
</head>
<body id="page-body">
<button id="save">save</button>
<button id="cancel" disabled>cancel</button>
<a id="link" href="#detail">detail</a>
<select id="choice">
<option id="choice-first">first</option>
</select>
<input id="amount" type="text" value="10" />
<input id="agree" type="checkbox" />
<textarea id="notes"></textarea>
<div id="bio" contenteditable="true">bio</div>
<div id="menu" role="button">menu</div>
<div id="attribute-click" onclick="void 0">attribute click</div>
<div id="delegating-root">delegating root</div>
<div id="plain">plain</div>
<div id="edit-text-field" class="EditTextField">styled</div>
<span id="collapsed">collapsed</span>
<div id="scroller"><div id="scroller-content"></div></div>
<div id="sideways"><div id="sideways-content"></div></div>
<div id="fits"><div id="fits-content"></div></div>
<div id="filler"></div>
<script id="page-script">
document.getElementById("delegating-root").onclick = function () {};
</script>
</body>
</html>
+1 -1
View File
@@ -68,7 +68,7 @@ func TranslateStringSelector(selector string) (string, bool, error) {
// - everything else passes through, including non-ASCII
//
// Callers should not pass this output into identifier contexts (class names,
// tag names) — use an attribute selector form (`[class~="..."]`) instead.
// tag names). Use an attribute selector form (`[class~="..."]`) instead.
func cssEscape(value string) string {
var builder strings.Builder
builder.Grow(len(value))
+3 -3
View File
@@ -45,9 +45,9 @@ func TestThunk_TransitionFromHoldToViolate(t *testing.T) {
wantSequence := []Verdict{
VerdictHolds, // true
VerdictHolds, // true
VerdictViolated, // false — latches
VerdictViolated, // true after violation — still violated
VerdictViolated, // true after violation — still violated
VerdictViolated, // false: latches
VerdictViolated, // true after violation: still violated
VerdictViolated, // true after violation: still violated
}
for index, want := range wantSequence {
got := evaluator.Observe()
+1 -1
View File
@@ -34,7 +34,7 @@ const (
// screenshot, picks ONE number, and echoes that action so a mismatch can be
// caught. The app-specific description (spec instructions) is appended.
const llmSystemPrompt = "You are exercising a UI to find bugs. Each turn you get a screenshot and a numbered list of concrete actions, each with a weight hinting how much the test author wants it exercised (higher = more). " +
"Pick the ONE action most likely to make progress or expose a defect. Bugs often hide in repeated or rapid actions, so once a screen works, deliberately stress it — for example submitting the same form twice in a row to check it is not applied more than once — rather than only advancing. " +
"Pick the ONE action most likely to make progress or expose a defect. Bugs often hide in repeated or rapid actions, so once a screen works, deliberately stress it (for example submitting the same form twice in a row to check it is not applied more than once) rather than only advancing. " +
"Respond with your reasoning, the chosen number, and chosen_action copied verbatim from that line. For a typing action, also provide the text to enter."
// llmSource selects each step's action with an OpenAI-compatible vision model
+96
View File
@@ -16,6 +16,8 @@ import (
"strings"
"testing"
"github.com/priyanshujain/sanderling/internal/driver"
mockdriver "github.com/priyanshujain/sanderling/internal/driver/mock"
"github.com/priyanshujain/sanderling/internal/hierarchy"
"github.com/priyanshujain/sanderling/internal/llmclient"
"github.com/priyanshujain/sanderling/internal/verifier"
@@ -276,6 +278,100 @@ func TestPickSourcesSeededByDefault(t *testing.T) {
}
}
// seededFixtureSpec declares no generator = llm(...), so --generator llm has
// nothing to build a picker from.
const seededFixtureSpec = `
import { always, taps, typing, weighted } from "@sanderling/spec";
globalThis.properties = { ok: always(() => true) };
globalThis.actions = weighted([1, taps], [1, typing]);
`
func newSeededVerifier(t *testing.T) *verifier.Verifier {
t.Helper()
verifierInstance, err := verifier.New()
if err != nil {
t.Fatal(err)
}
if err := verifierInstance.Load(bundleSpec(t, seededFixtureSpec)); err != nil {
t.Fatal(err)
}
if _, ok := verifierInstance.LLMConfig(); ok {
t.Fatal("seeded fixture spec must not register an llm action backend")
}
return verifierInstance
}
// TestPickSourcesRejectsLLMWithoutSpecConfig pins the abort. Falling back to the
// seeded picker here completes the run, writes a well-formed output directory,
// and records it under the requested arm, so a campaign cell silently reports
// the wrong policy's numbers.
func TestPickSourcesRejectsLLMWithoutSpecConfig(t *testing.T) {
for name, activeDriver := range map[string]driver.DeviceDriver{
"native": nil,
"web": &webMockDriver{Driver: mockdriver.New()},
} {
t.Run(name, func(t *testing.T) {
action, extractor, err := pickSources(Options{
Driver: activeDriver,
Verifier: newSeededVerifier(t),
Generator: "llm",
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err == nil {
t.Fatalf("pickSources = (%T, %T), want an error", action, extractor)
}
if action != nil || extractor != nil {
t.Errorf("sources = (%v, %v), want both nil alongside the error", action, extractor)
}
if !strings.Contains(err.Error(), "generator = llm(...)") {
t.Errorf("error = %q, want it to name the missing spec declaration", err)
}
})
}
}
// TestPickSourcesOnWebComposesLLMWithWebExtractors covers the second half of the
// same claim: the picker is chosen by --generator and the extractor source by
// the driver, so the llm policy runs on web instead of being silently replaced
// by the V8 picker.
func TestPickSourcesOnWebComposesLLMWithWebExtractors(t *testing.T) {
fake := newFakeOpenRouter(t)
_, verifierInstance := newLLMSource(t, fake)
action, extractor, err := pickSources(Options{
Driver: &webMockDriver{Driver: mockdriver.New()},
Verifier: verifierInstance,
Generator: "llm",
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatalf("pickSources: %v", err)
}
if _, ok := action.(*llmSource); !ok {
t.Errorf("action source = %T, want *llmSource on web with --generator llm", action)
}
if _, ok := extractor.(webSource); !ok {
t.Errorf("extractor source = %T, want webSource so overrides still come from V8", extractor)
}
}
func TestPickSourcesOnWebSeededKeepsBothOnV8(t *testing.T) {
action, extractor, err := pickSources(Options{
Driver: &webMockDriver{Driver: mockdriver.New()},
Verifier: newSeededVerifier(t),
Generator: "seeded",
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatalf("pickSources: %v", err)
}
if _, ok := action.(webSource); !ok {
t.Errorf("action source = %T, want webSource for the seeded web path", action)
}
if _, ok := extractor.(webSource); !ok {
t.Errorf("extractor source = %T, want webSource for the seeded web path", extractor)
}
}
func TestLLMSourceDrivesExecutedActions(t *testing.T) {
fake := newFakeOpenRouter(t)
source, verifierInstance := newLLMSource(t, fake)
+36 -26
View File
@@ -3,6 +3,7 @@ package runner
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -64,39 +65,48 @@ func (s webSource) ExtractorOverrides(ctx context.Context) (map[int]json.RawMess
// pickSources selects the runtime's action and extractor sources ONCE at setup
// from the driver's capabilities, the --generator flag, and the spec, so the
// step loop never type-asserts. With --generator llm and a spec-declared
// generator = llm({...}) it constructs the chat-completions client and returns
// an llmSource for selection while extractor overrides still come from the goja
// path. Otherwise the seeded goja picker drives.
// step loop never type-asserts.
//
// The two axes are independent. The DRIVER decides where extractor overrides
// come from: the web path reads the values its extractors computed in V8, every
// other path has none. The --generator flag decides who picks the action, and
// the llm picker composes with either extractor source because it reads the
// goja-side candidate list and screenshot, both of which the runner populates on
// every platform.
//
// A missing generator = llm(...) is fatal rather than a fallback to the seeded
// picker. Falling back silently corrupts a comparison campaign: the run
// completes and the output directory looks correct while the wrong policy drove
// it.
func pickSources(options Options) (ActionSource, ExtractorSource, error) {
seeded := ActionSource(gojaSource{verifier: options.Verifier})
extractor := ExtractorSource(gojaSource{verifier: options.Verifier})
if web, ok := options.Driver.(driver.WebDriver); ok {
source := webSource{web: web}
return source, source, nil
seeded, extractor = source, source
}
if options.Generator != "llm" {
return seeded, extractor, nil
}
config, ok := options.Verifier.LLMConfig()
if !ok {
return nil, nil, errors.New("--generator llm: the spec declares no generator = llm(...); add one to the spec or drop --generator llm")
}
client, err := llmclient.New()
if err != nil {
return nil, nil, fmt.Errorf("llm action generator: %w", err)
}
logger := options.Logger
if logger == nil {
logger = slog.Default()
}
if options.Generator == "llm" {
config, ok := options.Verifier.LLMConfig()
if !ok {
logger.Warn("--generator llm requested but spec declares no generator = llm(); using the seeded picker")
} else {
client, err := llmclient.New()
if err != nil {
return nil, nil, fmt.Errorf("llm action generator: %w", err)
}
action := &llmSource{
verifier: options.Verifier,
client: client,
model: config.Model,
instructions: config.Instructions,
logger: logger,
history: newActionHistory(llmHistorySize),
}
return action, gojaSource{verifier: options.Verifier}, nil
}
action := &llmSource{
verifier: options.Verifier,
client: client,
model: config.Model,
instructions: config.Instructions,
logger: logger,
history: newActionHistory(llmHistorySize),
}
source := gojaSource{verifier: options.Verifier}
return source, source, nil
return action, extractor, nil
}
+26 -2
View File
@@ -39,11 +39,35 @@ func Extract(dir string) (string, error) {
}
}
if err := os.WriteFile(jarPath, embeddedJAR, 0o644); err != nil {
if err := writeAtomic(jarPath, embeddedJAR); err != nil {
return "", fmt.Errorf("write %s: %w", jarPath, err)
}
if err := os.WriteFile(checksumPath, []byte(checksum), 0o644); err != nil {
if err := writeAtomic(checksumPath, []byte(checksum)); err != nil {
return "", fmt.Errorf("write checksum: %w", err)
}
return jarPath, nil
}
// writeAtomic publishes content at path through a rename, so a reader never
// observes a partial file. dir is shared between every sanderling process on
// the host, so a campaign running one worker per device has several of them
// extracting the same JAR at once on a cold host; a plain write let one
// process spawn a JVM against another's half-written file.
func writeAtomic(path string, content []byte) error {
temporary, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.partial")
if err != nil {
return err
}
defer os.Remove(temporary.Name())
if _, err := temporary.Write(content); err != nil {
temporary.Close()
return err
}
if err := temporary.Close(); err != nil {
return err
}
if err := os.Chmod(temporary.Name(), 0o644); err != nil {
return err
}
return os.Rename(temporary.Name(), path)
}
@@ -6,8 +6,11 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
@@ -89,3 +92,76 @@ func TestExtract_RewritesIfChecksumMissing(t *testing.T) {
t.Errorf("checksum should have been written: %v", err)
}
}
// TestExtract_ReadersNeverSeeAPartialJAR covers the cold-host case a parallel
// campaign hits: every worker process extracts into the same shared directory
// under os.TempDir, and one of them spawns a JVM against the JAR while another
// is still writing it. A plain write truncates the file in place, so the
// reader gets a short JAR and the JVM dies on a corrupt archive.
func TestExtract_ReadersNeverSeeAPartialJAR(t *testing.T) {
directory := t.TempDir()
want := EmbeddedSHA256()
jarPath, err := Extract(directory)
if err != nil {
t.Fatal(err)
}
checksumPath := jarPath + ".sha256"
stop := make(chan struct{})
torn := make(chan string, 1)
var readers sync.WaitGroup
for range 4 {
readers.Add(1)
go func() {
defer readers.Done()
for {
select {
case <-stop:
return
default:
}
content, err := os.ReadFile(jarPath)
if err != nil {
continue
}
sum := sha256.Sum256(content)
if got := hex.EncodeToString(sum[:]); got != want {
select {
case torn <- fmt.Sprintf("read %d bytes, sha256 %s", len(content), got):
default:
}
return
}
}
}()
}
for range 8 {
// Dropping the checksum is what a cold host looks like: no extraction
// has been recorded, so every caller writes the JAR again.
if err := os.Remove(checksumPath); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
if _, err := Extract(directory); err != nil {
t.Fatal(err)
}
}
close(stop)
readers.Wait()
select {
case detail := <-torn:
t.Fatalf("a reader observed a partial JAR while another caller extracted: %s", detail)
default:
}
entries, err := os.ReadDir(directory)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if strings.Contains(entry.Name(), ".partial") {
t.Errorf("Extract left a staging file behind: %s", entry.Name())
}
}
}
+39 -10
View File
@@ -31,9 +31,13 @@ type Options struct {
IosAppPath string
AndroidAppPath string
Duration time.Duration
MaxSteps int
Seed int64
Output string
ClearData bool
// Arm labels the experiment cell this run belongs to and is recorded in
// meta.json so a directory of runs can be attributed to a cell.
Arm string
// Generator selects the action picker: "llm" or the default seeded picker.
Generator string
@@ -47,6 +51,32 @@ type Options struct {
}
// Execute runs the full test pipeline: bundle, launch app, verify properties.
// buildRunMeta assembles the run's meta.json. Model and Instructions are
// recorded only when the LLM picker is the one that will actually run, so a
// spec that declares generator = llm() but is run under the seeded picker does
// not label its trace with a model it never called.
func buildRunMeta(options Options, bundleSHA256 string, seed int64, host string, llmConfig verifier.LLMConfig, hasLLMConfig bool) trace.Meta {
meta := trace.Meta{
Seed: seed,
SpecPath: options.Spec,
BundleSHA256: bundleSHA256,
Platform: options.Platform,
BundleID: options.BundleID,
StartedAt: time.Now().UTC(),
SanderlingVersion: "0.0.1",
Arm: options.Arm,
Generator: options.Generator,
MaxSteps: options.MaxSteps,
DurationMillis: options.Duration.Milliseconds(),
Host: host,
}
if options.Generator == "llm" && hasLLMConfig {
meta.Model = llmConfig.Model
meta.Instructions = llmConfig.Instructions
}
return meta
}
func Execute(ctx context.Context, options Options, stdout io.Writer) error {
switch options.Platform {
case "android":
@@ -140,15 +170,9 @@ func Execute(ctx context.Context, options Options, stdout io.Writer) error {
return fmt.Errorf("trace writer: %w", err)
}
defer traceWriter.Close()
meta := trace.Meta{
Seed: seed,
SpecPath: options.Spec,
BundleSHA256: bundle.SHA256,
Platform: options.Platform,
BundleID: options.BundleID,
StartedAt: time.Now().UTC(),
SanderlingVersion: "0.0.1",
}
hostname, _ := os.Hostname()
llmConfig, hasLLMConfig := verifierInstance.LLMConfig()
meta := buildRunMeta(options, bundle.SHA256, seed, hostname, llmConfig, hasLLMConfig)
if err := traceWriter.WriteMeta(meta); err != nil {
return fmt.Errorf("trace meta: %w", err)
}
@@ -159,9 +183,14 @@ func Execute(ctx context.Context, options Options, stdout io.Writer) error {
}()
fmt.Fprintf(stdout, "trace dir: %s\n", runDirectory)
fmt.Fprintf(stdout, "running for %s (seed=%d)\n", options.Duration, seed)
if options.MaxSteps > 0 {
fmt.Fprintf(stdout, "running for %s or %d steps, whichever comes first (seed=%d)\n", options.Duration, options.MaxSteps, seed)
} else {
fmt.Fprintf(stdout, "running for %s (seed=%d)\n", options.Duration, seed)
}
summary, err := runner.Run(ctx, runner.Options{
Duration: options.Duration,
MaxSteps: options.MaxSteps,
IdleTimeout: 1 * time.Second,
BundleID: options.BundleID,
Driver: activeDriver,
+50
View File
@@ -5,6 +5,9 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/priyanshujain/sanderling/internal/verifier"
)
func TestResolveSeed_UsesConfiguredWhenNonZero(t *testing.T) {
@@ -181,3 +184,50 @@ func TestResolveSpecAPIPath_ReturnsEmptyWhenMissing(t *testing.T) {
t.Fatalf("got %q, want empty (no sanderling source tree reachable)", got)
}
}
func TestBuildRunMeta_RecordsArmMembership(t *testing.T) {
options := Options{
Spec: "spec.ts",
BundleID: "com.example",
Platform: "android",
Duration: 3 * time.Minute,
MaxSteps: 300,
Arm: "llm-visible-text",
Generator: "llm",
}
meta := buildRunMeta(options, "deadbeef", 7, "farm-01",
verifier.LLMConfig{Model: "claude-sonnet-5", Instructions: "exercise the outbox"}, true)
if meta.Arm != "llm-visible-text" || meta.Generator != "llm" {
t.Errorf("arm membership: got arm=%q generator=%q", meta.Arm, meta.Generator)
}
if meta.Model != "claude-sonnet-5" || meta.Instructions != "exercise the outbox" {
t.Errorf("llm config: got model=%q instructions=%q", meta.Model, meta.Instructions)
}
if meta.MaxSteps != 300 || meta.DurationMillis != 180000 {
t.Errorf("budget: got maxSteps=%d durationMillis=%d", meta.MaxSteps, meta.DurationMillis)
}
if meta.Host != "farm-01" || meta.Seed != 7 {
t.Errorf("host and seed: got host=%q seed=%d", meta.Host, meta.Seed)
}
}
func TestBuildRunMeta_OmitsModelWhenSeededPickerRuns(t *testing.T) {
options := Options{Platform: "android", Generator: "seeded", Duration: time.Minute}
meta := buildRunMeta(options, "deadbeef", 1, "farm-01",
verifier.LLMConfig{Model: "claude-sonnet-5", Instructions: "hunt bugs"}, true)
if meta.Model != "" || meta.Instructions != "" {
t.Errorf("a seeded run must not be labelled with a model it never called: model=%q instructions=%q",
meta.Model, meta.Instructions)
}
}
func TestBuildRunMeta_OmitsModelWhenSpecDeclaresNoLLMGenerator(t *testing.T) {
options := Options{Platform: "android", Generator: "llm", Duration: time.Minute}
meta := buildRunMeta(options, "deadbeef", 1, "farm-01", verifier.LLMConfig{}, false)
if meta.Model != "" {
t.Errorf("model recorded without a spec-declared llm generator: %q", meta.Model)
}
}
+19 -1
View File
@@ -92,7 +92,7 @@ type Action struct {
// LLMChoice is the 1-based number the model picked from the candidate list;
// LLMChosenAction is the action description it echoed for that number. The
// runner strict-skips when the echo disagrees with the numbered entry, so on
// a recorded action the two always agree — the replay UI shows them to
// a recorded action the two always agree; the replay UI shows them to
// confirm the reasoning matched the executed action.
LLMChoice int `json:"llm_choice,omitempty"`
LLMChosenAction string `json:"llm_chosen_action,omitempty"`
@@ -126,6 +126,24 @@ type Meta struct {
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
SanderlingVersion string `json:"sanderling_version"`
// Arm labels the experiment cell this run belongs to, set from --arm. A
// directory of runs cannot be attributed to a cell after the fact without
// it, which makes any factorial computed from such a directory unanalysable.
Arm string `json:"arm,omitempty"`
// Generator, Model and Instructions record which picker ran and how it was
// configured. Two runs that differ in any of these are different arms.
Generator string `json:"generator,omitempty"`
Model string `json:"model,omitempty"`
Instructions string `json:"instructions,omitempty"`
// MaxSteps and DurationMillis are the budget the run was given, which has
// to be identical across arms for a comparison to mean anything.
MaxSteps int `json:"max_steps,omitempty"`
DurationMillis int64 `json:"duration_millis,omitempty"`
// Host is the machine that produced the run. Campaigns are split across
// several hosts, so a per-host effect has to be detectable rather than
// invisible.
Host string `json:"host,omitempty"`
}
type Writer struct {
+63
View File
@@ -429,3 +429,66 @@ func readLines(t *testing.T, path string) []string {
}
return lines
}
func TestWriteMeta_ArmMembershipRoundTrip(t *testing.T) {
directory := t.TempDir()
writer, err := NewWriter(directory)
if err != nil {
t.Fatal(err)
}
defer writer.Close()
meta := Meta{
Seed: 7,
SpecPath: "spec.ts",
BundleSHA256: "deadbeef",
Platform: "android",
BundleID: "com.example",
StartedAt: time.Date(2026, 8, 12, 10, 0, 0, 0, time.UTC),
SanderlingVersion: "0.0.1",
Arm: "llm-visible-text",
Generator: "llm",
Model: "claude-sonnet-5",
Instructions: "exercise the outbox",
MaxSteps: 300,
DurationMillis: 180000,
Host: "emulator-farm-01",
}
if err := writer.WriteMeta(meta); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(filepath.Join(directory, "meta.json"))
if err != nil {
t.Fatal(err)
}
var got Meta
if err := json.Unmarshal(body, &got); err != nil {
t.Fatalf("meta.json is not valid JSON: %v\n%s", err, body)
}
if got != meta {
t.Errorf("meta round-trip mismatch:\n got: %+v\nwant: %+v", got, meta)
}
}
func TestWriteMeta_OmitsArmMembershipWhenUnset(t *testing.T) {
directory := t.TempDir()
writer, err := NewWriter(directory)
if err != nil {
t.Fatal(err)
}
defer writer.Close()
if err := writer.WriteMeta(Meta{Seed: 1, Platform: "web"}); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(filepath.Join(directory, "meta.json"))
if err != nil {
t.Fatal(err)
}
for _, key := range []string{"arm", "generator", "model", "instructions", "max_steps", "duration_millis", "host"} {
if strings.Contains(string(body), `"`+key+`"`) {
t.Errorf("meta.json carries %q when unset:\n%s", key, body)
}
}
}