Skip to content

perf: shard portable serial tests across CI runners - #1544

Merged
kunchenguid merged 3 commits into
mainfrom
fm/fm-behavior-serial-ci-speedup-r1
Aug 2, 2026
Merged

kunchenguid merged 3 commits into
mainfrom
fm/fm-behavior-serial-ci-speedup-r1

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Speed up the 'Behavior portable serial' CI job so it completes with a comfortable buffer below its timeout-minutes limit.

Problem: on firstmate PR 1495 the 'Behavior portable serial' CI job was cancelled - not because tests failed (every step passed), but because its main step ('Run portable serial remainder') ran ~19m51s and the job hit its ~20-minute timeout-minutes at the exact boundary. It runs the behavior suite serially, which is too slow, so it intermittently times out and cancels. Same class of issue as the recently merged windows CI slowness fix (no-mistakes PR 645 - branchsync serial floor).

Goal: reduce the serial job's wall time SIGNIFICANTLY so it finishes with a comfortable margin - well under half the timeout, not a few seconds under. Approaches in preference order: parallelize the serial remainder where safe (shard/concurrent execution); keep only genuinely serial-only tests (shared mutable state, ports, global fixtures) in the serial set and move the parallel-safe majority to parallel; speed up the slowest individual tests; trim redundant setup. Preserve full behavioral coverage - never weaken or delete tests to gain speed. Provide concrete before/after wall-time evidence versus the timeout. Widening timeout-minutes is acceptable only as belt-and-suspenders on top of a real speedup, never as the primary fix.

Measured evidence gathered before implementing: on green CI run 30725985757 the lane's 69 scripts summed to 1143762 ms (19m04s) against the 20-minute cap; job setup (checkout, ShellCheck, tmux check, tasks-axi install) is only about 7s, so the cost is entirely test wall time and there is nothing meaningful to trim in setup. The single longest script, tests/fm-pr-check-security.test.sh at 199573 ms, is the hard floor for any shard count.

Chosen approach and the reasoning behind it: shard the portable serial lane across four SEPARATE CI runners rather than introducing concurrency inside one runner. Each shard stays strictly serial in itself. Because separate GitHub jobs get separate machines, no two of these stateful scripts (watcher, lock, AFK, real tmux, daemon, secondmate lifecycle, bootstrap, live-harness opt-in, GUI-backend) ever share a machine, so this split deliberately needs NO concurrency isolation proof - unlike the existing portable parallel lanes, which are restricted to the proven-isolated set owned by bin/fm-test-isolation-proof.sh. Moving serial tests into the proven-isolated parallel set was deliberately NOT done, because that would require a new concurrent isolation proof archive and is the riskier path. Individual test internals were deliberately left untouched to avoid weakening coverage or introducing flakiness; sharding alone reaches the target.

Deliberate design decisions a reviewer would not infer from the diff alone:

  • Serial-lane membership stays DERIVED (everything neither proven-isolated nor real-herdr-gated) rather than enumerated, so a newly added test lands in the lane by default instead of falling out of every lane. Shard assignment is computed at runtime by longest-processing-time bin packing, so new tests need no manual shard placement.
  • The per-script duration table embedded in bin/fm-test-run.sh is intentionally a BALANCE HINT ONLY, not a correctness input. The coverage guard keeps the partition complete and disjoint whatever the hints say, so a stale hint costs a slower shard rather than lost coverage. Unmeasured scripts get a conservative default near the measured per-script mean. docs/fm-test-portable-shards.md owns the refresh procedure.
  • Lane names deliberately carry the shard count (portable-serial-of) and bin/fm-test-run.sh refuses any lane whose ofN disagrees with its configured count. ci.yml deliberately derives the same N from strategy.job-total rather than a literal. This is fail-closed on purpose: changing the shard count in either file alone makes the lane fail loudly instead of silently leaving part of the required suite unrun. The plain- naming was rejected precisely because it has that silent coverage hole.
  • timeout-minutes was TIGHTENED from 20 to 15, not widened. Expected work per shard is 285941 ms (~4m46s), about a third of the cap, leaving roughly 3x hang-tripwire margin. Timeouts in this repo are hang tripwires, not expected healthy durations.
  • fail-fast: false on the matrix is deliberate so one shard's failure never hides another shard's result.
  • --check-coverage was extended to additionally prove the serial shards are non-empty, pairwise disjoint, and exactly equal to the serial lane. No test is weakened, skipped, or removed anywhere in this change.

