mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-02 02:11:29 +00:00
* fix(eval): cut skill-evolution wall clock without shrinking the gate
Reuse matching incumbent/CE cells, sanitize each SHA once, and default
dispatch workers to 3 so weekly review generations finish inside the
EventBridge window. Cap the sweep from leftover instance uptime so a
Friday dispatch still uploads evidence.
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf(eval): pipeline graph setup and correct the wall-clock cost model
The evolution sweep paid `sanitize` + `analyze --pdg --index-only` for every
unique task SHA on the critical path, one at a time, with nothing overlapping.
`_run_sweep` now starts the next unpaid SHA's clone template and graph snapshot
on a prefetch thread as soon as the current task's cells are dispatched, so
every SHA but the first hides behind a paid session wave. The thread is joined
before that SHA is used and before the trees tempdir is torn down, and a
prefetch failure is recorded against the SHA exactly as an inline failure is.
Tasks whose cells are all reusable comparator rows are not prefetched: they
never build a graph, so priming one would be pure cost.
Adds `measure_evolution_cost.py`, the cost model behind these numbers. It reads
the review corpus, the evolve defaults, and the workflow's workers default —
it does not start a session. Its first version charged `copy_isolated_tree`
once per paid cell, serially. `run_cell` clones inside its own pool worker, so
the clones in a wave overlap and only one is on the critical path per wave;
the model now charges `ceil(cells / workers)` waves.
Estimated review generation at workers=3: cold 21570s, weekly 7710s.
Wall clock is quantised by `ceil(cells_per_task / workers)`. A cold review task
is 9 cells, so workers=4 buys the wall clock of workers=3 and pays host
contention for it. Documented in the workflow's rollout checklist.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf(eval): price the benchmark against measured cell durations
The cost model assumed every cell runs the 1140s mean. Cells are not uniform:
the 41 rows in Actions run 33912693948's artifact are 826s at the median,
1262s at the mean, 2976s at p90, with two pinned at the 5400s session ceiling.
A wave waits for its slowest cell, so a mean understates every concurrent
schedule — the previous model called workers=3 cold 5.99h when the same
schedule against real durations is 10.33h.
session_durations.json carries the sample in submission order with its
provenance and its caveat: every cell in that run returned unusable evidence,
so the durations are real but a clean run may sit lower. It is the only live
artifact; the 2026-07-22 green run's has expired.
The model now simulates the schedule cell by cell rather than multiplying a
mean by a wave count, averaged over all 41 rotations of the sample so no
single alignment between sample order and cell index decides the answer. It
prices today's barrier (wave_makespan) against a continuously fed pool
(fed_makespan) and reports both, and it charges the proposer session — one
per generation, measured at 344.7s — which it had been omitting entirely.
Measurement only; no runtime behaviour changes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf(eval): price arms separately and stop inventing setup constants
Two errors in the model, both found by auditing it against the artifact it
claims to describe.
The arms are not interchangeable. `candidate_review` runs 1416s at the mean
against `review`'s 1204s and `ce_review`'s 1176s, and the weekly lane pays the
candidate arm and nothing else — reuse skips both incumbents. Pricing weekly
from a pooled sample charged it for arms it never runs: weekly is 4.59h, not
the 3.65h a pooled sample reported. Cells are also submitted run-major and
arm-minor, so at workers=3 every wave holds one cell of each arm and the
slowest arm sets the wave; the model now builds cells in that order.
The setup constants were invented. GRAPH_ANALYZE_SECONDS=600 and
TEMPLATE_SANITIZE_SECONDS=180 charged 3900s of per-SHA setup for a cold run —
more than the entire non-session time of the source run, which was 2541s for
41 cells and 5 SHAs. `duration_s` is the sum of a cell's Claude sessions
(runner_sessions.py), so that 2541s residual is every clone, graph build,
sandbox and teardown the sweep paid. The model now charges the measured
residual per cell, 62.0s, and no longer credits clone templates or graph
prefetch: both landed after that run and there is no measurement of them yet.
The residual bounds what they can be worth.
Cold 37452s (10.40h), weekly 16541s (4.59h), against a fed pool at 31683s and
16541s. Measurement only; no runtime behaviour changes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf(eval): charge sweep overhead where more workers cannot dissolve it
Three defects, found by auditing the model against the artifact again.
The overhead was charged inside the schedule. session_durations.json claimed
the residual was charged "per cell and serially - the pessimistic reading",
but task_cells folded it into each cell's duration, where the pool then
divided it by the worker count. The residual mixes per-cell work the pool
really does divide with per-SHA graph setup it cannot, and the artifact cannot
separate them, so it now sits outside the schedule: cold 11.09h, not 10.40h.
Alignment averaging weighted the shortest sample twice. The arm samples are 13,
14 and 14 long and the average ran over max()=14 offsets, so candidate_review's
first cell was counted twice and its last never. Averaging over lcm()=182
offsets weights every arm's sample evenly.
The wall assumed all 54 cells run. Replaying the sample's own error_kind
sequence through today's systemic_outage_streak trips the outage breaker at
cell 5 of 41. The source run executed all 41, so its runner did not break on
that sequence, but the current one would: these numbers price a HEALTHY sweep,
and a sweep with the sample's failure profile never reaches them. Stated on
generation_seconds and recorded next to the sample it qualifies.
Measurement only; no runtime behaviour changes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(eval): give the review agent somewhere it can actually write
Every review cell in the last recorded generation returned unusable evidence.
Not some — all 41, across all three arms and all six tasks, at $3653 for the
run. The transcripts say why, 127 times across 35 of 35 sessions:
EROFS: read-only file system,
open '/workspace/review-output.json.tmp.2.90a76e583b0c'
The review arm mounted the artifact as a writable FILE at
/workspace/review-output.json while binding /workspace read-only. The Write
tool writes atomically: it creates `<target>.tmp.<n>.<hex>` beside the target
and renames it. The parent was read-only, so the temp create failed and the
artifact was never written. A writable file inside a read-only directory is
not writable to anything that writes atomically. Agents tried
/proc/self/root/workspace/... and /proc/1/root/workspace/... to get around it;
all 41 artifacts came back 0 bytes.
The artifact now lives in its own writable directory bound at /review-output,
outside the workspace. That is what a rename needs, and it lets the workspace
get stricter rather than looser: the review phase may now change nothing there
at all (enforce_phase_workspace gained allowed_artifact=None), where before it
was entitled to one path inside it. The file is no longer pre-created — the
agent writes it, and absence is now meaningful evidence.
parse_review_output reported every one of these as "review output is not valid
UTF-8 JSON". The file was empty, and its except folded OSError, UnicodeError
and JSONDecodeError into that one string, so a sandbox that made writing
impossible was indistinguishable from an encoding fault. That is why this read
as an agent-quality problem for fifteen consecutive non-green runs. Each cause
now names itself: never written, empty, not valid UTF-8, not valid JSON with
the decoder's position. run_arm also keeps the FIRST error_detail, as it
already did for error_kind, so a phase-boundary violation is no longer buried
under the parse failure it causes.
The test double conflated sandbox.private_root with the clone, which put the
artifact directory inside the workspace and would have hidden the stricter
check. Regression tests pin the mount shape in the generated bwrap argv, the
contract path in the prompt, the four parse diagnostics, and the
untouched-workspace contract.
Verified by unit tests only: this container has unprivileged user namespaces
disabled, so bwrap cannot run here and the mount was not exercised end to end.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(review): close the artifact path in every layer that gates it
Code review of this branch found the relocated review artifact was fixed in the
bwrap mount and nowhere else. Four independent layers decide whether the agent
can write it, and three still named the old location.
Claude Code applies its own filesystem policy to its own tools, and
build_claude_settings listed only /workspace, /tmp and /home/agent under
allowWrite with denyRead ["/"]. The artifact used to live under /workspace, so
this list was correct until it moved. SANDBOX_REVIEW_OUTPUT is now in allowWrite
and allowRead; without it the bwrap bind grants a write the CLI then refuses.
The task corpus still ran `test -s review-output.json` from the workspace, in a
separate sandbox invocation that never sees the artifact mount. Every review
cell would have been stamped verify-failed with resolved=False no matter how
good the review was, which also made those rows permanently unreusable and so
silently disabled this branch's own comparator reuse for review arms. The verify
and hidden-oracle commands now read the location from
GITNEXUS_BENCH_REVIEW_OUTPUT and get the directory bound read-only, mirroring
the mount-plus-env-var shape _run_hidden_oracle already used.
host_text and host_path did not translate the new path, so the host-unsafe
backend told the agent to write somewhere that exists on neither backend.
Adding the mapping exposed a second defect: host_text substituted every
occurrence of a target, and "/review-output" appears twice in
"/review-output/review-output.json" - once as the directory and once inside the
filename. Matching is now anchored to a path boundary.
Comparator reuse had three ways to accept evidence it should have rejected. A
row with no runtime_digest passed the drift lock because the guard only compared
when both sides were bound, and the branch's own test asserted that as correct;
absence is now a mismatch and the test states the rule. materialize_reused_row
overwrote recorded_at with the copy time while the age check read that field, so
a row copied forward each generation refreshed its own clock and never aged out;
the first measurement time is now preserved and aged against. A future-dated
stamp passed a one-sided bound and is now rejected as corrupt.
RUNTIME_DIGEST never reached the runner at all: runner_environment builds a
fixed dict and process_control replaces the child environment wholesale, so the
digest the workflow exports was dropped and the lock it feeds was inert. The
instance-window deadline was also checked only after run_proposer returned,
buying a proposal the generation had no room to benchmark.
The graph prefetch thread was started without copy_context, so it never saw the
cancellation ContextVar the rest of the sweep shares, and the outage breaker
returned without setting cancel_event - together, a tripped breaker would block
on joining a prefetch that was never told to stop. Both fixed, with outage
checked before cancellation at the two exits so an outage keeps exit 1 instead
of becoming a Ctrl-C's 130.
Both bwrap canaries that actually execute a write still bound the pre-fix shape
against a file this branch no longer creates, so they would have errored rather
than caught anything. They now bind the directory and write atomically - temp
file beside the target, then rename - which is the exact operation that failed
with EROFS. A source-text assertion over inspect.getsource(run_arm) was replaced
with one that inspects the real mount, and a wall-clock assertion was pinned to
a fixed monotonic clock.
Not applied, and why: binding task-asset and dependency digests into comparator
reuse needs asset snapshots prepared before the reuse decision rather than
inside the per-task loop, and shipping the comparison without that would add a
guard that silently never fires. Forcing a paid canary cell per incumbent arm
and folding reused rows into the outage streak are behaviour decisions, not
fixes. Clone-template reuse still has no test. The cost model's per-cell
residual still shrinks with arm count, overstating weekly savings by at most the
2541s residual; the docstring now says so rather than inventing a split.
585 eval tests pass, ruff clean, 29 workflow contract tests pass. The two
test_model_gateway.py failures are pre-existing and fail on main.
* fix(review): bind reuse to its environment and keep the health canary real
Applies the five findings the previous review round left open.
Comparator reuse ignored the environment a row was measured in. TaskReuseBinding
carried the task and oracle identity but not the task-asset or sandbox-dependency
digests, and this branch itself changes sandbox_dependencies in the review
corpus - so a reused comparator could be measured against one dependency set and
compared against a candidate built on another, handing the gate a false
comparison. Closing it needed the digests to exist before the reuse decision, so
asset snapshots are now prepared for every task up front instead of lazily
inside the per-task loop. That also removes the concurrent TaskAssetCache.prepare
the prefetch thread could otherwise race, which the file's own "plain dict,
read-then-write race" comment warned about. Both digests fail closed on either
side, matching the runtime digest.
The broken-incumbent canary could not fire when reuse was working. It read
`resolved`, which counts reused rows, so an arm whose cells were all reused
always looked healthy - in precisely the run where a broken environment would go
unnoticed. aggregate now also reports `resolved_fresh` and the canary reads it.
That count would be vacuous if an arm were reused end to end, so the sweep keeps
one paid cell per incumbent arm and says which one it kept.
Reused rows did not participate in the outage streak, so a run of failures could
carry across them and trip on stale history. A reused success now resets the
streak the way a paid success does.
The cost model charged sweep overhead per cell, which credited a weekly
generation for shrinking work it still performs: it pays one arm instead of
three but builds exactly the same graphs. Overhead is charged per SHA now.
Weekly is 5.20h rather than the 4.80h the per-cell rate reported; cold is
10.86h. The residual still cannot be split between per-SHA and per-cell work
from one artifact, so session_durations.json records that assumption and the
direction it errs in, rather than leaving a number nobody can trace.
Clone-template reuse - the branch's core speedup, taken on essentially every
multi-cell sweep - now has a test that builds a real sanitized template, asserts
the cell runs against the copy with the template's HEAD, and fails if run_cell
re-clones. A second test asserting only on a namespace built inside the test was
written and deleted: it exercised nothing, which is the failure this review
round penalised elsewhere.
589 eval tests pass, ruff clean, 29 workflow contract tests pass. The two
test_model_gateway.py failures are pre-existing and fail on main.
* refactor(eval): consolidate duplicated harness logic after the review round
Simplification pass over the branch. Behavior-preserving throughout; three
reviewers, nine findings applied, two skipped.
The review-artifact block in _run_hidden_oracle was unreachable. That function
runs only in run_arm's non-review branch, while the directory it probes for is
created only in the review branch, and each sandbox serves exactly one arm - so
`review_artifact.parent.is_dir()` could never be true. It was added an hour
earlier to make the hidden oracle resolve the moved artifact; the oracle never
runs for review tasks, so the guard was dead on arrival. Deleting it also
removes the duplication it had with the verify-command wiring.
EXCLUDED_ERROR_KINDS is now one definition. runner.py and comparator_reuse.py
each carried the same six-member frozenset, kept in sync by a comment. Only one
direction is possible: runner already imports from comparator_reuse, so the
reverse import fails at module-init with a circular-import error. That is now
stated where the alias lives, so nobody tries it the other way.
ensure_task_graph and prefetch_next_graph shared ten keyword parameters, passed
through two call sites and forwarded whole between them. They now take a
GraphBuildEnv, mirroring TaskCellContext, which already bundles per-cell state
in this file. Its ready_keys() replaces an inline four-set union at the call
site.
Smaller consolidations: _sha256_file's hand-rolled chunk loop becomes
hashlib.file_digest (3.11+, already used in runner_artifacts); _copy_owner_only
reuses task_assets._write_all and COPY_CHUNK_BYTES instead of repeating the
short-write retry; its stat-then-open existence check becomes the O_EXCL failure
it was already relying on, which is atomic rather than merely narrow; and
runner_environment reads the digest through comparator_reuse.current_runtime_digest
instead of re-parsing the environment variable.
Three test docstrings summarised the branch's own history ("the branch's core
speedup", "the regression that produced fifteen runs") rather than the invariant
under test. Rewritten to state the constraint, which is what survives the merge.
Repaired the indentation left behind by the outage-streak edit and flattened the
prefetch dispatch from three nested conditionals to one.
Skipped: consolidating comparator_reuse._real_directory onto proposer_sandbox's
same-named helper - they differ, the sandbox one rejects any symlink in the
resolved path while this one checks only the leaf, so sharing it would tighten
behavior rather than preserve it. That needs a decision about which policy the
reuse path wants, not a simplification.
589 eval tests pass, ruff clean, 29 workflow contract tests pass. Unrelated and
pre-existing: two test_model_gateway.py failures, and
test_process_control.py::test_timeout_kills_term_ignoring_descendants_before_they_write,
which is a TERM-to-KILL timing flake (passes 2 of 3 in isolation) in a file this
branch does not touch.
* refactor(eval): name the reuse directory check for the promise it makes
The simplification pass left one finding open: comparator_reuse and
proposer_sandbox both defined `_real_directory`, same name and same shape, with
different guarantees. The sandbox one rejects every symlink hop in the path; the
reuse one checks only the leaf and resolves through parents. Sharing the name
invites a consolidation that would silently tighten one of them.
They should not be merged, so the name stops claiming they could be.
proposer_sandbox guards a mount root, where a symlink hop changes what an
untrusted session is handed. comparator_reuse guards a data directory whose
contents are already validated one file at a time - reads go through
_regular_file, which lstats and rejects symlinks, and writes through O_NOFOLLOW.
A symlinked parent therefore grants nothing those guards do not already cover,
while refusing one would reject a symlinked artifacts directory or macOS's /var
for no gain.
Renamed to _resolved_directory, with the reasoning recorded at the definition,
and a test that pins both halves: a symlinked parent is accepted and resolved, a
symlinked leaf is still refused. Behavior is unchanged.
591 eval tests pass, ruff clean. The two test_model_gateway.py failures are
pre-existing and fail on main.
* test(eval): measure the sweep scheduler instead of modelling it
measure_evolution_cost predicts wall clock from a model of what
sweep_task_cells does. This runs the real thing - real threads, the real wave
barrier, the real outage breaker - with only the paid agent session replaced by
a sleep, and times it.
Durations are the measured per-arm samples divided by 5000, so a 1416s cell
takes ~0.28s. The shape is kept on purpose: the median cell is 826s against a
5400s ceiling, and that spread is the entire reason a barrier costs anything.
Uniform random sleeps would erase the effect under test. All schedulers consume
one identical seeded plan, so a comparison cannot be an artifact of one of them
drawing luckier cells.
The model survives contact: it tracks real execution within about 10%, and
workers=1 - which runs without a pool at all - sits at 0.95, so the residual
above 1.0 at higher worker counts is per-wave thread overhead rather than a
modelling error. Two structural claims that were arithmetic are now observed.
Weekly is flat from workers=3: 3.59, 3.59, 3.59, 3.60, 3.59, 3.59 across w=3..8.
workers=4 buys nothing over workers=3 on cold, 7.68 against 7.78.
Two prototype schedulers are measured beside it, deliberately before any
production code exists. A continuously fed pool per task is worth more than the
model claimed on cold, -27.3% against a predicted -17.9%, and exactly nothing on
weekly, +0.0%, because a weekly task is one wave with nothing to feed. One pool
across all tasks beats both: -40.7% weekly and -42.9% cold at workers=3, rising
to -65.7% and -63.9% at workers=8. It also subsumes the fed pool, since packing
across tasks is a fed pool.
That reorders the backlog. Cross-task packing moves from second to first: it
dominates on both profiles, and it is the only thing that moves weekly at all.
Raising the worker count is worth nothing until it lands - under the barrier
weekly does not improve from w=3 to w=8, and speedup against serial is 1.58x for
three workers and only 2.40x for eight.
The bound on all of it: sleeping threads do not contend. Real sandboxed sessions
compete for CPU, page cache and disk, and the duration sample was itself
measured at workers=1, so it carries no contention either. These speedups are
upper bounds. The ordering is trustworthy because the schedulers were compared
under identical conditions; the magnitudes are not. The packed prototype is also
a bare ThreadPoolExecutor with no breaker folding, no per-task graph lifecycle
and no reuse binding - which is the actual cost of building it, and is not
measured here.
* test(eval): carry the sweep invariants into the packed prototype
The first packed prototype was a bare ThreadPoolExecutor. It reported -43% and
none of the invariants the shipped scheduler holds, so it priced an idea nobody
could ship. This one carries them: a global submission order continued across
task boundaries, in-order folding, the real outage breaker, and per-task graph
readiness gating behind a serial builder.
The fidelity check first reported the two schedulers tripping on different
cells, 17 against 16. That was my instrumentation, not a divergence -
sweep_task_cells folds an entire wave before it evaluates the breaker, so the
last cell folded is not the cell that tripped. With the harness mirroring the
breaker's own evaluation the two agree exactly, across failures starting at
cell 0, 4 and 12, with overrun inside the workers-1 bound the wave docstring
promises.
Two results worth the exercise.
Head-of-line blocking, not the barrier, is what a naive in-order design pays.
Holding submission to `workers` cells beyond the fold pointer leaves the
faithful scheduler at -8.1% cold and -2.7% weekly: one slow cell stalls the
pointer, the window cannot slide, and it reproduces the wave almost exactly.
That is the number to quote if anyone proposes the obvious implementation.
But the overrun bound turns out to be set by the worker count, not the window.
Only `workers` cells can be running when the breaker trips; everything queued
behind them short-circuits on the halt flag. Overrun is 3 at an unbounded
window exactly as at 6, and the trip cell never moves off 16. So H2 does not
have to trade breaker fidelity for speed - a wide window takes -42% with the
semantics intact. The tension I assumed was there is not, and window=12 already
captures 97% of it.
Still an upper bound: sleeping threads do not contend, and the sample was
measured at workers=1. What this establishes is that the invariants are
affordable, which was the thing blocking H2. Not built here: the trees tempdir
lifecycle, reuse-row binding, and the cancel_event path.
591 eval tests pass, ruff clean.
* test(eval): put the scheduler comparison under real CPU contention
Every Phase 2 number so far came from sleeping threads, which contend for
nothing, against a duration sample measured at workers=1, which contains no
contention either. That was the standing caveat on the whole result, so this
measures it.
A cell now waits for its API share and then burns a fixed number of sha256
rounds in a subprocess. Work-bounded rather than wall-clock bounded, so it takes
longer when cores are busy - that is the effect under test. A subprocess because
Python threads burning Python would measure the GIL rather than the machine.
Calibrated at 519k rounds/s, stable within 2% across three probes.
The first run of this was worthless and is recorded as such: on a 24-core host
with 3 to 6 workers nothing ever contends, since cpu_fraction 0.5 at 6 workers
is about 3 cores of demand out of 24. It measured an absence. Re-run pinned with
taskset to 4 and 2 cores.
The packing advantage survives. It holds between -40% and -47% across every host
size and CPU fraction tested, including a genuinely oversubscribed 2-core box at
cpu_fraction 0.5 with 6 workers.
But contention erodes packing more than it erodes waves, for a structural
reason: packing is what creates the concurrency. Moving from 24 cores to 2 at
cpu 0.5 and 6 workers, the faithful scheduler slows 13% while the wave slows
3.7%, and the gain narrows from 45.0% to 39.8%. Packing and a higher worker
count are therefore not independent wins - packing spends the contention
headroom first, so raising workers has to be re-argued after it lands rather
than added to it.
Three things this still does not measure, and they bound the result. The real
CPU fraction of a benchmark cell is a guess informed by roughly 180 tool calls
per session; nobody has profiled one. The evolution runner's core count decides
which column applies and is unknown here. And the burn is sha256, pure CPU,
while real cells run vitest and analyze, which are memory and IO heavy - so this
is a floor on contention, not a ceiling.
591 eval tests pass, ruff clean.
* perf(eval): add a packed sweep scheduler, and correct the bound I claimed for it
sweep_task_cells finishes one task before starting the next and drains a wave
before refilling it, so a task with fewer cells than workers leaves workers
idle and one slow cell stalls its whole wave. sweep_packed_cells feeds every
task's cells through a single pool instead. Measured against the review corpus
it is worth about 40% of a cold sweep, and it is the only change that moves a
seeded weekly run at all - there a task is three cells and a wave is never full.
The breaker keeps its exact meaning. Cells carry a total submission order
continued across task boundaries, a folder walks results in that order, and
consecutive systemic failures are counted there, so a doomed run aborts on the
same cell it would have under waves. Verified at three failure positions.
This commit also corrects a finding from the Phase 2 prototype. I claimed the
overrun bound was set by the worker count rather than the submission window,
and that packing therefore cost nothing in breaker fidelity. That was derived
from a window sweep that only ever injected failures at one position. Driving
the real function at other positions shows the halt flag does not bound overrun
at all: the folder walks in order, so a slow early cell lets workers race ahead
and the trip is detected after those cells have already paid. An unbounded
queue overran by 11 cells where waves overrun by 2.
So the window is load-bearing and the trade is real, measured at workers=3 with
failures injected at four positions:
window 3 -> -8% wall, overrun 2 (the wave scheduler's own bound)
window 6 -> -27% wall, overrun 4
window 12 -> -42% wall, overrun 9
window 54 -> -44% wall, overrun 11
Overrun is wasted paid sessions at roughly $70 each. The default multiplier is
2, keeping the worst case within twice the wave bound while taking most of the
gain; the curve is in the constant's comment so raising it is an informed
decision rather than a guess.
Not wired in yet: _run_sweep still calls sweep_task_cells per task. Moving the
per-task graph, trees tempdir and reuse binding out of that loop behind
await_ready is the larger and riskier half, and it belongs in its own change.
595 eval tests pass, ruff clean.
* fix(eval): judge harness health on execution, not on how many tasks resolved
broken_incumbent_arms infers "the environment is broken" from an arm resolving
zero tasks. That inference does not hold: a reviewer can be wrong about every
task in a hard corpus while every process, mount and capture worked perfectly.
Actions run 33962002890 is exactly that shape - 51 cells, all resolved=False
with error_kind=oracle-failed, median score 0.212, and a healthy harness.
Someone already knew this, and patched it by excluding review arms at the call
site. That leaves the unsound inference in place for workflow and
workflow_direct, and leaves review arms with no health check at all - so the
run that genuinely was broken, 33912693948, where the mount made an atomic
write impossible and all 41 artifacts came back empty, could not have been
caught here either.
So this replaces the inference rather than adding another exemption. aggregate
now classifies fresh rows into execution failures (the process or its tooling
did not complete), evidence failures (it completed but produced nothing
trustworthy or scoreable), and admissible measurements. An arm is unhealthy
only when it has fresh attempts, zero admissible measurements, and at least one
execution or evidence failure. Resolution count is no longer consulted. Arms
with only reused rows report current health as UNKNOWN rather than good.
With the inference corrected, review arms are checked again, which is what lets
the empty-artifact case be caught at all.
Deliberately unchanged: comparator reuse eligibility, quality denominators,
promotion thresholds, model settings, skill prompts and scheduler behaviour.
Failures that stop being called infrastructure failures still surface in the
counts and reasons - an agent-originated failure must not vanish from reporting
because it was reclassified. broken_incumbent_arms and its tests are left in
place; deleting behaviour belongs in its own change.
Seven regression tests, built from both runs' shapes and labelled as
reconstructed from logged observations, since 33962002890's results.jsonl did
not survive the instance shutdown. They pin: a badly-scoring reviewer is
healthy; an all-zero score is still a valid negative; empty artifacts are
unhealthy; one admissible cell keeps an arm healthy while its failures stay
visible; reused rows alone leave health unknown; reused successes do not mask
fresh failures; and a parseable artifact does not excuse a failed session.
602 eval tests pass, ruff clean.
* fix(eval): pin the health guard below the breaker, and stop calling mixed runs healthy
Two corrections to the health-classification patch.
The regression I wrote could not have proved what it claimed. A fixture of 41
empty artifacts aborts through the outage breaker long before finalization:
review-evidence-invalid is in SYSTEMIC_ERROR_KINDS and the limit is 5, so it
trips at cell 5 through the pre-existing path. It demonstrated failure
detection, not the new guard. The decisive test now uses ONE fresh unusable
cell, asserts the streak stays under the breaker threshold, and only then
requires finalization to abort - leaving the new check as the only thing that
can catch it. Removing the call makes that test fail; restoring it passes.
The accurate defect statement is narrower than the last message claimed. Review
arms were excluded from the final incumbent-health check while the consecutive-
failure breaker gave them separate, partial coverage. They were not unguarded.
Second: "one admissible cell plus two execution failures" was asserted as
healthy. That converts "not wholly unusable" into "ran reliably", which is how
a partly-broken sweep passes review. Arms now report UNKNOWN, OBSERVED_OK,
DEGRADED or UNUSABLE. Only UNUSABLE is fatal, so eligibility and promotion are
untouched - this changes what is reported, not what is allowed.
The guard is extracted as enforce_measurement_health so it can be driven
directly, and it now reports a status line per arm. It names no cause: an empty
artifact establishes that evidence is unusable, not that a mount rejected the
write, so it prints cause=undetermined rather than guessing EROFS. It still
runs after report.md and promotion.json are written, so a failing sweep leaves
its evidence behind.
ce_review is named explicitly at the call site. It is a comparator rather than
a candidate, so it is absent from CANDIDATE_ARMS.values(), and dropping the
review exclusion alone would have left it unclassified.
The wiring test reads _run_sweep's compiled code object for the referenced
global rather than matching source text. It is honest about its limit: it
proves the call exists and would catch its removal, but no test here drives
_run_sweep end to end, which needs bwrap and a sandbox.
broken_incumbent_arms is marked LEGACY and NON-AUTHORITATIVE with removal
tracked. It has no production caller.
608 eval tests pass, ruff clean. The two test_model_gateway.py failures are
test_locked_litellm_translates_messages_to_offline_responses and
test_openai_gateway_never_leaves_proxy_output_on_an_undrained_pipe; both fail
identically on origin/main in this environment, checked directly rather than
carried forward as an inherited label.
* fix(eval): review artifact path, evidence classification, comparator reuse
Extracted from the combined skill-evolution branch. This is the runtime change
set: everything that alters how a sweep executes and what it records. The
packed scheduler and its measurement harness were separated onto
perf/skill-evolution-packed-scheduler, which is purely additive.
Correctness. The review artifact was mounted as a writable FILE inside a
read-only workspace while the agent's Write tool writes atomically - temp file
beside the target, then rename - so the temp create failed EROFS and the
artifact was never written. Four layers gate that path and three named the old
location: the CLI's own allowWrite/allowRead policy, the task corpus verify
command run in its own sandbox invocation, and host_text/host_path for the
host-unsafe backend. Fixing the translator exposed a second defect, since
"/review-output" appears twice in "/review-output/review-output.json"; matching
is now anchored to a path boundary. parse_review_output folded OSError,
UnicodeError and JSONDecodeError into one message, so an artifact that was
never written looked like an encoding fault; each cause now names itself.
Health classification. broken_incumbent_arms inferred a broken environment from
an arm resolving zero tasks, which a reviewer facing a hard corpus falsifies -
Actions run 33962002890 is exactly that shape. Arms are now classified from
fresh execution and evidence outcomes as UNKNOWN, OBSERVED_OK, DEGRADED or
UNUSABLE, and only UNUSABLE aborts. Resolution count is not consulted. The
guard names no cause: an empty artifact establishes unusable evidence, not that
a mount rejected the write.
Comparator reuse. Reuse accepted evidence it should have rejected: a row
without a runtime_digest passed the drift lock, recorded_at was overwritten with
the copy time so a row could outlive its own max_age, and the binding ignored
task-asset and dependency digests although this change alters
sandbox_dependencies in the review corpus. Closing the last one required
preparing asset snapshots before the reuse decision, which also removes the
concurrent TaskAssetCache.prepare the prefetch thread could race.
These three concerns share aggregate() and _run_sweep, which is why they ship
together: separating them further would mean hunk-level surgery on a function
all three modify, and the risk of a silent omission outweighs the reviewability
gain.
592 eval tests pass at this base. The two test_model_gateway.py failures,
test_locked_litellm_translates_messages_to_offline_responses and
test_openai_gateway_never_leaves_proxy_output_on_an_undrained_pipe, fail
identically on origin/main in this environment.
Known gap, and the reason this is not ready to merge: no test drives _run_sweep
end to end. enforce_measurement_health is unit-tested including the
below-breaker unusable case, and the caller wiring is pinned structurally by
reading _run_sweep's compiled code object, but interruption semantics, exit
precedence and persisted artifacts are not exercised through the real path.
* fix(eval): address PR review feedback (#3207)
- aggregate: count admissible rows directly instead of subtracting the
execution and evidence counters, which double-charged a row that is both
a session error and invalid review evidence and could report UNUSABLE for
an arm holding real measurements.
- run_proposer: bound the session timeout by what is left of
--max-runtime-seconds, so clearing the sweep minimum cannot start a
full-length session past the instance window.
- comparator reuse: hold one O_NOFOLLOW descriptor for the size check,
digest and copy, and prove it is the inode that was checked, closing the
swap window a concurrent writer of the reuse directory had.
- Drive the review-artifact mount assertion through run_arm and the
clone-template assertion through run_cell, instead of rebuilding the
expected values in the tests (also removes the CodeQL unnecessary lambda).
- Assert the workflow invokes run-evolution.sh rather than that its YAML
mentions --max-runtime-seconds, which only appears in a comment.
- Correct the parse_review_output failure-mode claim: the fold was empty
artifacts reported as "not valid UTF-8 JSON"; a never-created file raised
FileNotFoundError.
- prettier: wrap the over-long readFileSync call flagged by PR autofix.
Note: pre-existing failure in tests/test_model_gateway.py::test_locked_litellm_translates_messages_to_offline_responses (local LiteLLM proxy never becomes ready in this environment) not addressed by this PR.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(eval): address the second round of PR review feedback (#3207)
- Refuse a symlinked `transcripts` component on both sides of comparator
reuse. O_NOFOLLOW guards the leaf only, so a link there redirected the
read or the copy out of the results directory; checked per component as
evolution._require_directory_chain does.
- Base the paid incumbent canary on the cells this sweep PLANS. Reuse
selection accepts any prior run index, so a results directory produced
with more runs left extra keys, the equality never held, and the canary
stopped firing. Extracted as drop_canary_reuse_key and unit-tested.
- Start the runtime clock in main(). --max-runtime-seconds is measured from
/proc/uptime before exec, so parsing, task I/O, preflight and gateway
setup were being handed back to the sweep out of the upload reserve.
- Do not fall back to shutil.copytree when the managed clone copy was
cancelled or timed out; that fallback is for a filesystem that cannot
reflink, and copytree cannot be cancelled.
- Assert the review session's writable mount, not only the verifier's
read-only one: the EROFS bug is about the agent's write.
- Exercise ref isolation in the copy_isolated_tree test rather than
comparing an initial HEAD a shared namespace would also match.
- Point the stale-symlink fixture at the sentinel via os.path.relpath, and
skip the reuse symlink tests where symlink creation needs privilege.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(eval): close the runtime-cap gap and pin the reuse directory
Both were left open on #3207 as approach decisions rather than nits.
Runtime cap: run-evolution.sh computed the budget in its own
`uv run python -c` and passed a number, so the script's remaining
provenance work and the CLI's own startup were spent by nobody and charged
to the sweep — out of the upload reserve the cap exists to protect. The
script now passes --max-runtime-from-instance-window and evolve reads
/proc/uptime itself, on the line after it starts the clock the budget is
measured against, so no interval exists to lose. Also removes an
interpreter start from the script and lets --dry-run print the real argv.
Reuse directory: _real_child_directory lstat-checked `transcripts` and
returned its pathname, so a concurrent writer could rename the directory
and leave a symlink before the name was used again — O_NOFOLLOW guards
only the leaf. Every artifact is now resolved against a held descriptor:
_open_real_directory opens with O_DIRECTORY|O_NOFOLLOW (check and open in
one syscall), and _open_regular / _copy_owner_only take dir_fd. The reuse
path is therefore POSIX-only; _require_openat says so and fails closed,
which the runner already treats as "run a paid cell". _resolved_directory
still tolerates a symlinked reuse root, unchanged and still tested.
evolution._require_directory_chain is still lstat-per-component. It guards
a different surface (candidate overlay reads) that neither review raised,
so it is left alone rather than widened into here.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(eval): sample the proposer budget where it is spent, digest what is copied
Four findings against f0cdc9e7, all of them mine.
- run_proposer took a precomputed remaining_seconds, but it clones,
sanitizes and builds a sandbox before the session starts, so the caller's
reading was already stale. It takes started_monotonic now and samples the
budget on the last line before run_claude. The caller's earlier reading
still decides whether to start at all — it just no longer decides how
long to allow.
- _copy_transcript_artifact hashed the source and then read it again to
copy it. A held descriptor stops the pathname being substituted, not the
inode being rewritten, so the row could record the expected digest while
the destination held other bytes. _copy_owner_only now digests the same
buffers it writes and returns (digest, bytes); a mismatch unlinks the
destination and raises. One read instead of two.
- Explain the empty except in _open_real_directory: an existing directory
is the ordinary case, and the O_DIRECTORY|O_NOFOLLOW open below is what
proves what it is (CodeQL).
- Drop the unused uptime fixture from the runtime-cap test, and correct the
cross-file contract described in the workflow-contract test and the
workflow YAML: neither names --max-runtime-from-instance-window, the
script does.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(eval): close the reuse producer/consumer contract through the real run_cell
Every comparator-reuse test built its rows by hand. That proves the predicate's
logic and nothing about the producer: a fixture can satisfy eligibility while a
row the runner actually emits never does, and a key-name inventory cannot tell
the difference. I checked that inventory first - all 25 keys the predicate reads
have a producer - which is exactly why it was not sufficient evidence.
This carries one record through the production path instead:
real run_cell -> production JSONL writer -> load_result_rows
-> row_is_reusable_comparator
Only the expensive dependencies are replaced: the model session, sandbox launch,
repository acquisition, graph preparation, git plumbing. The digest fields the
reuse binding compares are assembled by run_cell itself from its
TaskCellContext, so they stay real - they are the subject, not scaffolding.
Expectations are built from the sweep's own configuration rather than copied out
of the emitted row, since copying them back would make producer and consumer
agree because the test arranged it.
Two cases: a production-emitted row with matching bindings is eligible, and the
same evidence with one dependency binding changed is rejected. A test-controlled
digest set keeps both deterministic.
Mutation-checked. Replacing run_cell's task_asset_manifest_digest assignment
with None makes the positive case fail; restoring it passes. That is evidence
the inventory audit could not produce.
Building it also documented what a real review row must carry, which no fixture
had recorded: a scored review with review_weighted_f1 present, and at least one
transcript artifact whose source is PARENT_EVENT_STREAM_SOURCE. An empty
artifact list is not reusable. Those are production contracts my first double
got wrong, and the reader rejected it each time.
No production code changed. 607 eval tests pass, ruff clean.
* test(eval): drive the real sweep to its finalization decision
enforce_measurement_health was unit-tested and its call site pinned by reading
_run_sweep's compiled code object. Neither showed the guard running inside a
sweep. These drive the real _run_sweep with cell execution scripted and
everything downstream left alone: folding, aggregation, the artifact writers,
the health guard and the exit selection.
The below-breaker case is the decisive one. A fixture of many unusable cells
aborts through the pre-existing outage breaker instead - review-evidence-invalid
is systemic with a limit of five - and would pass whether or not the
finalization guard exists. One fresh unusable cell stays under that threshold,
so only the guard can catch it. The test asserts the arm and status the guard
reports, and that no systemic-outage line was printed, rather than accepting any
SystemExit: an unrelated setup failure must not satisfy it.
Mutation-checked at the runtime path. Removing the guard invocation fails the
below-breaker test because the expected finalization behaviour disappears, not
because a name went missing from a code object.
A zero score is covered separately. review_weighted_f1 = 0.0 must stay a present
valid negative measurement; a truthiness check would read it as absent and turn
a quality result into an execution-health failure. The third test asserts the
evidence survives - results.jsonl carries the scored row and report.md exists -
so the persisted artifacts tell the same story as the exit.
Only expensive setup is replaced: cell execution, graph preparation, asset
snapshots, and task-binding resolution, which clones the repository and verifies
the ref. Building the fixture also documented that the report renders the whole
review metric set, so an incomplete row fails in formatting rather than logic.
Still open on this track: interruption semantics and exit-reason precedence
(outage 1 before cancellation 130) are not yet exercised, and fold order and the
real sandbox mount contract remain on separate tracks.
No production code changed. 610 eval tests pass, ruff clean. The two
test_model_gateway.py failures reproduce on origin/main in this environment.
* fix(eval): an interrupted sweep is interrupted, not aborted
Driving the real _run_sweep to its exit revealed that cancellation without an
outage exits 1 and writes "Sweep aborted: partial evidence", where the contract
is 130 and "Sweep cancelled".
sweep_task_cells returns (streak, tripped), and its caller assigns that flag to
outage_tripped and turns it into exit 1. Both cancellation paths returned True
for it. The breaker's own return is also True, so the two became
indistinguishable one frame up and cancellation inherited the outage's exit and
wording. The fix is to return False from the cancellation paths: the flag means
the breaker tripped, and the caller already tests cancel_event itself for the
stop decision, so nothing stops running any later than before.
Reproduced before the fix, through the real caller, not from reading. The
failing assertion was the report line; the exit code was 1.
Two runtime tests cover it. Each begins with one admissible cell so the arm
classifies DEGRADED rather than UNUSABLE - otherwise enforce_measurement_health
supplies exit 1 first and a precedence test passes without ever reaching exit
selection. Cancellation is set from a completed cell rather than a sleep or a
real signal, so the interruption point is deterministic.
The precedence test is mutation-checked: moving the cancel_event check ahead of
the outage check fails it with "assert 130 == 1" - it observes the wrong exit
code, not merely some failure. My first attempt at that mutation silently
matched nothing and the suite passed; a no-op mutation proves nothing, so the
edit now asserts its own anchor.
test_process_control read the same flag as "stopped" and asserted it after a
cancellation. It now reports the event and the flag separately, which is what it
was really asserting: cancelled, and not an outage.
The scored-row shape moved into tests/bench_fixtures.py with zero values
written out, so the finalization and interruption tests share one definition
of what a real review row carries.
Impact analysis returned risk UNKNOWN - the index predates this branch and does
not carry the eval harness - so the callers were confirmed by text search as the
rules require for UNKNOWN: one production caller and three test sites, all
updated or verified. detect_changes reports zero for the same reason; that zero
is unseen, not unaffected.
612 eval tests pass, ruff clean. The two test_model_gateway.py failures
reproduce on origin/main in this environment.
* test(eval): prove the review artifact mount under a real sandbox
The orchestration tests replace the sandbox, so they say nothing about
isolation. This covers the filesystem contract the EROFS defect actually broke,
through the production configuration: the same command_prefix_for call run_arm
makes for a review cell, with read_only_workspace=True and the review-output
directory as the writable mount - not a hand-built mount tuple that merely looks
right.
A deterministic writer stands in for the agent. It writes a temp file beside the
destination and renames it into place, which is the operation that failed: an
atomic write needs a WRITABLE PARENT DIRECTORY, and binding the file itself left
nowhere to put the temp file. It then attempts a workspace write and must be
refused, and the production parse_review_output reads the bytes the sandbox left
behind. No model session and no credentials.
Placed in test_proposer_sandbox.py, which the "eval / containment (ubuntu)" job
already runs with GITNEXUS_REQUIRE_BWRAP_CANARY=1. That gate is the point: where
the variable is set, a missing namespace capability FAILS the job instead of
skipping into a green tick. Verified here - forcing the variable on this machine
fails with "bwrap: No permissions to create new namespace" rather than skipping.
What this does not establish: the assertions have never executed. This machine
cannot create user namespaces, so the test stops at the preflight. Imports,
signatures and the payload were checked statically instead - parse_review_output
returns a tuple rather than an object, and it rejects a body without "verdict",
so both of my first attempts were wrong and are fixed. The first CI run on a
namespace-capable runner is what will actually confirm it.
Scope is the filesystem and process contract only. A stand-in writer does not
establish that a particular agent CLI's own file-access policy permits the same
operation; that is a second, independent gate.
40 passed, 10 skipped locally; ruff clean.
* fix(eval): read the review artifact before the sandbox deletes it
The containment (ubuntu) job has been red since before the mount canary was
added, and both failures have the same cause.
This branch moved the review artifact out of the clone and into the session's
private root, which is the point of the change: the agent writes atomically, so
the artifact needs a writable parent DIRECTORY outside the read-only workspace.
prepare_sandbox removes that private root in a finally on scope exit. Two tests
read the artifact AFTER the with block, so they were asserting against a
directory the sandbox had already deleted - FileNotFoundError, reported as
"review output was never written".
Production is not affected, and this is the reason: run_arm holds the live
session and reads the artifact inside that scope, both to score it and to mount
it read-only into the verifier's separate sandbox invocation. The tests were the
only readers outside it.
Both now read inside the scope. The pre-existing canary
(test_read_only_review_workspace_exposes_only_one_writable_artifact) predates
this PR and passes on main, where the artifact still lived in the clone and
survived teardown; the relocation is what broke it, so the fix belongs here.
The new canary found this independently and agreed on the cause, which is what
it was written for - though only after CI ran it, since this machine cannot
create user namespaces.
40 passed, 10 skipped locally; ruff clean. The bwrap-gated tests still skip here
and remain unverified until the ubuntu job runs them.
* test(eval): pin what an interrupted sweep persists and refuses to promote
The completed-run persistence test could not show either of these: it never
interrupts, so it would pass even if the writers only ran on the clean path.
Evidence already paid for survives cancellation. The cell that completed before
the interruption is still in results.jsonl with its measurement intact, and
report.md is still written. Losing those rows would mean paying for evidence the
sweep then discards.
An interrupted run emits nothing that authorizes promotion. Asserted as the
semantic condition rather than the absence of a file: promotion.json IS still
written for an aborted run - it is the record of why nothing was promoted - so
the test requires run_status "aborted" and every decision reduced to
insufficient_evidence with a partial-evidence reason, rather than requiring the
artifact to disappear.
Mutation-checked. Forcing complete=True at the promotion_evidence call site
fails the test with "assert 'complete' == 'aborted'" - it observes an aborted
run claiming completeness, not merely some failure.
These were the last two unasserted items on this PR's finalization checklist.
614 eval tests pass, ruff clean. The two test_model_gateway.py failures are
environmental (litellm[proxy] console script absent) and predate this branch.
* Address PR review feedback (#3207)
An exhausted runtime cap no longer buys a second. remaining_runtime_seconds
floors at 0 and the proposer call site wrapped it in max(1, ...), so a cap fully
spent by the clone, the sanitize pass and the sandbox build started a paid
session with a one-second allowance instead of stopping before the upload
reserve the cap exists to protect. It now returns a not-ok record, which the
caller already treats as end-of-run. Pinned by a test driving the real
run_proposer with setup that consumes the whole budget; reverting to max(1, ...)
fails it.
Reuse copies are bounded before their size is validated, not after. The source
is a prior sweep directory this module already treats as concurrently writable,
so a transcript appended to after its metadata was recorded was streamed to EOF
and only then compared against its declared size - filling the destination, or
never reaching EOF, long before the drift check could reject it. _copy_owner_only
now takes max_bytes and stops one byte past the ceiling, which keeps the drift
comparison meaningful. Review and patch artifacts carry no recorded size, but
"no recorded size" is not "no limit": they get MAX_TRANSCRIPT_BYTES, the ceiling
the capture path already enforces.
A reused review row must carry its artifact. The predicate accepted a row on its
score and transcript metadata while materialize_reused_row copied the review
artifact only when the row named one, so a scored review could be carried
forward with nothing for a proposer to read. The shared row fixture was the
thing out of step here, not the requirement - production sets review_artifact
whenever the review source exists - so it now carries one too.
Test fixes, all against code this PR added:
unusable_review_row could not be overridden at all. It passed explicit keywords
beside **overrides, and Python rejects the duplicate in the call expression
before scored_review_row can apply its update, so unusable_review_row(error_kind=...)
raised TypeError. Merged into one mapping.
The finalization helper monkeypatched runner.prepare_ce_plugin_snapshot with
raising=False. No such symbol exists - the real one is staged_ce_plugin_snapshot
- so it silently added an attribute nothing reads. Removed.
The promotion test named candidate_review in candidate_arms but _run_sweep builds
cells only from args.arms, so no candidate cell ran and insufficient_evidence
could hold because nothing executed rather than because partial evidence is
barred. The candidate arm now runs, cancellation fires after its cell, and the
test asserts the candidate actually produced a row so it cannot silently return
to being vacuous.
The reuse round trip serialized with json.dumps and write_text while claiming to
cover the production writer, which applies redact_text over the row's own bytes.
It now writes the way the sweep does. Its fixture also writes the review
artifact, because run_cell records review_artifact only when the review source
exists and the emitted row was otherwise one production never emits.
Not addressing the duplicate-match nit on proposer_sandbox.py: the claim is that
"/review-output" occurs once in "/review-output/review-output.json". It occurs
twice, at offsets 0 and 14 - the separator before the basename forms it again -
so the boundary the comment describes is real. Verified with re.finditer.
The workspace-snapshot finding is parked for a human: excluding bootstrap noise
is a documented deliberate choice, and tightening it is a genuine tradeoff.
634 eval tests pass, ruff clean. The two test_model_gateway.py failures are
environmental (litellm[proxy] console script absent) and predate this branch.
* Address PR review feedback (#3207), round 2
Carry review_f1 in the scored-row fixture. score_review emits "f1"
(review_scoring.py:317), which the runner folds in as review_f1, so a real
scored row has it and the fixture did not - the same fidelity gap as the metrics
already added there. aggregate now reports 0.5 for it instead of None.
The reported failure mode was not real, and the distinction matters for anyone
reading the thread later. aggregate filters on record.get(metric) is not None
BEFORE indexing record[metric], so a missing key is skipped rather than raising
KeyError; the finalization tests were passing throughout. Verified by running
aggregate against the old fixture. Fixed because the fixture should match what
production emits, not because anything was crashing.
Drop the unused row parameter from the round-trip _expectation helper. It never
read the argument - deliberately, since the docstring says the bindings must be
derived from sweep configuration rather than copied out of the emitted row - but
passing the row anyway was dead plumbing that suggested the opposite.
The reuse-root TOCTOU finding is parked for a human rather than fixed: the
lstat-then-resolve window is real, but _resolved_directory documents the weaker
promise as deliberate and says not to merge it with proposer_sandbox's helper
"without first deciding which promise the reuse path should make". That decision
is the fix, and it is the same class as the reuse TOCTOU already parked on this
PR.
634 eval tests pass, ruff clean. test_process_control's TERM-ignoring-descendant
test flaked once under full-suite load and passes 3/3 in isolation; it is a
timing test and neither file changed here touches it. The two
test_model_gateway.py failures remain environmental.
* fix(eval): pin the reuse roots to the directory that was checked
Settles the reuse TOCTOU that has been parked twice on this PR. The docstring
asked to decide which promise the reuse path makes before merging its helper
with proposer_sandbox's, and the answer is that two separate things were being
conflated.
The symlink POLICY stays exactly as it was: parent hops remain allowed, so a
symlinked artifacts directory or macOS's /var still works, and a symlinked leaf
is still refused. Rejecting hops would break ordinary setups for no gain, which
is what the docstring argued and it is still right.
What is closed is the other thing - the gap between checking a name and using
it. _resolved_directory lstats a name and the later open re-walks that same
name, so a prior sweep that renames its results root and leaves something else
behind is opened somewhere else entirely, and O_NOFOLLOW cannot see a link that
resolve() already followed. _resolved_directory now returns the checked
directory's identity alongside its path, and _open_pinned_root fstats the
descriptor it opened and refuses a mismatch.
The two are separable, so there was no trade to make: comparing identity
rejects nothing that holds still, since a stable directory always matches
itself. Both cases are pinned - a replacement by a different REAL directory is
refused (the leaf-symlink rule does not cover that one), and an ordinary
unchanged root opens normally.
Why it matters here rather than as a general hardening: the failure is silent.
Rows would be copied out of some other directory and folded into a comparator
baseline as though they were this sweep's own evidence, which is the one thing
the reuse path exists to get right - a corrupted baseline decides promotions.
636 eval tests pass, ruff clean. The two test_model_gateway.py failures remain
environmental.
* refactor(eval): one prompt digest, and drop two pieces of dead scaffolding
Compute task_prompt_digest once. row_is_reusable_comparator compares the value a
prior row stored against the value this sweep derives, as exact strings, and the
two inline copies of that hash had already drifted apart - the expectation side
had picked up a str() cast the row side lacked. They agree today only because
tasks validate "prompt" as a string (runner_tasks.required_strings), so nothing
was broken; a later divergence on one side would have silently stopped rows
matching, with no test to catch it. Verified the extracted helper is
byte-identical to what it replaced.
Two comments named broken_incumbent_arms as the thing that would read stale
health. This branch replaced that call with the measurement-health path, so the
reasoning still holds but the name no longer does; they now name arm_health.
The function itself stays: origin/main still calls it at runner.py:2098, and
retiring it is its own change rather than a cleanup pass.
Removed instance_window_budget_from_proc and its one test. It composes two
helpers main() deliberately calls separately - there is a comment there
explaining why the read and the budget calculation stay decoupled - and nothing
outside its own test ever called it. Introduced on this branch, absent from
main, so it was never deployed, public, or consumed elsewhere.
Dropped an unused tmp_path parameter from a comparator-reuse test that does no
filesystem work.
Skipped three findings. Hoisting _assert_self_contained_git_objects to a
once-per-template check is a real saving - measured at 5.66s over 1551 objects -
but it verifies the OUTPUT of each copy operation, and git clone from a local
path hardlinks objects by default, which is exactly what its st_nlink check
catches. Checking a predecessor instead of the clone each cell runs against
thins an isolation guarantee for 0.7% of a median cell. Deleting
broken_incumbent_arms outright would remove a symbol main still calls. And a
fourth copy of the test-only _git helper extends a pattern that already exists
in three other test modules; centralising it means editing conftest.py, outside
this scope.
635 eval tests pass, ruff clean. The two test_model_gateway.py failures are the
environmental ones.
---------
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1103 lines
42 KiB
Python
1103 lines
42 KiB
Python
"""Regression tests for benchmark evidence and phase-boundary hardening."""
|
|
|
|
import hashlib
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
from contextlib import nullcontext
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from workflow_bench import proposer_sandbox, runner, runner_artifacts, runner_sessions
|
|
from workflow_bench.evolution import skill_fingerprint
|
|
from workflow_bench.oracle_assets import review_case_setup_command
|
|
from workflow_bench.process_control import ManagedProcessError, ManagedProcessResult
|
|
from workflow_bench.proposer_sandbox import SandboxError
|
|
|
|
|
|
def _report(**overrides) -> str:
|
|
payload = {
|
|
"type": "result",
|
|
"session_id": "s",
|
|
"num_turns": 3,
|
|
"total_cost_usd": 0.1,
|
|
"duration_ms": 1000,
|
|
"usage": {
|
|
"input_tokens": 1,
|
|
"cache_creation_input_tokens": 2,
|
|
"cache_read_input_tokens": 3,
|
|
"output_tokens": 4,
|
|
},
|
|
}
|
|
payload.update(overrides)
|
|
return json.dumps(payload)
|
|
|
|
|
|
def _stream(*, secret: str = "", **report_overrides: object) -> str:
|
|
events = []
|
|
if secret:
|
|
events.append(
|
|
{
|
|
"type": "assistant",
|
|
"message": {"content": [{"type": "text", "text": secret}]},
|
|
}
|
|
)
|
|
events.append(json.loads(_report(**report_overrides)))
|
|
return "\n".join(json.dumps(event) for event in events) + "\n"
|
|
|
|
|
|
def test_sandboxed_verifier_does_not_execute_candidate_login_profile(tmp_path):
|
|
home = tmp_path / "home"
|
|
home.mkdir()
|
|
profile_sentinel = tmp_path / "profile-ran"
|
|
(home / ".profile").write_text(f"touch '{profile_sentinel}'\nexit 97\n")
|
|
|
|
passed, output = runner_artifacts.run_verify(
|
|
"printf verified",
|
|
tmp_path,
|
|
5,
|
|
command_prefix=["/usr/bin/env"],
|
|
env={"HOME": str(home), "PATH": "/usr/local/bin:/usr/bin:/bin"},
|
|
)
|
|
|
|
assert passed is True
|
|
assert output.strip() == "verified"
|
|
assert not profile_sentinel.exists()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"state",
|
|
[
|
|
"input-failure",
|
|
"timeout",
|
|
"forced-kill",
|
|
"ownership-failure",
|
|
"spawn-failure",
|
|
"reap-failure",
|
|
"cleanup-failure",
|
|
],
|
|
)
|
|
def test_verifier_infrastructure_states_are_not_candidate_quality(state):
|
|
process = ManagedProcessResult(
|
|
state=state,
|
|
returncode=None,
|
|
stdout_tail="",
|
|
stderr_tail="hidden oracle secret",
|
|
duration_s=0.1,
|
|
)
|
|
result = runner_artifacts.VerificationResult(
|
|
command=["verify"],
|
|
process=process,
|
|
output="hidden oracle secret",
|
|
)
|
|
|
|
with pytest.raises(ManagedProcessError) as caught:
|
|
runner._verification_outcome(result)
|
|
assert "hidden oracle secret" not in str(caught.value)
|
|
|
|
|
|
def test_verifier_normal_nonzero_exit_remains_candidate_quality():
|
|
process = ManagedProcessResult(
|
|
state="exited",
|
|
returncode=1,
|
|
stdout_tail="",
|
|
stderr_tail="assertion failed",
|
|
duration_s=0.1,
|
|
)
|
|
result = runner_artifacts.VerificationResult(
|
|
command=["verify"],
|
|
process=process,
|
|
output="assertion failed",
|
|
)
|
|
|
|
assert runner._verification_outcome(result) == (False, "assertion failed")
|
|
|
|
|
|
def test_review_skill_fingerprint_rejects_setup_and_review_phase_replacement(tmp_path):
|
|
skill = tmp_path / ".claude" / "skills" / "gitnexus-review" / "SKILL.md"
|
|
skill.parent.mkdir(parents=True)
|
|
skill.write_text("trusted review prompt")
|
|
expected = skill_fingerprint(tmp_path, "review")
|
|
assert expected is not None
|
|
|
|
skill.write_text("replaced during task setup")
|
|
with pytest.raises(ValueError, match="task setup changed the evaluated skill fingerprint"):
|
|
runner_artifacts.require_skill_fingerprint(tmp_path, "review", expected, phase="task setup")
|
|
|
|
skill.write_text("trusted review prompt")
|
|
expected = skill_fingerprint(tmp_path, "review")
|
|
skill.write_text("replaced during review")
|
|
with pytest.raises(ValueError, match="review changed the evaluated skill fingerprint"):
|
|
runner_artifacts.require_skill_fingerprint(tmp_path, "review", expected, phase="review")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("state", "returncode", "report_overrides"),
|
|
[
|
|
("exited", 1, {}),
|
|
("timeout", None, {}),
|
|
("exited", 0, {"is_error": True}),
|
|
],
|
|
)
|
|
def test_failed_session_still_persists_redacted_transcript(
|
|
monkeypatch,
|
|
tmp_path,
|
|
state,
|
|
returncode,
|
|
report_overrides,
|
|
):
|
|
secret = "sk-ant-postmortem-secret"
|
|
output = tmp_path / "output"
|
|
output.mkdir()
|
|
stream = _stream(secret=secret, **report_overrides)
|
|
result = ManagedProcessResult(
|
|
state=state,
|
|
returncode=returncode,
|
|
stdout_tail=stream,
|
|
stderr_tail="primary failure",
|
|
duration_s=0.1,
|
|
timed_out=state == "timeout",
|
|
stdout_capture=stream.encode(),
|
|
)
|
|
monkeypatch.setattr(runner_sessions, "run_managed", lambda *args, **kwargs: result)
|
|
|
|
record = runner_sessions.run_claude(
|
|
"task",
|
|
tmp_path,
|
|
claude_bin="claude",
|
|
timeout=5,
|
|
transcript_output_dir=output,
|
|
transcript_output_prefix="failed-run",
|
|
transcript_secrets=(secret,),
|
|
)
|
|
|
|
artifact = output / record["transcript_artifact"]["path"]
|
|
assert record["ok"] is False
|
|
assert record["error_kind"] == "session-error"
|
|
assert record["error_detail"]["process_state"] == state
|
|
assert artifact.is_file()
|
|
assert secret not in artifact.read_text()
|
|
assert record["transcript_artifact"]["sha256"] == hashlib.sha256(artifact.read_bytes()).hexdigest()
|
|
|
|
|
|
def test_failed_session_keeps_primary_error_when_transcript_persistence_fails(monkeypatch, tmp_path):
|
|
stream = _stream()
|
|
result = ManagedProcessResult(
|
|
state="exited",
|
|
returncode=1,
|
|
stdout_tail=stream,
|
|
stderr_tail="primary failure",
|
|
duration_s=0.1,
|
|
stdout_capture=stream.encode(),
|
|
)
|
|
monkeypatch.setattr(runner_sessions, "run_managed", lambda *args, **kwargs: result)
|
|
|
|
record = runner_sessions.run_claude(
|
|
"task",
|
|
tmp_path,
|
|
claude_bin="claude",
|
|
timeout=5,
|
|
transcript_output_dir=tmp_path / "missing-output-root",
|
|
)
|
|
|
|
assert record["error_kind"] == "session-error"
|
|
assert record["error_detail"]["stderr_tail"] == "primary failure"
|
|
assert any("event-stream persistence" in item for item in record["evidence_diagnostics"])
|
|
|
|
|
|
def test_timed_out_session_never_trusts_writable_home_without_parent_result(monkeypatch, tmp_path):
|
|
projects = tmp_path / "projects"
|
|
output = tmp_path / "output"
|
|
output.mkdir()
|
|
|
|
def timeout_after_writing_transcript(*args, **kwargs):
|
|
forged = projects / "some-slug" / "timeout-session.jsonl"
|
|
forged.parent.mkdir(parents=True)
|
|
forged.write_text(_stream())
|
|
return ManagedProcessResult(
|
|
state="timeout",
|
|
returncode=None,
|
|
stdout_tail="",
|
|
stderr_tail="timed out",
|
|
duration_s=5.0,
|
|
timed_out=True,
|
|
stdout_capture=b"",
|
|
)
|
|
|
|
monkeypatch.setattr(runner_sessions, "run_managed", timeout_after_writing_transcript)
|
|
record = runner_sessions.run_claude(
|
|
"task",
|
|
tmp_path,
|
|
claude_bin="claude",
|
|
timeout=5,
|
|
transcript_projects=projects,
|
|
transcript_output_dir=output,
|
|
transcript_output_prefix="timeout-run",
|
|
)
|
|
|
|
assert record["error_kind"] == "session-error"
|
|
assert record["session_id"] is None
|
|
assert "transcript_artifact" not in record
|
|
assert record["transcript_missing"] is True
|
|
|
|
|
|
def test_phase_workspace_rejects_unchanged_preseeded_review_output(tmp_path):
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("preseeded output")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
|
|
with pytest.raises(ValueError, match="did not create or change"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_rejects_symlink_review_output(tmp_path):
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
outside = tmp_path.parent / f"{tmp_path.name}-outside-review.md"
|
|
outside.write_text("outside")
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.symlink_to(outside)
|
|
|
|
with pytest.raises(ValueError, match="regular non-symlink"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_accepts_new_regular_review_output(tmp_path):
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_ignores_claude_sandbox_bootstrap_noise(tmp_path):
|
|
# Reproduced empirically: Claude Code's own enableWeakerNestedSandbox
|
|
# bootstrap creates this exact set of paths on every session regardless
|
|
# of task or model output (a trivial "say OK" prompt was enough). None
|
|
# of it is something the model decided to write, so it must not read as
|
|
# an unauthorized planning-phase change.
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(tmp_path / ".claude" / "agents").mkdir(parents=True)
|
|
(tmp_path / ".claude" / "commands").mkdir(parents=True)
|
|
(tmp_path / ".claude" / ".cc-writes").write_text("{}")
|
|
(tmp_path / ".env").write_text("")
|
|
(tmp_path / ".bash_profile").write_text("")
|
|
(tmp_path / ".bashrc").write_text("")
|
|
(tmp_path / ".gitconfig").write_text("")
|
|
(tmp_path / ".idea").mkdir()
|
|
(tmp_path / ".profile").write_text("")
|
|
(tmp_path / ".ripgreprc").write_text("")
|
|
(tmp_path / ".vscode").mkdir()
|
|
(tmp_path / ".zprofile").write_text("")
|
|
(tmp_path / ".zshrc").write_text("")
|
|
(tmp_path / "scripts").write_text("")
|
|
(tmp_path / ".env.development.local").write_text("")
|
|
(tmp_path / ".npmrc").write_text("")
|
|
(tmp_path / "package.json").write_text("{}")
|
|
(tmp_path / "node_modules").mkdir()
|
|
(tmp_path / "node_modules" / ".bin").mkdir()
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_records_a_root_scripts_symlink(tmp_path):
|
|
target = tmp_path / "helper.py"
|
|
target.write_text("planted\n")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(tmp_path / "scripts").symlink_to(target)
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_still_rejects_writes_under_scripts(tmp_path):
|
|
scripts = tmp_path / "scripts"
|
|
scripts.mkdir()
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(scripts / "helper.py").write_text("planted\n")
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_still_rejects_a_genuinely_unauthorized_change(tmp_path):
|
|
# The bootstrap-noise exclusion must stay narrow: an actual source-file
|
|
# edit outside the allowed artifact still has to be caught.
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(tmp_path / "src.py").write_text("changed")
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_ignores_nested_claude_sandbox_bootstrap_noise(tmp_path):
|
|
# Claude Code bootstraps into whatever directory it is running in, not just
|
|
# the workspace root. The benchmark's task prompts cd into gitnexus/, so the
|
|
# same noise lands one level down -- observed verbatim in skill-evolution run
|
|
# 29861768554, where 13 of 18 sessions failed with
|
|
# "phase changed unauthorized workspace path(s): gitnexus/.claude/.cc-writes".
|
|
nested = tmp_path / "gitnexus" / ".claude"
|
|
nested.mkdir(parents=True)
|
|
(nested / "settings.local.json").write_text("{}")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(nested / ".cc-writes").write_text("{}")
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_does_not_descend_into_nested_bootstrap_directories(tmp_path):
|
|
# The exclusion must skip an entry before it is queued for traversal, so
|
|
# content created *inside* the ignored directory stays invisible too.
|
|
nested = tmp_path / "gitnexus" / ".claude" / ".cc-writes"
|
|
nested.mkdir(parents=True)
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(nested / "pending.json").write_text('{"writes": 1}')
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_still_rejects_nested_real_claude_config(tmp_path):
|
|
# gitnexus/.claude/settings.local.json is real tracked repository content.
|
|
# Excluding ".claude" wholesale at depth would blind the check to it, so the
|
|
# exclusion must name only the entries Claude Code itself creates.
|
|
nested = tmp_path / "gitnexus" / ".claude"
|
|
nested.mkdir(parents=True)
|
|
settings = nested / "settings.local.json"
|
|
settings.write_text("{}")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
settings.write_text('{"permissions": "changed"}')
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_still_rejects_nested_package_json(tmp_path):
|
|
# package.json is in WORKSPACE_SNAPSHOT_BOOTSTRAP_NOISE, but only as a
|
|
# workspace-root entry: gitnexus/package.json is real tracked content whose
|
|
# edits must still be caught.
|
|
nested = tmp_path / "gitnexus"
|
|
nested.mkdir()
|
|
manifest = nested / "package.json"
|
|
manifest.write_text("{}")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
manifest.write_text('{"version": "9.9.9"}')
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def test_phase_workspace_still_sees_writes_under_a_pre_existing_nested_claude_dir(tmp_path):
|
|
# Every excluded name is a blind spot. .claude/agents and .claude/commands
|
|
# are deliberately NOT excluded at depth: once a .claude directory exists
|
|
# (gitnexus/.claude/settings.local.json is tracked), anything written
|
|
# underneath an excluded entry is invisible to this check, and Claude Code
|
|
# loads .claude/agents relative to its cwd -- which these tasks point at
|
|
# gitnexus/. A planning phase must not be able to plant a definition there
|
|
# for the later work phase to read.
|
|
nested = tmp_path / "gitnexus" / ".claude"
|
|
nested.mkdir(parents=True)
|
|
(nested / "settings.local.json").write_text("{}")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
(nested / "agents").mkdir()
|
|
(nested / "agents" / "planted.md").write_text("planted agent definition")
|
|
artifact = tmp_path / "review-output.md"
|
|
artifact.write_text("new review")
|
|
|
|
with pytest.raises(ValueError, match="unauthorized workspace path"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=artifact)
|
|
|
|
|
|
def _cell_context(tmp_path, **overrides):
|
|
"""A TaskCellContext whose per-task inputs are all present and valid."""
|
|
snapshot = SimpleNamespace(
|
|
digest="asset-digest",
|
|
manifest_digest="asset-manifest",
|
|
dependency_content_digest="dep-content",
|
|
dependency_manifest_digest="dep-manifest",
|
|
)
|
|
graph = SimpleNamespace(
|
|
digest="graph-digest",
|
|
manifest_digest="graph-manifest",
|
|
materialize=lambda *_a, **_k: None,
|
|
)
|
|
oracle = SimpleNamespace(
|
|
digest="oracle-digest",
|
|
command_digest="oracle-command",
|
|
manifest_digest="oracle-manifest",
|
|
)
|
|
fields = {
|
|
"task": {"id": "task-a", "class": "demo", "prompt": "do the thing"},
|
|
"oracle_snapshot": oracle,
|
|
"repo": tmp_path / "repo",
|
|
"task_sha": "a" * 40,
|
|
"graph_snapshot": graph,
|
|
"graph_snapshot_error": None,
|
|
"asset_snapshot": snapshot,
|
|
"asset_snapshot_error": None,
|
|
"args": SimpleNamespace(
|
|
claude_bin="claude",
|
|
model="pinned-model",
|
|
proposer_model=None,
|
|
effort="xhigh",
|
|
auth_token=None,
|
|
),
|
|
"out_dir": tmp_path / "out",
|
|
"ce_plugin_snapshot": None,
|
|
"trees_dir": tmp_path / "trees",
|
|
"bwrap_bin": tmp_path / "bwrap",
|
|
"runtime_mounts": (),
|
|
"candidate_overlay": None,
|
|
"overlay_digest": None,
|
|
}
|
|
fields.update(overrides)
|
|
fields["out_dir"].mkdir(parents=True, exist_ok=True)
|
|
return runner.TaskCellContext(**fields)
|
|
|
|
|
|
def _stub_cell_dependencies(monkeypatch, tmp_path):
|
|
"""Replace everything a cell shells out to, so only its own logic runs.
|
|
|
|
Returns the clone it will hand out and the list its teardown appends to.
|
|
"""
|
|
removed: list[Path] = []
|
|
worktree = tmp_path / "clone"
|
|
worktree.mkdir()
|
|
monkeypatch.setattr(runner, "make_worktree", lambda *_a, **_k: worktree)
|
|
monkeypatch.setattr(runner, "sanitize_clone_for_hidden_oracles", lambda *_a, **_k: "b" * 40)
|
|
monkeypatch.setattr(runner, "stage_task_assets", lambda *_a, **_k: [])
|
|
monkeypatch.setattr(runner, "isolated_gitnexus_registry_mount", lambda *_a, **_k: None)
|
|
monkeypatch.setattr(runner, "ce_plugin_mounts_for_arm", lambda *_a, **_k: [])
|
|
monkeypatch.setattr(runner, "ce_plugin_dir_for_arm", lambda *_a, **_k: None)
|
|
monkeypatch.setattr(runner, "prepare_sandbox", lambda **_k: nullcontext(SimpleNamespace(run=None)))
|
|
monkeypatch.setattr(runner, "skill_fingerprint", lambda *_a, **_k: "skill-digest")
|
|
monkeypatch.setattr(runner, "require_skill_fingerprint", lambda *_a, **_k: None)
|
|
monkeypatch.setattr(runner, "_sandbox_git", lambda *_a, **_k: "c" * 40)
|
|
monkeypatch.setattr(runner, "implementation_diff_digest", lambda *_a, **_k: "")
|
|
monkeypatch.setattr(runner, "_prepare_untracked_for_diff", lambda *_a, **_k: None)
|
|
monkeypatch.setattr(runner, "diff_churn", lambda *_a, **_k: {})
|
|
monkeypatch.setattr(runner, "enforce_work_evidence", lambda *_a, **_k: None)
|
|
monkeypatch.setattr(runner, "capture_patch", lambda *_a, **_k: b"diff")
|
|
monkeypatch.setattr(runner, "run_arm", lambda *_a, **_k: {"resolved": True, "ok": True, "error_kind": None})
|
|
monkeypatch.setattr(runner, "remove_clone", lambda path: removed.append(path))
|
|
return worktree, removed
|
|
|
|
|
|
def test_run_cell_returns_a_row_bound_to_its_task_and_snapshots(monkeypatch, tmp_path):
|
|
_, removed = _stub_cell_dependencies(monkeypatch, tmp_path)
|
|
|
|
record = runner.run_cell(_cell_context(tmp_path), 2, "workflow")
|
|
|
|
assert record["resolved"] is True
|
|
assert record["error_kind"] is None
|
|
# The row has to carry its own coordinates: once cells stop running in a
|
|
# predictable order, position in results.jsonl identifies nothing.
|
|
assert record["task"] == "task-a"
|
|
assert record["arm"] == "workflow"
|
|
assert record["run"] == 2
|
|
assert record["task_asset_snapshot_digest"] == "asset-digest"
|
|
assert record["sanitized_graph_snapshot_digest"] == "graph-digest"
|
|
assert record["oracle_digest"] == "oracle-digest"
|
|
assert removed == [tmp_path / "clone"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"failure",
|
|
[
|
|
ManagedProcessError(
|
|
["setup"],
|
|
ManagedProcessResult(
|
|
state="timeout",
|
|
returncode=-15,
|
|
stdout_tail="",
|
|
stderr_tail="",
|
|
duration_s=1.0,
|
|
),
|
|
),
|
|
SandboxError("sandbox refused"),
|
|
OSError("disk went away"),
|
|
RuntimeError("overlay drifted"),
|
|
ValueError("bad binding"),
|
|
],
|
|
ids=["managed-process", "sandbox", "os", "runtime", "value"],
|
|
)
|
|
def test_run_cell_records_an_expected_failure_and_still_removes_its_clone(monkeypatch, tmp_path, failure):
|
|
_, removed = _stub_cell_dependencies(monkeypatch, tmp_path)
|
|
|
|
def explode(*_args, **_kwargs):
|
|
raise failure
|
|
|
|
monkeypatch.setattr(runner, "run_arm", explode)
|
|
record = runner.run_cell(_cell_context(tmp_path), 0, "workflow")
|
|
|
|
assert record["error_kind"] == "infra-error"
|
|
assert record["resolved"] is False
|
|
# A cell owns its clone for its whole lifetime; the sweep has no other
|
|
# chance to reclaim it, so the finally must survive every expected failure.
|
|
assert removed == [tmp_path / "clone"]
|
|
|
|
|
|
def test_run_cell_redacts_the_auth_token_from_the_failure_it_prints(monkeypatch, tmp_path, capsys):
|
|
_stub_cell_dependencies(monkeypatch, tmp_path)
|
|
secret = "sk-ant-not-a-real-key"
|
|
|
|
def explode(*_args, **_kwargs):
|
|
raise ManagedProcessError(
|
|
["claude"],
|
|
ManagedProcessResult(
|
|
state="exited",
|
|
returncode=1,
|
|
stdout_tail="",
|
|
stderr_tail=f"ANTHROPIC_API_KEY={secret}",
|
|
duration_s=1.0,
|
|
),
|
|
)
|
|
|
|
monkeypatch.setattr(runner, "run_arm", explode)
|
|
context = _cell_context(tmp_path)
|
|
context.args.auth_token = secret
|
|
# ManagedProcessError stringifies up to 1000 raw bytes of stderr_tail, and
|
|
# this line streams live into the CI log now that the sweep's stdout is
|
|
# echoed. results.jsonl already redacts the same field.
|
|
runner.run_cell(context, 0, "workflow")
|
|
|
|
assert secret not in capsys.readouterr().out
|
|
|
|
|
|
def test_run_cell_lets_an_unexpected_failure_escape_rather_than_scoring_it(monkeypatch, tmp_path):
|
|
_, removed = _stub_cell_dependencies(monkeypatch, tmp_path)
|
|
|
|
def explode(*_args, **_kwargs):
|
|
raise KeyError("harness bug")
|
|
|
|
monkeypatch.setattr(runner, "run_arm", explode)
|
|
# A harness bug recorded as an ordinary infra-error would be averaged into
|
|
# the evidence and counted toward the outage breaker. It must crash instead.
|
|
with pytest.raises(KeyError):
|
|
runner.run_cell(_cell_context(tmp_path), 0, "workflow")
|
|
assert removed == [tmp_path / "clone"]
|
|
|
|
|
|
def test_run_cell_reports_a_cleanup_failure_over_its_primary_outcome(monkeypatch, tmp_path):
|
|
_stub_cell_dependencies(monkeypatch, tmp_path)
|
|
|
|
def refuse(_path):
|
|
raise OSError("clone is busy")
|
|
|
|
monkeypatch.setattr(runner, "remove_clone", refuse)
|
|
record = runner.run_cell(_cell_context(tmp_path), 1, "workflow")
|
|
|
|
assert record["error_kind"] == "cleanup-failure"
|
|
assert record["resolved"] is False
|
|
assert "primary=None" in record["error_detail"]
|
|
assert "clone is busy" in record["error_detail"]
|
|
|
|
|
|
def _git(repo, *args):
|
|
return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True)
|
|
|
|
|
|
def test_run_cell_runs_the_arm_against_a_copy_of_the_clone_template(monkeypatch, tmp_path):
|
|
"""run_cell must copy the template, never re-clone.
|
|
|
|
run_cell takes the clone-template branch on essentially every multi-cell
|
|
sweep: it copies a pre-sanitized template rather than paying `git clone
|
|
--no-local` plus repack/prune/fsck per cell. Asserting on a copy the test
|
|
makes itself proves nothing about that branch — the clone the arm receives
|
|
is what has to come from the template, carrying the template's sanitized
|
|
HEAD rather than a recomputed one.
|
|
"""
|
|
|
|
repo = tmp_path / "repo"
|
|
repo.mkdir()
|
|
_git(repo, "init", "--quiet")
|
|
_git(repo, "checkout", "--quiet", "-b", "main")
|
|
(repo / "from-template.txt").write_text("sanitized\n")
|
|
_git(repo, "add", "-A")
|
|
_git(repo, "-c", "user.name=test", "-c", "user.email=test@invalid", "commit", "--quiet", "-m", "base")
|
|
sha = _git(repo, "rev-parse", "HEAD").stdout.strip()
|
|
trees = tmp_path / "trees"
|
|
trees.mkdir()
|
|
template = runner.make_worktree(repo, sha, trees)
|
|
template_head = _git(template, "rev-parse", "HEAD").stdout.strip()
|
|
|
|
_stub_cell_dependencies(monkeypatch, tmp_path)
|
|
|
|
def fail_if_recloned(*_args, **_kwargs):
|
|
raise AssertionError("clone template present: run_cell must not re-clone")
|
|
|
|
monkeypatch.setattr(runner, "make_worktree", fail_if_recloned)
|
|
monkeypatch.setattr(runner, "sanitize_clone_for_hidden_oracles", fail_if_recloned)
|
|
|
|
seen: dict[str, object] = {}
|
|
|
|
def record_arm(_arm, _task, worktree, _args, **_kwargs):
|
|
seen["worktree"] = worktree
|
|
seen["head"] = _git(worktree, "rev-parse", "HEAD").stdout.strip()
|
|
seen["content"] = (worktree / "from-template.txt").read_text()
|
|
# The copy is a private checkout: what the cell writes must not reach
|
|
# the template the other cells of this task still copy from.
|
|
(worktree / "from-template.txt").write_text("cell-local\n")
|
|
return {"resolved": True, "ok": True, "error_kind": None}
|
|
|
|
monkeypatch.setattr(runner, "run_arm", record_arm)
|
|
|
|
runner.run_cell(
|
|
_cell_context(tmp_path, clone_template=template, sanitized_head=template_head),
|
|
0,
|
|
"workflow",
|
|
)
|
|
|
|
assert seen["content"] == "sanitized\n"
|
|
assert seen["head"] == template_head
|
|
assert seen["worktree"] != template
|
|
assert (template / "from-template.txt").read_text() == "sanitized\n"
|
|
|
|
|
|
def test_run_cell_does_not_mask_the_staged_review_patch_before_setup(monkeypatch, tmp_path):
|
|
"""Review setup applies a patch staged under eval/workflow_bench.
|
|
|
|
Overlaying the empty oracle mask on that path is the CI abort:
|
|
`git apply` dies with `can't open patch`. The staged copy must stay
|
|
visible to sandboxed setup, then be gone before the model starts.
|
|
"""
|
|
|
|
worktree, _ = _stub_cell_dependencies(monkeypatch, tmp_path)
|
|
patch = worktree / "eval" / "workflow_bench" / "review_cases" / "pr-2718.patch"
|
|
patch.parent.mkdir(parents=True)
|
|
patch.write_text("diff --git a/visible.py b/visible.py\n")
|
|
captured: dict[str, object] = {}
|
|
|
|
def fake_prepare(**kwargs):
|
|
captured["mounts"] = kwargs.get("read_only_mounts", [])
|
|
|
|
def run(_command, **_kwargs):
|
|
leftover = worktree / "eval" / "workflow_bench"
|
|
if leftover.exists():
|
|
shutil.rmtree(leftover)
|
|
return SimpleNamespace(ok=True)
|
|
|
|
return nullcontext(SimpleNamespace(run=run))
|
|
|
|
monkeypatch.setattr(runner, "prepare_sandbox", fake_prepare)
|
|
context = _cell_context(
|
|
tmp_path,
|
|
task={
|
|
"id": "review-pr-2718-defect",
|
|
"class": "review-defect",
|
|
"prompt": "review the local diff",
|
|
"setup": review_case_setup_command("pr-2718.patch"),
|
|
},
|
|
)
|
|
record = runner.run_cell(context, 0, "workflow")
|
|
|
|
assert record.get("error_kind") is None
|
|
targets = [getattr(mount, "target", None) for mount in captured["mounts"] if mount is not None]
|
|
assert not any(target and "eval/workflow_bench" in str(target) for target in targets)
|
|
assert not (worktree / "eval" / "workflow_bench").exists()
|
|
|
|
|
|
def test_run_cell_fails_closed_when_setup_leaves_the_hidden_harness(monkeypatch, tmp_path):
|
|
worktree, _ = _stub_cell_dependencies(monkeypatch, tmp_path)
|
|
leftover = worktree / "eval" / "workflow_bench" / "review_cases"
|
|
leftover.mkdir(parents=True)
|
|
(leftover / "pr-2718.patch").write_text("diff\n")
|
|
|
|
def fake_prepare(**kwargs):
|
|
return nullcontext(SimpleNamespace(run=lambda *_a, **_k: SimpleNamespace(ok=True)))
|
|
|
|
monkeypatch.setattr(runner, "prepare_sandbox", fake_prepare)
|
|
context = _cell_context(
|
|
tmp_path,
|
|
task={
|
|
"id": "review-pr-2718-defect",
|
|
"class": "review-defect",
|
|
"prompt": "review the local diff",
|
|
"setup": review_case_setup_command("pr-2718.patch"),
|
|
},
|
|
)
|
|
record = runner.run_cell(context, 0, "workflow")
|
|
|
|
assert record["error_kind"] == "infra-error"
|
|
assert "hidden harness visible" in str(record["error_detail"])
|
|
|
|
|
|
def test_run_cell_fails_closed_when_a_per_task_snapshot_never_materialized(tmp_path):
|
|
# The snapshots are prepared once per task, before any cell. If that failed,
|
|
# every cell of the task has to record it rather than run against nothing.
|
|
context = _cell_context(tmp_path, asset_snapshot=None, asset_snapshot_error=OSError("no assets"))
|
|
record = runner.run_cell(context, 0, "workflow")
|
|
|
|
assert record["error_kind"] == "infra-error"
|
|
assert "no assets" in str(record["error_detail"])
|
|
|
|
|
|
def _progress():
|
|
"""Collector for what a sweep started and kept, readable after it raises."""
|
|
return SimpleNamespace(started=[], kept=[], streak=0, tripped=False)
|
|
|
|
|
|
def _sweep(cells, *, workers, run, outage_limit=5, streak=0, into=None):
|
|
"""Drive sweep_task_cells, recording what it started and kept.
|
|
|
|
Pass ``into`` a ``_progress()`` when the sweep is expected to raise: the
|
|
collector survives the exception, the return value does not.
|
|
"""
|
|
result = _progress() if into is None else into
|
|
result.streak, result.tripped = runner.sweep_task_cells(
|
|
cells,
|
|
workers=workers,
|
|
run=run,
|
|
on_start=lambda run_idx, arm: result.started.append((run_idx, arm)),
|
|
on_record=lambda run_idx, arm, _record: result.kept.append((run_idx, arm)),
|
|
outage_streak=streak,
|
|
outage_limit=outage_limit,
|
|
)
|
|
return result
|
|
|
|
|
|
def _row(error_kind=None):
|
|
return {"resolved": error_kind is None, "error_kind": error_kind}
|
|
|
|
|
|
CELLS = [(run_idx, arm) for run_idx in range(3) for arm in ("workflow", "candidate_workflow")]
|
|
|
|
|
|
@pytest.mark.parametrize("workers", [1, 3, 8])
|
|
@pytest.mark.parametrize("primary", ["review-evidence-invalid", "skill-not-invoked", "session-error"])
|
|
def test_unusable_review_evidence_stops_a_54_cell_sweep(workers, primary):
|
|
cells = [(i, "review") for i in range(54)]
|
|
result = _sweep(
|
|
cells,
|
|
workers=workers,
|
|
run=lambda *_: {
|
|
"resolved": False,
|
|
"error_kind": primary,
|
|
"review_evidence_valid": False,
|
|
},
|
|
)
|
|
assert result.tripped
|
|
assert 5 <= len(result.started) <= 5 + workers - 1
|
|
assert result.kept == result.started
|
|
|
|
|
|
def test_measured_review_miss_resets_the_outage_streak():
|
|
result = _sweep(
|
|
CELLS,
|
|
workers=1,
|
|
streak=4,
|
|
run=lambda *_: {
|
|
"resolved": False,
|
|
"error_kind": "oracle-failed",
|
|
"review_evidence_valid": True,
|
|
"review_weighted_f1": 0.0,
|
|
},
|
|
)
|
|
assert result.streak == 0 and not result.tripped
|
|
|
|
|
|
def test_invalid_review_with_primary_skill_error_is_excluded_from_aggregation():
|
|
result = runner.aggregate(
|
|
[
|
|
{
|
|
"resolved": False,
|
|
"error_kind": "skill-not-invoked",
|
|
"review_evidence_valid": False,
|
|
}
|
|
]
|
|
)
|
|
assert result["excluded_runs"] == 1 and result["valid_runs"] == 0
|
|
|
|
|
|
def test_sweep_keeps_rows_in_submission_order_whatever_order_they_finish():
|
|
# Cells finish in whatever order the machine allows, but a wave is folded
|
|
# in submission order — the outage streak counts consecutive failures, and
|
|
# "consecutive" in completion order would make the trip point flaky.
|
|
import threading
|
|
|
|
first_wave = CELLS[:3]
|
|
rendezvous = threading.Barrier(3, timeout=10)
|
|
release_first = threading.Event()
|
|
fast_finished = threading.Event()
|
|
finished: list[tuple[int, str]] = []
|
|
result: list[SimpleNamespace] = []
|
|
|
|
def run(run_idx, arm):
|
|
cell = (run_idx, arm)
|
|
if cell in first_wave:
|
|
rendezvous.wait()
|
|
if cell == first_wave[0]:
|
|
release_first.wait(timeout=10)
|
|
else:
|
|
finished.append(cell)
|
|
if len(finished) == 2:
|
|
fast_finished.set()
|
|
return _row()
|
|
|
|
sweep = threading.Thread(target=lambda: result.append(_sweep(CELLS, workers=3, run=run)))
|
|
sweep.start()
|
|
try:
|
|
assert fast_finished.wait(timeout=10)
|
|
assert first_wave[0] not in finished
|
|
assert set(finished) == set(first_wave[1:])
|
|
finally:
|
|
release_first.set()
|
|
sweep.join(timeout=10)
|
|
|
|
assert not sweep.is_alive()
|
|
assert result[0].kept == CELLS
|
|
assert result[0].started == CELLS
|
|
assert result[0].tripped is False
|
|
|
|
|
|
@pytest.mark.parametrize("workers", [1, 2, 3])
|
|
def test_sweep_trips_the_breaker_within_one_wave_of_the_serial_point(workers):
|
|
# Serial stops after the 5th consecutive systemic failure. Cells already in
|
|
# flight when the breaker trips cannot be recalled or erased from the
|
|
# evidence, so the overrun is bounded by the wave and every completed row
|
|
# is kept. Ten cells make the bound visible rather than hidden by the end.
|
|
long_task = [(run_idx, arm) for run_idx in range(5) for arm in ("workflow", "candidate_workflow")]
|
|
|
|
result = _sweep(long_task, workers=workers, run=lambda *_: _row("session-error"))
|
|
|
|
assert result.tripped is True
|
|
assert 5 <= len(result.started) <= 5 + workers - 1
|
|
assert result.kept == result.started
|
|
assert len(result.started) < len(long_task)
|
|
|
|
|
|
def test_sweep_reads_a_real_failure_as_signal_rather_than_an_outage():
|
|
# resolved=False with no systemic error_kind is the benchmark working, not
|
|
# the harness failing; it must reset the streak instead of tripping.
|
|
result = _sweep(CELLS, workers=3, run=lambda *_: {"resolved": False, "error_kind": None})
|
|
|
|
assert result.tripped is False
|
|
assert result.streak == 0
|
|
assert result.kept == CELLS
|
|
|
|
|
|
def test_sweep_surfaces_an_unexpected_worker_failure_instead_of_dropping_the_cell():
|
|
def run(run_idx, arm):
|
|
if (run_idx, arm) == (0, "candidate_workflow"):
|
|
raise KeyError("harness bug")
|
|
return _row()
|
|
|
|
# A Future holds its exception until read. Unread, this cell would vanish
|
|
# from the evidence with no crash and no row — fewer runs in an arm's
|
|
# aggregate, silently.
|
|
with pytest.raises(KeyError):
|
|
_sweep(CELLS, workers=3, run=run)
|
|
|
|
|
|
def test_sweep_runs_cells_of_a_wave_at_the_same_time():
|
|
import threading
|
|
|
|
barrier = threading.Barrier(3, timeout=10)
|
|
|
|
def run(run_idx, arm):
|
|
# Deadlocks unless all three cells of the wave are genuinely in flight
|
|
# together — a pool that serialised them would time out here.
|
|
barrier.wait()
|
|
return _row()
|
|
|
|
result = _sweep(CELLS, workers=3, run=run)
|
|
|
|
assert result.kept == CELLS
|
|
|
|
|
|
def test_sweep_of_one_worker_never_leaves_the_calling_thread():
|
|
import threading
|
|
|
|
caller = threading.current_thread()
|
|
seen: list[threading.Thread] = []
|
|
|
|
def run(run_idx, arm):
|
|
seen.append(threading.current_thread())
|
|
return _row()
|
|
|
|
# Ctrl-C reaches only the main thread, so the serial default has to stay on
|
|
# it: a cell on a worker thread is outside the reach of the cleanup that
|
|
# kills its sandboxed process tree.
|
|
_sweep(CELLS, workers=1, run=run)
|
|
|
|
assert seen == [caller] * len(CELLS)
|
|
|
|
|
|
@pytest.mark.parametrize("failure", [KeyError("harness bug"), SystemExit(97)])
|
|
def test_sweep_keeps_the_rows_of_cells_that_finished_beside_a_failing_one(failure):
|
|
def run(run_idx, arm):
|
|
if (run_idx, arm) == (0, "candidate_workflow"):
|
|
raise failure
|
|
return _row()
|
|
|
|
progress = _progress()
|
|
# The failing cell's two siblings completed and spent their budget before
|
|
# the harness bug surfaced. Reading the futures in order and raising on the
|
|
# first failure would drop their rows: money spent, no evidence written.
|
|
with pytest.raises(type(failure)):
|
|
_sweep(CELLS, workers=3, run=run, into=progress)
|
|
|
|
assert progress.kept == [(0, "workflow"), (1, "workflow")]
|
|
|
|
|
|
def test_sweep_hands_a_ctrl_c_back_without_waiting_for_the_running_cells(monkeypatch):
|
|
import threading
|
|
|
|
in_flight = threading.Barrier(3, timeout=10)
|
|
release = threading.Event()
|
|
finished: list[tuple[int, str]] = []
|
|
|
|
def run(run_idx, arm):
|
|
in_flight.wait()
|
|
release.wait(timeout=10)
|
|
finished.append((run_idx, arm))
|
|
return _row()
|
|
|
|
def interrupt_once_the_wave_is_running(_futures, *_args, **_kwargs):
|
|
# Stands in for the Ctrl-C an operator types mid-wave: an async
|
|
# KeyboardInterrupt is delivered to the main thread, which is the one
|
|
# blocked here waiting on the wave.
|
|
in_flight.wait()
|
|
raise KeyboardInterrupt
|
|
|
|
monkeypatch.setattr(runner, "wait", interrupt_once_the_wave_is_running)
|
|
try:
|
|
with runner.cancellation_scope(release), pytest.raises(KeyboardInterrupt):
|
|
_sweep(CELLS, workers=2, run=run)
|
|
|
|
# Cancellation releases active work before joining; no worker can
|
|
# outlive the assets the interrupted sweep is about to clean up.
|
|
assert set(finished) == set(CELLS[:2])
|
|
finally:
|
|
release.set()
|
|
|
|
|
|
def test_workers_is_bounded_at_both_ends_before_the_sweep_starts():
|
|
base = ["--tasks", "tasks.yaml", "--model", "pinned-model"]
|
|
|
|
assert runner.build_parser().parse_args(base).workers == 1
|
|
at_max = runner.build_parser().parse_args([*base, "--workers", str(runner.MAX_WORKERS)])
|
|
assert at_max.workers == runner.MAX_WORKERS
|
|
|
|
# A mistyped worker count has to fail at the command line: hours later it
|
|
# only shows up as timed-out sessions, which the promotion gate throws away.
|
|
for rejected in ("0", "-1", str(runner.MAX_WORKERS + 1)):
|
|
with pytest.raises(SystemExit):
|
|
runner.build_parser().parse_args([*base, "--workers", rejected])
|
|
|
|
|
|
def test_partial_wave_submission_preserves_rows_and_original_interruption(monkeypatch):
|
|
original = runner.ThreadPoolExecutor.submit
|
|
submissions = 0
|
|
|
|
def submit(pool, *args, **kwargs):
|
|
nonlocal submissions
|
|
submissions += 1
|
|
if submissions == 2:
|
|
raise KeyboardInterrupt("submission interrupted")
|
|
return original(pool, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(runner.ThreadPoolExecutor, "submit", submit)
|
|
records = []
|
|
with pytest.raises(KeyboardInterrupt, match="submission interrupted"):
|
|
runner.sweep_task_cells(
|
|
CELLS,
|
|
workers=2,
|
|
run=lambda *_: _row(),
|
|
on_start=lambda *_: None,
|
|
on_record=lambda *record: records.append(record),
|
|
outage_streak=0,
|
|
outage_limit=5,
|
|
)
|
|
assert len(records) == 2
|
|
assert records[1][2]["error_kind"] == "cancelled"
|
|
|
|
|
|
@pytest.mark.parametrize("error_kind", ["infra-error", "cleanup-failure"])
|
|
def test_progress_line_reports_an_unmeasured_failure_as_unmeasured_not_as_free(error_kind):
|
|
dead = runner.infra_error_record(RuntimeError("bwrap died"))
|
|
dead["error_kind"] = error_kind
|
|
|
|
line = runner.cell_progress_line("task", "workflow", 0, dead)
|
|
|
|
# The 0.0s are placeholders for numbers no session ever produced; printed
|
|
# as numbers they read as a cell that ran instantly for free.
|
|
assert "cost=n/a" in line
|
|
assert "took=n/a" in line
|
|
assert f"error_kind={error_kind}" in line
|
|
# results.jsonl is promotion evidence — only the display changes.
|
|
assert dead["cost_usd"] == 0.0
|
|
assert dead["duration_s"] == 0.0
|
|
|
|
|
|
def test_progress_line_reports_the_numbers_a_real_run_measured():
|
|
line = runner.cell_progress_line(
|
|
"task",
|
|
"workflow",
|
|
1,
|
|
{
|
|
"resolved": True,
|
|
"input_tokens": 10,
|
|
"output_tokens": 2,
|
|
"cost_usd": 0.5,
|
|
"duration_s": 12.0,
|
|
"error_kind": None,
|
|
},
|
|
)
|
|
|
|
assert "cost=$0.5" in line
|
|
assert "took=12.0s" in line
|
|
assert "error_kind=none" in line
|
|
|
|
|
|
def test_claude_settings_allow_the_review_artifact_directory():
|
|
"""The second gate on the artifact path.
|
|
|
|
The bwrap bind is not the only thing that decides whether the agent can
|
|
write: the CLI applies this filesystem policy to its own tools, so a path
|
|
missing from allowWrite is unwritable however the mount is shaped. The
|
|
artifact lived under /workspace when this list was written, which is why
|
|
moving it out needed this entry and nothing caught the omission.
|
|
"""
|
|
|
|
settings = json.loads(proposer_sandbox.build_claude_settings(sandbox_enabled=True))
|
|
filesystem = settings["sandbox"]["filesystem"]
|
|
assert proposer_sandbox.SANDBOX_REVIEW_OUTPUT in filesystem["allowWrite"]
|
|
assert proposer_sandbox.SANDBOX_REVIEW_OUTPUT in filesystem["allowRead"]
|
|
assert filesystem["denyRead"] == ["/"]
|
|
|
|
|
|
def test_review_contract_tells_the_agent_the_writable_path():
|
|
prompt = runner.REVIEW_PROMPT.format(task="task text")
|
|
assert f"{runner.SANDBOX_REVIEW_OUTPUT}/{runner.REVIEW_OUTPUT}" in prompt
|
|
assert f"{runner.SANDBOX_WORKSPACE}/{runner.REVIEW_OUTPUT}" not in prompt
|
|
# The JSON shape survives .format() with its braces intact.
|
|
assert '{"schema_version":1' in prompt
|
|
artifact = f"{runner.SANDBOX_REVIEW_OUTPUT}/{runner.REVIEW_OUTPUT}"
|
|
assert runner.CE_REVIEW_PROMPT.format(task="task text").count(artifact) == 1
|
|
|
|
|
|
def test_enforce_phase_workspace_can_require_an_untouched_workspace(tmp_path):
|
|
(tmp_path / "tracked.py").write_text("original\n")
|
|
before = runner_artifacts.workspace_snapshot(tmp_path)
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=None)
|
|
|
|
(tmp_path / "tracked.py").write_text("the review edited the code it was reviewing\n")
|
|
with pytest.raises(ValueError, match="changed the read-only workspace"):
|
|
runner_artifacts.enforce_phase_workspace(tmp_path, before, allowed_artifact=None)
|