Kern
On this page

Test-runner sharding: measurement and design

Status: design + measurement only. No production code changed by this document. Branch test-sharding, worktree /Users/franciscosainzwilliams/.cip/worktrees/llm-lang-test-sharding, based on fa8b021. All instrumentation was built in throwaway trees outside the repository ($TMPDIR/ts1-scratch, $TMPDIR/ts1-kern-instr) and is not committed.

This document does five things:

  1. measures where the wall time of kern test actually goes, for both compilers (build/kern-stage0 and the self-hosted build/kern);
  2. shows which of those terms sharding can and cannot remove, with a hard ceiling;
  3. specifies a sharding design that preserves every observable behaviour of today's runner;
  4. compares the three candidate designs from the brief and recommends one, with cost, risk and size;
  5. lists the exact files, tests and acceptance criteria.

0. TL;DR

  • kern test compiler today is 78 tests (the brief quotes 76; the suite has 78 on this base commit), 225 files, 36 680 lines. --jobs gives 1.09x (stage0: 5.02 s → 4.62 s) and 1.12x (self-hosted: 17.02 s → 15.20 s) — the brief's symptom (CPU/real ≈ 1) reproduces exactly.
  • The brief's attribution is not what the data shows. Serial single-image codegen is 0.3 % of wall for stage0 (14.9 ms) and 11 % for the self-hosted compiler (1.73 s of 15.6 s).
  • The binding constraint is one test: frontend: semantic checker accepts the entire compiler source and its concrete instances (compiler/src/frontend/finish.kn:723) costs 2.64 s of 2.99 s (88 %) of stage0 test time and 10.51 s of 11.39 s (92 %) of self-hosted test time. No scheduling change can go below the longest single test.
  • Measured ceiling for any sharding design on today's suite: 1.13x for both compilers (perfect parallel codegen, perfect load balance and zero dispatch overhead). The executor itself scales fine: on a synthetic balanced corpus of 16 CPU-bound tests the same runner goes 0.23 s → 0.03 s (≈7.5x at --jobs 8).
  • Recommendation: build design B (parent selects once → forked workers emit a shard, package and execute it) as the target shape, because it is the only one that does not multiply the 1.6–2.5 s front-end and the only one that can later parallelize codegen; but ship it as B0 (shard the packaging + execution, one parse) and gate B1 (split emission so codegen is itself parallel) on a suite that no longer has a 10 s single test. Ship --shard i/N first: it is ~60 lines, needs no in-compiler IPC, and is the only change that helps before the suite is rebalanced.
  • Prerequisite work that dwarfs sharding (do it first, it is not in this brief's scope): the 10.5 s self-check test is uncacheable by construction (it reads a directory, and test_inputs only snapshots single files — see §3.7), so even a warm cache still runs it. Removing just that one test from the warm path takes the run from 15.3 s to 5.3 s (2.9x); making all nine always-run io tests cacheable collapses it to the selection cost (2.7 s, 5.6x) — several times the entire sharding ceiling on today's suite (1.13x).

1. What the runner does today

Both compilers have the same two-level structure, and both are already "parallel execution, serial codegen".

1.1 stage0 (Rust, src/)

src/main.rs:163 → test_runner::run (src/test_runner.rs:101):

stepcodenotes
load sourcessrc/main.rs:118225 files
front end (parse, generics, check, contracts, test validation, ownership)src/main.rs:38-47, front()single-threaded
test_inputs::load + rules::enforcesrc/main.rs:158-160rules print and may exit
semantic fingerprints + local fingerprintstest_runner.rs:106-107whole program, once
cache version = kern-test-v3-<sha256(current_exe)>-<max_test_ms>-<cc>-<trace>test_runner.rs:108-110
cache read + selectiontest_runner.rs:111-113always-run rule: is_io && test_inputs.is_empty()
--list early returntest_runner.rs:115-130one line per test, program order
one runner image for all selected testsgen::gen_runner, src/gen.rs:382, generate(..., dispatch=true), gen.rs:390-493emits every non-test function, every kt_<i> test function, and one entry that dispatches on argv[1]
package / link the imageBackend::load, test_runner.rs:226JIT (test_mem) by default on macOS arm64, otherwise ELF/Mach-O writer or cc
executeexecute, test_runner.rs:303-347fork() + execv(binary, [global_test_index]), or Image::run(position); --jobs concurrent children; waitpid(WNOHANG) poll, 200 µs sleep; per-test timeout kill at :338-341; fork failure kills the whole batch at :319-322
reporttest_runner.rs:140-149ok <label> on stdout in selection order, FAIL <label> on stderr, passed map updated, cache written once

The memory backend deserves attention because it changes what "sharding" can mean: test_mem::Image::load (src/test_mem.rs:20-88) resolves the symbol kt_<i> of every selected test and stores a direct entry address per test in entries (:73-75); Image::run(index) (src/test_mem.rs:90-96) writes the global test index into the kern_test_index data slot and calls that entry address. So on the JIT path the image already has one entry stub per test, and tests are already independently enterable. Only the binary path uses argv[1] + the dispatch chain.

1.2 Self-hosted (Kern, compiler/src/)

compiler/src/driver/compile.kn:76-92 → runner.run (compiler/src/runner/run.kn:31):

stepcode
load + parse + check + inputs + rulesdriver/compile.kn:54-90
fingerprints, cache path, cache versionrunner/run.kn:37-51, testcache/cache.kn:79-102
selection (always() at run.kn:93-96)run.kn:55-71
--listrunner/list.kn:53-137
one runner imagerunner/paths.kn:8-13 → backend.generate_runner (backend/generate.kn:24)
package / linkrunner/selected.kn:66-90 (testimage.package + image_open, or toolchain.executable + cc)
executerunner/processes.kn:95-161 (image_spawn or spawn_process, capture files case-<pos>.out/.err, --jobs active set, timeout at :143-149)
reportrun.kn:156-183 (captured() replays each test's captured stdout/stderr in order), cache update, run.kn:185-194 local hashes

Note the self-hosted executor already captures per-test output and replays it in selection order (processes.kn:62-84), whereas stage0's children inherit the parent's stdout and interleave freely. Sharding stage0 therefore requires adopting per-test capture (§4.5).

1.3 There is no --time breakdown for tests

--time exists for check/build/asm in both compilers (stage0: src/main.rs:89,173,203; self-hosted: driver/compile.kn:83-85, options.parse), and both test paths return before any timing is printed. So the split in §3 was obtained by instrumenting a scratch copy (§2.2).


2. Method

2.1 Machine and load

MachineApple M3 Max, 16 logical cores (12 performance + 4 efficiency), 48 GiB
OSmacOS 26.5.2 (Tahoe)
Compilerrustc -O stage0 (build/kern-stage0, 2 046 344 B), self-hosted build/kern (1 068 064 B)
Commitfa8b021 (test-sharding)
Loadshared machine, 5 logged-in users; load average 3.2 – 9.3 during the runs (measured start 3.25, later 9.25)
Replicationevery figure in §3 is the median of 3 consecutive runs unless stated; variance between runs is 1–5 % for phase times under 1 s, up to 15 % for the front end when the machine is busy

Because the machine is shared and loaded, absolute totals carry ±10 %; the ratios (codegen : execution : front end : single test) were stable to ±2 % across runs, and those ratios are what the design depends on.

2.2 Instrumentation (scratch only, not committed)

Neither compiler prints a per-phase breakdown for kern test, so two scratch trees were used:

  • $TMPDIR/ts1-scratch — stage0 sources copied, wall clocks inserted in src/main.rs (source load, front, test_inputs::load, rules::enforce) and in src/test_runner.rs (fingerprints, exe hash + version, cache read + selection, gen_runner with assembly bytes, Backend::load, execute, per-child wall time). Rebuilt with rustc -O --edition 2021 -o kern-instr src/main.rs; prints only when KERN_TEST_TIME is set.
  • $TMPDIR/ts1-kern-instr — full copy of the worktree; mark() helpers added to compiler/src/runner/run.kn and compiler/src/driver/compile.kn, plus a per-child completion timestamp in compiler/src/runner/processes.kn. Rebuilt with the repo's own .cip/build-kern.sh (stage0 compiles the instrumented compiler).

Instrumented binaries were verified to produce identical test outcomes and identical ok lines as the shipped binaries; only stderr gained TIME/TIMEF/CHILD lines. Overhead is one clock_ns() per phase (< 1 µs) and was not measurable against run-to-run noise.

Note: the repo's own duplicate_code rule (R050) fires on two identical mark() helpers in two modules, so the second one is named markf with a different prefix. This is a scratch-tree quirk.

2.3 Commands

# whole-suite ladder, both compilers, medians of 3 (§3.3)
for k in kern-stage0 kern; do for j in 1 2 4 8 12; do
  ./build/$k test compiler --no-cache --jobs $j
done; done

# breakdown (§3.1, §3.2)
KERN_TEST_TIME=1 $TMPDIR/ts1-scratch/kern-instr test compiler --no-cache --jobs 1
$TMPDIR/ts1-kern-instr/build/kern test compiler --no-cache --jobs 1

# codegen sensitivity to the test set (§3.6)
./build/kern asm      compiler --time > /dev/null     # no test bodies
./build/kern asm-test compiler --time > /dev/null     # with test bodies

# cache / variants (§3.7, §3.8)
./build/kern test compiler --jobs 8          # warm
./build/kern test compiler --list            # selection only
./build/kern test compiler --no-cache --jobs 8 --cc
/usr/bin/time -l ./build/kern test compiler --no-cache --jobs 8

3. Measurements

3.1 Stage0 breakdown — 78 tests, --no-cache --jobs 1

Median of 3 runs. "Pct" is of a 4.69 s total (sum of the phase column).

phasemspct
load 225 sources5.90.1 %
front end (parse+generics+check+contracts+validate+ownership)1 55533.2 %
test_inputs::load0.010.0 %
rules::enforce97.82.1 %
test_hash::fingerprints (+ local)154.53.3 %
cache version (sha256 of the 2 MB executable)1.20.0 %
cache read + selection (78 of 78 selected, --no-cache)0.160.0 %
gen_runner → 4 803 813 B of assembly14.90.3 %
Backend::load (JIT package + image_open)14.20.3 %
execute (78 children)2 81660.0 %
└ of which one child (test 37)2 375 – 2 585~50 %
report (ok lines) + cache write~300.6 %

Runner-internal summary printed by the binary: kern: 78 run, 0 cached (2994–3124 ms); process wall clock 5.00–5.58 s. The ~0.3 s difference between the sum above and wall clock is process start, page cache warm-up of the 225 sources on the first run, and the Drop cleanup of the temp binary directory.

3.2 Self-hosted breakdown — 78 tests, --no-cache --jobs 1

Median of 3 runs, total 15.6 s.

phasemspct
loader.load (225 files)13.30.1 %
parser.parse99.70.6 %
frontend.finish (semantic check — the dominant front-end phase)2 25314.5 %
inputs.load + rules.load/enforce (everything after finish)1971.3 %
testhash.fingerprints179.81.2 %
testcache.version (hash of 1 MB executable) + path20.70.1 %
testcache.read0.0020.0 %
selection1.290.0 %
gen_runner → 13 654 925 B of assembly1 734.911.1 %
prepare (image packaging + image_open / link)190.51.2 %
execute (78 children)11 191.971.7 %
└ of which one child (test 37)10 50867.3 %
report (ok/FAIL + captured output replay) + local hashes35.90.2 %

kern: 78 run, 0 cached (12 628–13 311 ms) is the runner-internal timer (run.kn:36 → summary at run.kn:98), i.e. fingerprints → report; it does not include the front end. Process wall clock over the same runs was 15.24–17.60 s (the spread is the machine load, §2.1).

Self-hosted codegen is 41x slower per byte than stage0's (13.65 MB in 1.73 s ≈ 7.9 MB/s vs 4.80 MB in 14.9 ms ≈ 322 MB/s) and emits 2.8x more bytes for the same program. That is a second, independent finding: the self-hosted backend is the only compiler where codegen is worth parallelizing at all.

3.3 --jobs ladder (the brief's symptom, reproduced)

Wall clock, median of 3, --no-cache:

jobsstage0speedupself-hostedspeedup
15.02 s1.00x17.02 s1.00x
24.62 s1.09x15.80 s1.08x
44.64 s1.08x15.90 s1.07x
84.69 s1.07x15.54 s1.10x
124.89 s1.03x15.20 s1.12x

CPU/real (stage0, /usr/bin/time -p): jobs 1 → user 4.54 s / real 4.99 s = 0.91; jobs 8 → user 4.48 s / real 4.34 s = 1.03. Self-hosted jobs 8: user 15.60 / real 16.69 = 0.93. So the machine is not saturated: the work simply is not parallel work.

Internal execute time, self-hosted: 11.15 s (jobs 1) → 9.80 s (jobs 8) → 9.76 s (jobs 16). The executor is fine; the corpus is not (§3.5).

3.4 Control: a balanced CPU-bound corpus scales ≈7.5x

To separate "the runner is serial" from "the suite is lopsided", a synthetic single-file suite was built with 16 identical CPU-bound tests, each summing 0..30 000 000 (~15 ms of work):

jobsstage0 wallspeedupself-hosted wallspeedup
10.23 s1.00x1.02 s1.00x
20.12 s1.9x––
40.06 s3.8x––
80.03 s≈7.5x0.17 s6.0x
160.03 s≈7.5x––

($TMPDIR/ts1-balanced/balanced.kn, rules relaxed via a local kern.rules: max_tests_per_fn raised to 100, duplicate_code, magic_number, format and test_helper_scope off. Both compilers include their front end in the wall time, which is why jobs 8 plateaus at ≈7.5x / 6.0x rather than 8x.)

Conclusion: the fork-per-test executor already scales linearly. --jobs fails on the compiler suite for two reasons only: one 10.5 s test, and a serial front end.

3.5 Where the test time actually is

Per-child wall times, --jobs 1, both compilers:

positionteststage0self-hosted
37frontend: semantic checker accepts the entire compiler source and its concrete instances2 636 ms10 508 ms
20frontend: module linking accepts compiler and rejects invalid qualified names146 ms325 ms
64parser: the parser accepts its complete compiler project113 ms242 ms
66sha256: SHA-256 standard vectors reusable state and padding boundaries20 ms122 ms
47loader: project loading preserves main first and sorted modules13 ms20 ms
39image: assembly symbols survive collisions and index growth7.7 ms10 ms
–remaining 72 tests, together53 ms152 ms
sum2.99 s11.39 s
median test0.8 ms2.0 ms
single largest / sum88 %92 %

--jobs N makespan is bounded by the largest test, so the best possible test-phase time is 2.64 s / 10.51 s for any N ≥ 2. Longest-processing-time bin packing over the measured times:

workersstage0 makespanspeedupself-hosted makespanspeedup
12.99 s1.00x11.39 s1.00x
22.64 s1.13x10.51 s1.08x
42.64 s1.13x10.51 s1.08x
82.64 s1.13x10.51 s1.08x
162.64 s1.13x10.51 s1.08x

Add back the parts no candidate design can remove (front end, fingerprints, one shared emission of the non-test functions, one packaging, the longest test) to get the hard ceiling:

stage0self-hosted
front end + source load + rules1.65 s2.45 s
fingerprints + cache version0.15 s0.20 s
shared codegen (non-test bodies, ~97 % of gen)0.01 s1.69 s
packaging one image0.01 s0.19 s
longest test2.64 s10.51 s
floor4.46 s15.04 s
today5.02 s17.02 s
maximum speedup from sharding1.13x1.13x
(hypothetical: shared codegen also parallel)1.13x1.27x

No candidate design in §5 parallelizes the shared emission (they only split test bodies, ~45 ms of 1.73 s for the self-hosted compiler), so 1.13x is the real ceiling for both compilers today.

What the numbers look like after the suite is rebalanced, i.e. if test 37 were split into 8 equal pieces of the same total cost (the same work, measured, just partitioned):

stage0self-hosted
test-phase makespan at 8 workers (LPT)0.48 s1.64 s
wall (front + fingerprints + one image per shard: codegen + packaging + makespan)2.31 s (2.2x)6.18 s (2.75x)
shared-codegen share of that wall0.7 %27 %

So codegen parallelism becomes worth designing only after the single-test problem is solved, and only for the self-hosted compiler.

3.6 Codegen is nearly insensitive to the test set

gen_runner emits every non-test function plus every test function. To find out how much of the codegen is "the tests" (the only part a test-index shard could omit), compare a normal build with the test build (--time prints front+codegen):

asm (no test bodies)asm-test (with test bodies)delta = test bodiesassembly bytes
stage01 578 ms (1 553–1 584)1 570 ms (1 564–1 575)≈ 0 (noise)4.55 MB → 4.80 MB (+5.5 %)
self-hosted3 818 ms (3 668–3 915)3 870 ms (3 861–3 907)≈ 50 ms12.58 MB → 13.72 MB (+9.1 %)

Test bodies are ~3 % of self-hosted codegen time and ~0 % of stage0's, while being 5–9 % of the bytes. Any design that shards by selected test index therefore re-emits ~97 % identical shared code once per shard: codegen work goes up by N×, and only becomes parallel if the shared part is emitted once and concatenated (§5.2 B1).

3.7 Cache behaviour, and why the slow test never gets cached

Warm-cache runs (default cache on, after a full successful run), --jobs 8:

summarywall
stage0kern: 9 run, 69 cached (2809 ms)4.49 s
self-hostedkern: 9 run, 69 cached (12667 ms)15.29 s

Only 69 of 78 tests can be cached. The other 9 are test io with no declared inputs, and the selection rule is always for them (test_runner.rs:113, run.kn:63-70, always() at run.kn:93-96). One of those 9 is test 37 — which is 67 % of the self-hosted wall time:

run frontend: semantic checker accepts the entire compiler source and its concrete instances: test io always runs

Test 37 calls loader.load("compiler") + parse + finish, i.e. it reads a directory tree. test_inputs can only snapshot single files (src/test_inputs.rs:3-10), and a test with declared inputs is rejected by test_runner::validate if it reaches any untracked filesystem builtin (E126, test_runner.rs:58-68; the self-hosted equivalent in frontend). So there is no way to make this test cacheable today, and it is re-run in full on every kern test compiler, even unchanged. --list confirms it: --list takes 1.85 s (stage0) / 3.08 s (self-hosted), and the cached path still spends 12.7 s inside the runner.

This is the single largest inefficiency in the test workflow, and it is orthogonal to sharding:

changeself-hosted warm runspeedup
today15.3 s–
cache test 37 only (directory-input fingerprinting, new cache concept)~5.3 s2.9x
cache the other eight always-run io tests too~2.7 s5.6x
+ full sharding (design B, best case, today's suite)15.0 s1.13x
+ full sharding after splitting test 376.2 s2.75x

(Estimates for the cache rows are measured-total minus the measured cost of the tests that would be skipped; they still pay the front end, fingerprints, one codegen and one packaging.)

3.8 Other measured variants

variantstage0self-hosted
--list (selection only, warm)1.85 s3.08 s
--list --no-cache1.86 s3.29 s
--no-cache --jobs 8 --cc (assemble + link 4.8 MB / 13.7 MB of asm)6.48 s (runner 4 695 ms)18.62 s (runner 15 704 ms)
peak RSS of the compiler process, --jobs 8208 142 336 B (198 MiB)209 879 040 B (200 MiB)
--forceidentical to --no-cache for timing (skips the read, still writes)same

--cc adds ~1.8 s (stage0) / ~2.7 s (self-hosted) of packaging, per image (assembling and linking 4.8 MB / 13.7 MB of assembly). A sharding design that builds one image per shard pays that per shard on the --cc path (§5).


4. Design: sharding the runner

4.1 Invariants (must hold for every N, including N = 1)

  1. stdout is byte-identical to today: one ok <label> per passing test, in program order.
  2. stderr contains the same diagnostic lines: FAIL <label>, trap: ..., kern: test process N exited with status S, kern: max_test_ms: test N exceeded N ms, kern: cannot ....
  3. exit code 0 iff every selected test passed.
  4. every test runs in its own OS process; no test can observe or damage another.
  5. --list, --no-cache, --force, --audit, max_test_ms, same_path_test behave as today.
  6. the cache file content after a sharded run is byte-identical to the unsharded run.
  7. N = 1 executes exactly today's code path (no worker, no capture change, no extra fork).
  8. no test is ever reported twice or silently dropped — including when a worker dies.

4.2 Shard planning

Given selected = [i0, i1, … i(m-1)] (program order, as produced today) and jobs:

W       = clamp(jobs, 1, m)                 # workers
shard(k) = { selected[p] : p mod W == k }   # round-robin over positions
  • Round-robin, not contiguous: cost is unknown at plan time and the expensive tests are neither first nor last; round-robin also keeps --shard i/N composable with harness fan-out.
  • W is clamped to the selection size (1 test → 1 worker, no worker overhead) and to available_parallelism().
  • Empty shards are never spawned (important for the warm-cache case where 69 tests are skipped).
  • The plan is a pure function of the selection and jobs; it is never persisted, so a cache hit that changes the selection only changes the plan, never any key.

For cross-machine fan-out the same function is exposed as --shard k/N (0-based, N explicit, independent of --jobs): the union over k of shard(k) with N fixed is exactly selected, so CI can split a suite across machines and each machine can still use --jobs internally.

4.3 Per-shard image and the child contract

gen_runner becomes gen_runner_shard(prog, target, shard):

  • emit all non-test functions (tests call them; this is the 97 % that cannot be dropped),
  • emit kt_<i> only for i ∈ shard,
  • emit ktn_<i> / trap tables only for i ∈ shard,
  • keep the dispatch comparisons against the global program index (kt_<i> numbers stay global), so the child contract is unchanged: execv(binary, [global_test_index]) and Image::run(position) with image.tests[position] = global index.

Hazard, must be guarded. With a reduced dispatch table, a child launched with an index outside its shard falls through every comparison and exits 0 having run nothing — a silent false pass. Three cheap guards, all required:

  1. generate a cmp/b.eq table over exactly the shard's indices and a final mov edi, #125; exit (x64) / mov x0, #125; @SYS exit (arm64) for "index not in this image"; the executor treats 125 as a hard internal error, not a pass;
  2. the worker asserts shard.contains(global_index) before spawning each child;
  3. the parent asserts outcomes.len() == shard.len() before merging and fails the run otherwise.

4.4 Worker model

Why processes, not threads. Neither compiler has a thread pool to reuse: the self-hosted Kern runtime exposes spawn_process/wait_process/process_status/stop_process/sleep_ms and image_spawn, but no threads at all, and stage0 is a single-threaded Rust binary whose Prog (Vec<Func> with String bodies) would have to become Sync for scoped threads. Process-based sharding is therefore the only shape that works for both compilers, and it is also what gives the required isolation (§4.6). Threads are explicitly out of scope.

Stage0 (Rust) — real fork(). The parent has already parsed, checked, fingerprinted and selected. For each shard it fork()s; the child inherits the Prog by copy-on-write (no reparse, no re-read of 225 files), then:

child k:  asm   = gen_runner_shard(prog, target, shard k)
          be    = Backend::load(asm, shard k, target, cc, 0)      # JIT / ELF / Mach-O / cc
          outs  = execute(be, shard k, jobs = 1, timeout, quiet=false)
          write  <scratch>/shard-k.res   # u8 per position, in shard order
          _exit(0)
parent:   waitpid all workers, read result files, merge by global index, print, write cache

Per-test output: the shard worker redirects each test child's stdout/stderr to <scratch>/case-<pos>.{out,err} (the mechanism the self-hosted runner already has, processes.kn:38-84) and the parent replays them in global order. This is required because today stage0's children inherit the parent's stdout and would interleave across workers.

Self-hosted (Kern) — no fork builtin. The Kern runtime exposes spawn_process, wait_process, process_status, stop_process, image_spawn, image_open but not fork (compiler/src/builtins/names.kn:119). Two options:

  • B0-exec (no runtime change, recommended for v1): re-exec the compiler as kern test <path> --shard-worker k --shard-plan <file> --shard-results <file>. The worker re-loads and re-parses (it is design A's cost — 2.45 s each), but the parent still owns selection, ordering, output and cache, so all invariants hold and no new primitive is needed.
  • B0-fork (later): add fork() -> i64 to runtime_mac/part_*, runtime_arm/part_*, runtime_x64/part_*, runtime_jit/part_0.kn (a stub returning -1 in the JIT, where a compiler cannot fork usefully), plus the builtin table, signatures and SPEC. ~60 lines + docs. This gives true "no reparse" parity with stage0.

Note that image_spawn is a fork of the test image for a test index; it cannot be used to fork a compiler worker, which is why a separate primitive or re-exec is needed.

IPC. No pipes: each worker writes one small file per shard (a u8 outcome vector plus the captured per-test streams). This keeps the Kern side to write_file/try_read_file and the Rust side to std::fs, works identically on both compilers, and makes a crashed worker detectable (missing or short file ⇒ fail that shard's remaining tests).

4.5 Aggregation, ordering, exit code

merged = [None; m]
for k in 0..W:                      # deterministic order, irrelevant to output
    entries = read shard-k.res
    if entries missing or count != |shard(k)|:
        mark every test of shard(k) FAIL, print one kern: line naming shard k
    else: merged[position] = outcome
for p in 0..m:                      # program order == today
    print "ok <label>"  or  "FAIL <label>"

Ordering is already "all outcomes first, then print" in both runners (test_runner.rs:140-146, run.kn:156-183), so no per-test streaming is lost; output is simply printed by the parent instead of by the runner that executed the test.

4.6 Timeouts, traps, isolation

behaviourtodaysharded
per-test timeoutexecute kills at max_test_ms (test_runner.rs:338-341, processes.kn:143-149)unchanged, per test, inside the shard worker
worker watchdog–parent kills a worker that exceeds |shard| × max_test_ms + 5 s, marks that shard's unfinished tests FAIL, prints kern: shard k exceeded its budget
trap messagesprinted by the test process (gen.rs:376, runtime kern_trap)unchanged; replayed with the test's captured stderr
crash (signal)child status ≠ 0 ⇒ FAIL, others unaffectedsame; a whole worker crash is caught by the count check (§4.4 guard 3)
single-test isolationone fork/spawn_process per testunchanged — sharding adds a layer above the per-test fork, never merges tests into one process
max concurrent test processesjobs≤ jobs in total: W × per_worker_jobs ≤ jobs (recommended: per_worker_jobs = 1, W = jobs)

4.7 Cache correctness

  • No key change. The version string stays kern-test-v3-<sha256(exe)>-<max_test_ms>-<cc>-<trace> (test_runner.rs:109) and the self-hosted header stays kern-selfhost-test-v1 + executable hash + timeout + flags (testcache/cache.kn:79-102). --jobs and --shard are scheduling, not semantics: adding them to the version would invalidate the cache on every different --jobs and turn a warm run into a full re-run. Explicitly do not.
  • Parent owns the cache. Workers never read or write it (opts.cache = false in workers, internal flag on the Kern side). Reason: write_cache is atomic but last-writer-wins (test_runner.rs:95-98, testcache/cache.kn:190-198); if each worker wrote the map it built, the last worker would publish a map containing only its own shard's entries — silent, permanent loss of 7/8 of the cache. This is the strongest argument against design A.
  • Merge in program order with exactly today's rule: on pass insert T<identity> → fingerprint unless the test is always-run; on fail remove it; always overwrite all F<identity> local entries from local[] (test_runner.rs:140-148, run.kn:156-194). Because the merge order and the map are identical, the resulting file is byte-identical to the unsharded run (acceptance test #8).
  • Cost: the parent already computes hashes, local and version once (154 ms / 180 ms); sharding does not multiply it. Design A would multiply it by N.

4.8 Flag semantics

flagtodaysharded
--listone line per test, program order, then returnnever sharded; identical output
--jobs Nup to N concurrent test processestotal concurrency budget: W = clamp(N,1,m), one test at a time per worker
--shard k/N–select only slice k of N over the global selection (0-based); the slice is executed by the normal executor with the full --jobs budget; never combined with --list or --audit
--no-cacheno read, no writeunchanged (parent only)
--forceskip read, still writeunchanged (parent only)
--auditmutates the program per mutant and re-generates the runner (src/test_audit.rs:145-154)never sharded — inherently serial and mutation-dependent; leave alone
same_path_test (trace)one bitmap row per selected position, compared in order (test_runner.rs:190-206, runner/paths.kn:15-62)never sharded in v1 (would need global row indexing across processes); document it
max_test_msper testunchanged; plus the parent watchdog

4.9 Failure modes and their handling

failuretodaysharded
fork failskill all active children, error, exit 1 (test_runner.rs:319-322)kill all workers, error, exit 1
gen_runner_shard errorsone error, exit 1that shard's tests FAIL, error printed once, run continues
packaging / cc fails for a shardone error, exit 1same, scoped to the shard
worker dies (signal, OOM)n/aresult file missing/short ⇒ that shard's tests FAIL, run continues, exit 1
scratch dir cleanupDrop for Backend removes the per-run dir (test_runner.rs:215-223), cleanup() on Kern sideone dir per worker, removed by the parent after merging; bounded by W × image bytes
output explosiona test's stdout goes to the terminal unboundedbehaviour change: capture to a file; cap each stream (e.g. 1 MiB) and append a truncation marker, or keep direct inheritance when W = 1

5. Design comparison

All three are compared on today's suite (78 tests) and on the rebalanced scenario from §3.5. "Today" = measured; "rebalanced" = the same total test work with test 37 split into 8 equal parts.

5.1 Design A — N compiler processes, each select + codegen + execute

kern test compiler --jobs 8 becomes: 8 kern processes, each with --shard k/8, each doing load → parse → check → rules → fingerprints → select → codegen (whole image) → package → execute its shard → print its own outcomes. A parent (the harness, or kern shelling out to itself) orders the output, owns the cache and the exit code.

  • Per-worker cost: stage0 1.65 s (front) + 0.15 s (fingerprints) + 0.015 s (codegen) + shard execution; self-hosted 2.45 s + 0.18 s + 1.73 s + 0.19 s + shard execution.
  • Wall today: front + codegen + max shard = 4.5 s (stage0) / 15.0 s (self-hosted) — 1.13x / 1.13x, i.e. the ceiling, because test 37 is alone in its shard.
  • Wall rebalanced: 2.3 s (stage0, 2.2x) / 6.2 s (self-hosted, 2.75x).
  • CPU today: 8 × (1.8 s) = 14.7 s (stage0) and 8 × (4.55 s) = 36 s (self-hosted) for a 5 s / 17 s job — 3x / 2.2x more CPU than today, and on a 2-core CI box it is a pessimization (8 × 4.55 s / 2 cores = 18 s > 15.6 s serial).
  • Buys: cross-machine fan-out for free (each machine runs --shard k/N with its own cache).
  • Risks: cache write contention (§4.7 — must be forbidden); output ordering; 8× sha256 of the executable; N× front end on every invocation.
  • Size: ~60 LOC for --shard k/N in each compiler (a modulo filter in the selection loop: test_runner.rs:112-113, run.kn:55-71) + ~80 LOC of orchestration if kern itself drives it.

5.2 Design B — parent selects once, forks workers that each codegen a shard and execute

Parent does load/front/fingerprints/select once, then forks W workers (§4.4). No reparse.

B0 (v1): each worker emits the full image with only its shard's dispatch table.

  • Wall today: front + max(codegen + package + execute_shard) = 4.5 s / 15.0 s → 1.13x / 1.13x.
  • CPU today: stage0 1.65 + 8×(0.015+0.015) ≈ 1.9 s (no worse than today); self-hosted 2.45 + 8×(1.73+0.19) ≈ 17.8 s (vs 15.6 s today — worse CPU, same wall).
  • Buys: packaging + execution are parallel; one parse; one cache writer; identical output by construction; the same code shape in both compilers once fork exists (or B0-exec for Kern).
  • Risks: fork-per-worker with a 200 MiB parent (copy-on-write page tables, ~1 ms — measured: today's per-test fork+exec costs 0.8 ms median, so this is negligible); output capture adoption in stage0; the reduced-dispatch false-pass hazard (§4.3); Kern needs fork or re-exec.
  • Size: stage0 ~220 LOC, Kern ~230 LOC (+60 if a real fork builtin is added).

B1 (later): split emission so codegen itself is parallel.

Three-phase generate: (1) shared non-test function bodies (emitted once by the parent), (2) shard test bodies (per worker, ~45 ms), (3) epilogue = entry stub + dispatch table + runtime + rodata/data (per shard, after the feature flags are known). The pieces are concatenated as assembly text per shard, then packaged.

  • Wall today: front + gen_shared + max(gen_test + package + execute_shard) = 4.5 s / 15.1 s → still 1.13x (test 37 again: 10.51 s of the 10.75 s shard).
  • Wall rebalanced: 2.3 s (stage0, 2.2x) / 6.2 s (self-hosted, 2.75x) — the same wall as B0. The win over B0 on the rebalanced suite is CPU, not wall (self-hosted 17.8 s → 6.2 s) because at W = 8 the largest shard (1.9 s: 0.045 gen + 0.19 package + 1.64 execute) already exceeds the 1.69 s duplicated shared emission, so duplicating it per worker is free in wall-clock terms. B1 only wins wall once the largest shard drops below ~1.7 s (W ≥ 16 on this corpus, or a much smaller program).
  • Risks: high. The generator carries cross-function state: label counter (must be partitioned per shard or namespaced), trap_used table, arena_used/io_used/system_used (union across shards decides which runtime sections the epilogue emits), mem offset base, string pool order, snapshots/trace_id. The assembly tail (src/gen.rs:477-492, backend/generate.kn:83-95) must be emitted after all function bodies are known, so the parent cannot emit one epilogue for all shards. Only worth it when codegen is ≥ 20 % of wall — true only for the self-hosted compiler after the suite is rebalanced (§3.5).
  • Size: ~250 LOC per compiler plus a rewrite of generate/generate_program; 2–3 days and a second design doc.

5.3 Design C — one image, multiple entry stubs, per-shard code pages

  • "Multiple entry stubs" already exists on the JIT path: Image::load records one entry address per test (src/test_mem.rs:73-75) and Image::run(index) jumps straight to kt_<i> (src/test_mem.rs:90-96). The binary path uses one argv[1] dispatch chain (gen.rs:436-441, gen.rs:462-467).
  • "Per-shard code pages" would mean emitting functions into separately-located pages and letting each shard fault in only its own. That changes page locality, not work: every shard still needs all shared functions, and the image is still produced by one generate call in one process.
  • Measured justification for rejecting it: image packaging is 14 ms (stage0) and 190 ms (self-hosted) — the only thing C could shorten — and it is already 1.2 % of self-hosted wall and fully overlapped with nothing. There is no measurement in §3 that C improves; it adds an image format change, a loader change and a second code-layout path in exchange for nothing.
  • Size: ~400 LOC + image format change; not recommended.

5.4 Comparison table and recommendation

A (N processes)B0 (fork, one parse)B1 (fork + split emission)C (multi-entry / pages)
speedup today (stage0 / self-hosted)1.13x / 1.13x1.13x / 1.13x1.13x / 1.13x~1.0x
speedup after rebalancing2.2x / 2.75x2.2x / 2.75x2.2x / 2.75x (CPU 3x lower)1.0x
extra CPU today3x / 2.2x1.0x / 1.14x1.0x / 1.05x1.0x
works on 2-core CIno (loses)yesyesyes
reparse per invocationN ×111
new runtime primitivenofork on Kern (or re-exec)sameloader/format
cache safetyneeds worker isolationparent-owned, safeparent-owned, safeparent-owned, safe
cross-machine fan-outyesnonono
implementation size~60–140 LOC~220 / ~290 LOC+250 LOC/compiler, high risk~400 LOC, format change

Recommendation: B, staged.

  1. Ship --shard k/N first (design A's selection half, ~60 LOC per compiler). It is orthogonal, it is what CI fan-out needs, it makes the sharding semantics testable without any IPC, and it costs nothing when unused. Do not let workers write the cache.
  2. Then build B0: parent selects once, forks W workers, each emits its shard's image, packages it, executes it, and writes a result file; the parent merges in program order and owns the cache. In stage0 use fork directly; in the self-hosted compiler use the re-exec worker first (--shard-worker) and add the fork builtin only if the 2.45 s front end turns out to matter on the shard path.
  3. Defer B1 and reject C. B1's prerequisite is a suite without a 10 s single test; C's prerequisite is a measurement showing packaging matters, and there is none.

Important expectation setting: on the compiler suite as it exists today, B0 delivers ≈ 1.1x, not 8x, and the same is true of every design in this document. The value of B0 is that it is the only shape that (a) does not multiply the front end, (b) keeps one cache writer, and (c) can be extended into B1 without redesign once the suite is rebalanced. If the goal is "make kern test compiler fast today", the work is §3.7 (cacheable directory-reading tests) and splitting the self-check test, not sharding.


6. Acceptance tests

Each test states the command and the exact expectation. Every case is timing-free except #11–#13.

Determinism and completeness

  1. Stable output order — kern test compiler --no-cache --jobs 1 and … --jobs 8 and … --jobs 16 produce byte-identical stdout (ok lines) and byte-identical stderr after stripping timings. Run 5× at --jobs 8; all 5 identical.
  2. No duplicates, nothing missing — stdout line count equals kern test compiler --list | wc -l (78 today) at every N; the multiset of labels equals the --list set exactly; no label appears twice.
  3. Plan is a partition — unit test of the shard function on synthetic selections (m = 0, 1, 2, 7, 78, 1000; N ∈ 1..16): shards are pairwise disjoint, their union is the selection, and sizes differ by at most 1.
  4. Outcome independent of N — a fixture project with 1 failing, 1 trapping and 1 passing test gives exit code 1, exactly one FAIL, exactly one trap: line, and one ok for every N ∈ 1..16.

Failure reporting

  1. Per-shard failure attribution — fixture with three tests spread over three shards: a normal assertion failure, a segfault, and a max_test_ms overrun. All three are reported, in program order, each naming its own test; the other tests in those shards still run and pass; exit 1.
  2. Worker death — kill a worker externally mid-run (SIGKILL); the run reports that shard's tests as FAIL, still reports the other shards' results, exits 1, and leaves no passing cache entry for the killed tests.
  3. Timeout preserved — with max_test_ms = 200 in kern.rules, a sleeping test fails with kern: max_test_ms: test N exceeded 200 ms and its shard-mates are unaffected.

Cache

  1. Cache equivalence — after a clean --force run, the file build/.kern-test/<hash>.cache is byte-identical for --jobs 1 and --jobs 8 (and for --shard 0/2 + --shard 1/2 merged by the harness: the union must equal the single-process file).
  2. Warm run unchanged — a second run prints N run, 78-N cached with the same N as today (69 cached / 9 always-run for the compiler project) at every --jobs, and spawns no worker for an empty shard.
  3. --no-cache writes nothing — no build/.kern-test file created or modified (mtime and content check); --force rewrites it exactly once.

Performance and resources (the only timing assertions)

  1. Speedup gate — on a project whose test corpus is rebalanced (no test > 15 % of the total), --jobs 8 vs --jobs 1 (median of 5) ≥ 2.5x. On the compiler suite as it is today the gate is "no regression": --jobs 8 ≤ --jobs 1 × 1.05, and CPU/wall ≤ 1.25 × jobs.
  2. Memory bound — peak RSS (/usr/bin/time -l) of the parent at --jobs 16 ≤ 1.25 × the current 208 MiB; the sum of worker RSS ≤ jobs × 260 MiB; temp bytes ≤ W × image bytes and the scratch directory is gone after exit (also after a kill -9 of a worker, via the parent's sweep).
  3. Overhead at N = 1 — --jobs 1 wall time within 2 % of the pre-change binary on the same machine (N = 1 must take today's path).

Parity and regressions

  1. Compiler parity — for the same fixture and the same N, build/kern-stage0 and build/kern produce identical stdout and exit codes; sh tests/test_selfhost_cli.sh build/kern-stage0 --host-only still passes with byte-identical stage2/3/4.
  2. Unsharded features intact — --list output equals a golden file; --audit output unchanged on a small fixture; same_path_test = on still reports R047 and disables sharding.
  3. Cross-machine composition — --shard 0/3, --shard 1/3, --shard 2/3 run sequentially against one cache produce the same stdout union and the same cache file as one --jobs 3 run.

7. Files to change

7.1 stage0 (src/)

filechangesize
src/test_runner.rsshard planning; --shard k/N; worker fork/waitpid; result-file read/merge; parent watchdog; ordered report; parent-owned cache; per-test output capture for sharded runs~180 / −40
src/gen.rsgen_runner_shard(prog, target, shard); thread the shard through generate/generate_program (test list at :404-416, dispatch comparisons at :436-441 / :462-467, ktn_ table at :484); out-of-shard trap (exit 125); keep gen_runner = gen_runner_shard(all) so N = 1 is unchanged~25 now, ~200 for B1
src/main.rsaccept and validate --shard k/N; keep --time; reject --shard with --list/--audit~10
src/test_mem.rsno change for B0 (pass the shard's tests slice to Image::load); B1 would need nothing either0
src/test_hash.rsno change — keys are per-test identity + semantic fingerprints, unchanged by sharding0
src/test_audit.rsno change — audit stays serial (run() → run_selected, :126, :145-154)0
cacheno format change, no version bump; parent read/merge/write stays in test_runner.rs:85-99,111,1480

7.2 Self-hosted compiler (compiler/src/)

filechangesize
runner/run.knshard plan from selected (:55-71); worker spawn/wait; result merge; ordered report (:156-183); parent-owned cache write (:78-81)~120
runner/selected.knrun_selected / Selection gain a shard; prepare (:66-90) packages a shard image~40
runner/processes.knexecute (:95-161) takes the shard's tests; global indices in messages; worker result files; watchdog~60
runner/paths.knrunner_assembly(program, settings, shard) (:8-13); keep compare_paths unsharded~15
backend/generate.kngenerate_runner_shard (:24-26) + mode bits for "only these tests"; out-of-shard trap; B1 adds the phase split of generate_program (:76-95)~15 now, ~250 for B1
testcache/cache.knno format/version change; optionally a merge helper for reading a worker's partial map — not needed if workers never write0–20
options/parse.kn (+ cli/dispatch.kn usage)--shard k/N, --shard-worker, --shard-plan, --shard-results (internal flags, not in usage text except --shard)~20
runner/list.knno change (never sharded)0
runtime_mac/part_*, runtime_arm/part_*, runtime_x64/part_*, runtime_jit/part_0.knonly for B0-fork: kern_fork (JIT stub returns -1)~40
builtins/names.kn (+ signatures, spec/print.kn)only for B0-fork: declare/document fork() -> i64~8 + docs
testhash/*no change0

7.3 Harness, bench, docs

filechange
tests/run.sh, .cip/features.shadd a --jobs 1/2/8 and --shard 0/2,1/2 matrix over the existing suites
tests/test_runner.shthe acceptance cases from §6 that belong to the runner suite
tests/test_selfhost_cli.shparity: stage0 vs self-hosted identical output at N = 1 and N = 8
bench/bench.pya sharded jobs curve (already reports test-job parallelism)
SPEC.md / compiler/src/spec/print.kndocument --shard (and fork if B0-fork lands)

7.4 Explicitly unchanged

src/test_mem.rs image format, src/elf.rs, src/macho.rs, src/rules.rs (timeouts/rules), testcache file format and version strings, --list/--audit/--force/--no-cache semantics, test_audit (stays serial).


8. Sequencing and risks

  1. --shard k/N alone (design A selection half). ~60 LOC/compiler, no behaviour change when unused. Unblocks CI fan-out and gives the shard function its own tests.
  2. Suite-shape work (out of this brief's scope, but the actual win): make directory-reading tests cacheable, and/or split the whole-project self-check test. Without this, every design here is capped at 1.13x.
  3. B0 (fork workers, one parse, parent-owned cache and output). Reaches the ceiling and prepares B1.
  4. B1 only if, after step 2, self-hosted codegen is still ≥ 20 % of wall.

Risks to watch, in order of severity:

  • False-pass on a reduced dispatch table (§4.3) — the only correctness hazard that can silently turn a failing test suite green. Guard with the exit-125 trap and the count check.
  • Cache corruption from multi-writer (§4.7) — parent-only writes, no exceptions.
  • Lost ok ordering / interleaved output — stage0 must adopt per-test capture before sharding; this changes what a test's own print does at --jobs > 1 (file, capped, replayed).
  • CPU pessimization on small machines — design A on a 2-core CI box is slower than today (measured front-end costs make 8 × 4.55 s / 2 cores = 18 s vs 15.6 s serial). B0 does not have this failure mode.
  • Machine load — all numbers in this document were taken on a shared, loaded machine (load 3.2–9.3). Ratios were stable; absolute totals ±10 %. Any performance acceptance test must be a median of ≥ 5 runs and should record the load average with the result.

Appendix A — raw per-test data (--jobs 1, --no-cache)

Position is the index in the --list output (0-based). Both compilers run the identical 78 tests.

posstage0 msself-hosted ms
372 636.010 508
20145.8325
64113.2242
6620.4122
4713.220
397.710
501.911
51.83
691.82
281.83
231.53
261.53
other 66≈ 43 total≈ 145 total

Sum 2.99 s / 11.39 s; max 2.64 s / 10.51 s; median 0.8 ms / 2.0 ms.

The exact per-test files (per-test-stage0.txt, per-test-selfhost.txt, ladder.txt, breakdown-stage0.txt, breakdown-kern.txt) are in $TMPDIR/ts1-data in the scratch environment used for this measurement and are not committed (they are machine- and load-specific).

Appendix B — instrumented patch points

Stage0 scratch (src/main.rs): before project::load/fs::read → load_sources; around front() → front; around test_inputs::load; around rules::enforce; src/test_runner.rs: around fingerprints+local_fingerprints, around std::fs::read(current_exe)+version, around read_cache+selection, around gen::gen_runner (with asm.len()), around Backend::load, around execute (with jobs), and per completed child inside execute.

Self-hosted scratch: mark(name, started) helpers in compiler/src/runner/run.kn (before label) and compiler/src/driver/compile.kn (as markf, to satisfy R050), emitted with (clock_ns() - started) / 1000 µs; marks around testhash.fingerprints, testcache.path+version, testcache.read, the selection loop, runner_assembly, prepare, execute, the report loop, and run_tests as a whole; a per-child clock_ms() - child.started print in runner/processes.kn.

Both instrumented builds reproduce the shipped binaries' outcomes and ok lines exactly; only stderr is extended. clock_ns() in the Kern runtime is wall-clock (verified: internal summary 1 036.81 ms vs external 1.03 s on the balanced corpus).

Appendix C — cache format (unchanged by sharding)

stage0self-hosted
pathbuild/.kern-test/<sha256(canonical input path)>.cache (test_runner.rs:78-83)same (testcache/cache.kn:56-71)
headerfirst line = version string (test_runner.rs:87-88)magic 1262834254 + 32-byte digest (cache.kn:19,124-127)
versionkern-test-v3-<sha256(current_exe)>-<max_test_ms>-<cc>-<trace>sha256("kern-selfhost-test-v1" ‖ sha256(exe) ‖ timeout ‖ flags) (cache.kn:79-102)
entryT<hex identity> → test fingerprint; F<hex identity> → local fingerprint; TAB separatedkind(1|2) + key digest + value digest, 72 B (cache.kn:8-21)
identitysha256(path ‖ module ‖ name ‖ is_test) (test_runner.rs:26-30)same fields (cache.kn:34-54)
writetemp file …<pid>.tmp + rename (:95-98)…tmp-<pid> + rename (:190-198)

Sharding changes when entries are merged, never what they are. Do not add --jobs or --shard to the version string.

Source: TEST-SHARDING.md in the repository.