Also included deliberately, as an engineering-excellence fix for flakiness encountered while validating: tests/fm-test-run.test.sh's --jobs scheduler fixture proved slot-refill behavior with a 0.5s-versus-0.05s wall-clock sleep race, which failed on a loaded machine during this work. It is replaced with an explicit signal handshake between the fixtures (the slow fixture blocks until the replacement fixture signals, and the replacement reads the evidence before signalling), with a bounded deadline so a genuinely wait-for-oldest scheduler still reports instead of hanging. Verified 3/3 under sustained ~20x CPU saturation where the old shape had already flaked.

Local verification already performed: bin/fm-lint.sh clean; bin/fm-doc-audience-check.sh ok; --check-coverage reports FM_TEST_COVERAGE ok total=104 parallel=24 serial=69 serial_shards=4 herdr=11; all four shards balance to 285.9s with 1 ms imbalance; tests/fm-test-run.test.sh, tests/fm-lint.test.sh and tests/fm-documentation-audiences.test.sh pass; portable-serial-1of4 executed end to end with 15/15 green (FM_TEST_SUMMARY total=15 failed=0 skipped_gate=2, exit 0); bin/fm-test-run.sh parses under stock macOS Bash 3.2.

This is firstmate's own shared tracked material (.github/workflows/, bin/, docs/, CONTRIBUTING.md, tests/), so the firstmate-coding-guidelines skill applies: one sentence per line in tracked Markdown, plain dash never em dash, no agent commit co-author, shellcheck-clean bin scripts via bin/fm-lint.sh, tests colocated in tests/ extending the existing runner, tests must exercise executable interfaces rather than assert implementation source text, and every contract stated in full exactly once with cross-references elsewhere. The authoritative before/after wall time will come from this PR's own CI run.

What Changed

  • Split the portable serial behavior lane into four duration-balanced CI jobs that remain serial per runner, disable matrix fail-fast, and tighten the timeout from 20 to 15 minutes.
  • Add deterministic longest-processing-time shard assignment, fail-closed shard-count validation, lane discovery, and coverage checks proving the serial shards are non-empty, disjoint, and complete.
  • Document shard timing and refresh procedures, and replace the scheduler test's timing race with a bounded signal handshake.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed
✅ **Rebase** - passed
✅ **Review** - completed
✅ **Test** - passed
✅ **Document** - passed
✅ **Lint** - passed
✅ **Push** - passed

The Behavior portable serial job ran all 69 scripts of the serial
remainder on one runner. The measured serial sum on run 30725985757 was
1143762 ms (19m04s) against a 20-minute timeout, so the job intermittently
reached the cap and was cancelled with every step passing. Setup is only
about 7s, so the cost is entirely test wall time.

Split the lane into four separate-runner shards. Each shard is still
strictly serial, and separate runners mean no two of these stateful
scripts ever share a machine, so the split needs no concurrency isolation
proof. Assignment is longest-processing-time bin packing over measured
per-script duration hints, balancing every shard to 285941 ms (~4m46s) of
expected work, and the timeout tightens from 20 to 15 minutes.

bin/fm-test-run.sh owns the shard count and refuses a lane whose "ofN"
disagrees with it, while ci.yml derives the same count from
strategy.job-total rather than a literal, so changing it in either file
alone fails the lane loudly instead of leaving part of the required suite
unrun. --check-coverage additionally proves the shards are non-empty,
disjoint, and exactly equal to the serial lane. No test is weakened,
skipped, or removed.

Also replace the wall-clock sleeps in the --jobs scheduler test fixture
with an explicit signal handshake between the fixtures. The old
0.5s-versus-0.05s race failed on a loaded machine; the handshake passes
under sustained CPU saturation.
@kunchenguid
kunchenguid merged commit f5ab708 into main Aug 2, 2026
13 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-behavior-serial-ci-speedup-r1 branch August 2, 2026 21:42
justinmaxw added a commit to justinmaxw/firstmate-archive that referenced this pull request Aug 3, 2026
* fix(bin): preserve full task contract in no-mistakes intent (kunchenguid#1447)

* Preserve task contract in no-mistakes intent

* no-mistakes(review): Preserve complete current task contract in no-mistakes intent

* fix(bin): parse punctuated secondmate registry entries safely (kunchenguid#1452)

* fix: centralize secondmate registry parsing

* no-mistakes(review): Centralize secondmate registry binding validation

* no-mistakes(review): Harden registry EOF and symlink validation

* no-mistakes(review): Reject unreadable registries before parsing

* no-mistakes(document): Document punctuation-safe secondmate registry validation

* no-mistakes: apply CI fixes

* feat(bin): add durable process-event supervision (kunchenguid#1483)

* feat(procevent): supervise long-polling sources into durable events

Firstmate had no way to wait on a blocking external process without holding
a conversational turn. Add a domain-neutral process-to-event runner plus a
thin adapter around the currently published `lavish-axi poll` interface:
canonical physical source identity, one machine-wide owner per source, direct
argv execution, and durable 0600 result capture before any event referencing
it is published on the existing wake queue. No second notifier, no polling
control plane, and no retry machinery.

A captured result with no durable handled acknowledgement stays eligible for
bounded re-announcement across any number of drains and restarts. Draining a
wake before acting on it and then starting a replacement session resurfaces
the same exact source and sequence, and never puts result payload text in an
event line. `fm-procevent.sh handled <source-id> <sequence>` is the only thing
that stops re-announcement: generation-keyed, private, path-safe, durable, and
atomically idempotent, so a paired external effect gated on its first-time
versus repeat report is never authorized twice.

An acknowledgement is refused unless matching captured result and adapter
records already exist, so a premature or mistyped call cannot suppress a
future result.

The source side is unchanged and still lossy: the published poll clears
feedback destructively before returning it, so a result lost in that window
is unrecoverable. This is never at-least-once, no-loss, or lossless, and the
handled acknowledgement is not a generic exactly-once effect either - a crash
between an external effect and its acknowledgement can still repeat that
effect on replay.

Integrate registered sources with watcher supervision, the guards, and
recoverable secondmate teardown across nested homes, and cover source
identity, lifecycle races, supervision, restart handling, and cleanup safety
with regressions.

* no-mistakes(review): Prevent Lavish prompt text from spoofing missing sessions

* no-mistakes(review): Serialize publication and secure handled acknowledgements

* no-mistakes(document): Document hardened process-event acknowledgement guarantees

* fix(procevent): never reclaim a source whose owned group still runs

A runner is its own process group leader and starts the blocking source in
that group, but the claim records only the leader PID and its identity. If the
leader died while the source child kept running, the missing PID was
classified stale: reconciliation released the claim and started a second
runner while the old blocking source was still consuming the same canonical
source. For the Lavish adapter that means two destructive long polls racing on
one review session, so it is not harmless process litter. It also contradicted
the documented promise that ownership is never released until the whole group
is gone.

Ownership state now distinguishes a generation that is really gone from one
whose leader crashed with its group still alive. Reconcile stops that
surviving group and releases its exact generation before starting any
replacement, and keeps the claim for a later cycle when it cannot prove the
group stopped or another home owns it. Acquisition and `start` treat the same
state as held rather than reclaimable.

Signalling that group is safe precisely because only an absent leader reaches
this state. A reused PID leaves the leader alive, so the identity comparison
still classifies it stale or uncertain and no group signal follows, which
keeps the existing PID-reuse refusal intact.

Add a public-interface regression for the exact crash cut - SIGKILL only the
leader, prove the child group survives, reconcile, and prove the old group is
gone with no second source running - plus its counterexample that a generation
with no leader and no surviving group is still reclaimed. Update the runner
help, operating documentation, skill, and verification record where they
described reclaim in terms of the leader alone.

* no-mistakes(review): Enforce runner group ownership and detect poller overlap

* no-mistakes(review): Isolate runner groups from unrelated caller processes

* no-mistakes(document): Document isolated process-event runner launch

* no-mistakes(lint): Suppress Perl literal ShellCheck false positive

* fix(bin): retire terminal process events and surface queued wakes (kunchenguid#1500)

* fix(bin): deliver process-event results and retire ended sources

Two defects reproduced during a real Lavish adapter session.

One human `Send & End` produced four captured results: the real feedback,
then recurring empty ended sessions. The generic runner had no way to learn
a source was finished, so every reconcile restarted a poll that returned
immediately. The runner now asks the source's own adapter -
`fm-procevent-<adapter>.sh terminal <result-file>` - and on exit 0 alone
re-proves ownership, drops the registration, and releases its own claim
under one source boundary. Terminal knowledge stays adapter-owned: for
Lavish that is an ended session, a missing session, and the final feedback
delivery the published poll marks with `session_ended`. An adapter with no
terminal command keeps its source armed exactly as before. Capture before
publication, captured-result durability, queued wake durability, bounded
re-announcement, handled deduplication, one-owner ownership, and explicit
idempotent retirement are all unchanged.

A captured result queued its `check` wake durably, but a healthy watcher
with a fresh beacon never delivered it; the result surfaced only after a
manual drain. Publication happens outside the watcher (in the runner) or
unconditionally (in reconcile), so the watcher had no newly actionable
signal to report and never reached its rewake path. It now reports a
queued-but-unsurfaced process-event record through the same actionable exit
every other wake uses, deduplicated by the same `.seen-*` marker discipline
the signal scan uses, so the record is always durable before it is
suppressed. The durable queue remains the authority and no second notifier,
poller, timer, queue, or adapter-specific wake path is added.

Regressions cover both, driven end to end: an armed Lavish source against a
stand-in for the published poll polls once, captures once, publishes one
distinct event, and retires itself; two fixture adapters prove the terminal
decision follows the adapter alone; and a real capture plus a real watcher
prove one proactive wake before any drain, with no duplicate wake while the
record stays queued or after it is acknowledged.

* no-mistakes(review): Harden process-event retirement and proactive delivery

* no-mistakes(review): Route process-event delivery through shared wake owner

* no-mistakes(document): Clarify process-event delivery and retirement documentation

* no-mistakes(lint): Fix ShellCheck control-flow warnings

* no-mistakes(lint): Fix wake output status lint warning

* perf: shard portable serial tests across CI runners (kunchenguid#1544)

* perf(ci): shard the portable serial behavior lane across runners

The Behavior portable serial job ran all 69 scripts of the serial
remainder on one runner. The measured serial sum on run 30725985757 was
1143762 ms (19m04s) against a 20-minute timeout, so the job intermittently
reached the cap and was cancelled with every step passing. Setup is only
about 7s, so the cost is entirely test wall time.

Split the lane into four separate-runner shards. Each shard is still
strictly serial, and separate runners mean no two of these stateful
scripts ever share a machine, so the split needs no concurrency isolation
proof. Assignment is longest-processing-time bin packing over measured
per-script duration hints, balancing every shard to 285941 ms (~4m46s) of
expected work, and the timeout tightens from 20 to 15 minutes.

bin/fm-test-run.sh owns the shard count and refuses a lane whose "ofN"
disagrees with it, while ci.yml derives the same count from
strategy.job-total rather than a literal, so changing it in either file
alone fails the lane loudly instead of leaving part of the required suite
unrun. --check-coverage additionally proves the shards are non-empty,
disjoint, and exactly equal to the serial lane. No test is weakened,
skipped, or removed.

Also replace the wall-clock sleeps in the --jobs scheduler test fixture
with an explicit signal handshake between the fixtures. The old
0.5s-versus-0.05s race failed on a loaded machine; the handshake passes
under sustained CPU saturation.

* no-mistakes(review): Correct portable serial shard balance evidence

* no-mistakes(document): Document portable serial shard evidence accurately

* fix(bin): correct session lock and attached watcher supervision (kunchenguid#1545)

* fix(bin): identify harness sessions by path and report delivered wakes

Two supervision faults, both reported by a contributor and both open on the
default branch.

Fault 1: the Stop auto-arm never claims the home. fm_harness_ancestry_pid()
matched only the basename of `ps -o comm=`, and Claude Code's native installer
names the per-session executable by its version (.../share/claude/versions/
2.1.220), so that basename identifies nothing. Three real failure shapes follow:
a version-named session is missed entirely and the hook exits 0 with the epoch
never written (unconditional on Linux, where procps reports the kernel exec name
and ignores argv[0]); a claude-named daemon that directly parents sessions wins
the outermost-contiguous-claude rule ahead of the session itself; and a session
that is both version-named and daemon-parented has its live lock reclaimed as
stale and rewritten to the shared daemon pid, corrupting the home's ownership
record.

Harness identity now also reads whole components of the executable path and of
argv[0], which is what both platforms still carry. Matching whole components
only keeps that widening safe: bin/fm-claude-stop-autoarm.sh and ~/.claude/hooks
scripts have no "claude" component. Ownership is then decided against the
session's whole contiguous harness ancestry rather than one chosen pid, which is
the honest form of the question the library already documents ("does the current
process descend from that same harness?"). That subsumes the outermost-pid rule
for Claude's nested bg-spare worker chain instead of reverting it, and lets a
daemon-parented session recognize its own lock. Lock acquisition still writes the
outermost pid of the run, the only pid that lives as long as the session.

Fault 2: an attached arm reports a delivered cycle as FAILED. The watcher prints
its one reason line to its own stdout, so only the arm that forked it can read
that line; an arm that attached observes nothing but a released lock and called a
completely successful cycle "cycle ended without an actionable reason". No
supervision event was lost - the durable queue held it - but every harness
protocol reads that line as "supervision is down" and directs a manual re-arm.

The arm now resolves an unobservable close against the durable wake queue, which
records every wake before the watcher prints it and whose sequence counter never
rewinds, not even across a drain. A cycle the queue proves delivered a wake
reports that wake and exits 0; a cycle whose records a handling turn already
drained reports the delivery without inventing a reason line; only a cycle that
delivered nothing is still the typed nonzero failure. Fixing it in the arm covers
codex, opencode, pi, grok and kimi, not just the Claude Stop path.

Regressions: tests/fm-session-lock-ancestry.test.sh pins both platforms' ps
semantics behind a deterministic process table and runs the real Stop auto-arm in
version-named, daemon-parented, and combined real process trees, each orphaned so
the walk cannot escape the fixture. tests/fm-watch-arm.test.sh drives a real
watcher and a real attached arm through a real wake. Every fault case fails on
the previous code.

* no-mistakes(review): Bind watcher delivery records to process identity

* no-mistakes(review): Return validated watcher identity atomically

* no-mistakes(review): Track watcher successors by PID and identity

* no-mistakes(document): Consolidate watcher arm-cycle documentation ownership

* fix(bin): harden Claude supervision auto-arm recovery (kunchenguid#1495)

* fix(supervision): harden Claude auto-arm failure handling

* no-mistakes(review): Guarantee automatic retry after Claude auto-arm failures

* no-mistakes(review): Gate attended fail-open on verified supervision failure

* no-mistakes(document): Document Claude auto-arm retry and guard scope

* no-mistakes: apply CI fixes

* fix(supervision): make Claude fail-open progression monotonic

* no-mistakes(review): Preserve auto-arm failure episodes until verified watcher recovery

* no-mistakes(review): Linearize auto-arm failure progression across existing locks

* no-mistakes(review): Linearize positive recovery across shared failure episode lock

* no-mistakes(review): Scope Claude recovery contention to Claude guard mode

* no-mistakes(document): Align supervision auto-arm documentation

* no-mistakes(review): Preserve actionable wakes despite healthy successors

* no-mistakes(document): Refresh supervision auto-arm documentation

* no-mistakes: apply CI fixes

---------

Co-authored-by: Kun Chen <[email protected]>
sbracewell64 added a commit to sbracewell64/firstmate that referenced this pull request Aug 3, 2026