Skip to content

feat(experiments): M6 — E2 reconstruction cost + E5 budget enforcement - #3

Merged
pdettori merged 12 commits into
mainfrom
feat/m6-experiments
Jun 25, 2026
Merged

pdettori merged 12 commits into
mainfrom
feat/m6-experiments

Conversation

@pdettori

Copy link
Copy Markdown
Member

M6 — Experiments E2 + E5

Turns the M5 openFromCheckpoint loader and budget voter into reproducible, asserted experiments in a new in-process TypeScript experiments/ (@sh/experiments) vitest workspace. One production change makes the model a runtime input. No pi-fork edits.

Spec: docs/specs/2026-06-24-m6-experiments-design.md · Plan: docs/superpowers/plans/2026-06-24-m6-experiments.md

E2 — local reconstruction cost

Measures Redis read volume (entries + bytes) for openFromCheckpoint vs openFromBackend across synthetic compacted sessions, via a CountingBackend decorator (no pi-fork change, no LLM). Honest framing per the M5 spec §1: this is the loader's local win — Pi's native compaction already bounds the LLM context, so end-to-end latency is the wrong metric.

N backend entries checkpoint entries ratio
50 53 6 8.8
200 203 6 33.8
1000 1003 6 167.2
5000 5003 6 833.8

Checkpoint reconstruction stays constant at 6 entries while the full read grows linearly — the backend/checkpoint ratio increases with N. buildSessionContext() parity holds at every N. Gate asserts series-completeness + strict-monotone ratio + parity (non-vacuous).

E5 — budget-voter enforcement

  • Structural gate (no key, real Redis): drives the real budgetVoterExtension past the cap → tool call blocked + exactly one abort persisted to Redis; inert (no block, no abort) when the cap is disabled.
  • Live (key-gated): tiny-cap real-model run, skips cleanly without SH_RUN_LIVE + key. Not the pass gate.

Production change

Model + provider are now runtime inputs in harness/src/run-turn.ts — resolveModelSelection (config > SH_MODEL/SH_MODEL_PROVIDER > default), plus TurnConfig.model?/provider?. Defaults preserved → M4/M5 unchanged. No secrets in the repo; see experiments/README.md for how to pass model + credentials to the live run.

Test status

  • @sh/session-backend 10/10 · @sh/experiments 7 pass + e5-budget-live skipped · @sh/harness 25 pass.
  • The one harness failure (run-turn.test.ts, stopReason "stop" vs "end_turn") is pre-existing and unrelated to M6 — that test is ungated and makes a real gateway call. Suggest a separate tracking issue (also covers the pre-existing run-turn.ts x-api-key: null tsc cast).

Deferred (non-blocking, from final review)

  • E5 inert test asserts limit:0 (voter internal disable) rather than the production "SH_BUDGET_TOKENS unset ⇒ voter never registered" path (guard at run-turn.ts is correct by inspection).
  • Live E5 omits the spec §4.7 stopReason assertion (checks abortCount===1 only).

Sequel

E1 / E3-mobility / E4 are end-to-end cluster experiments deferred to M7 (need the M4 Knative deploy + a live model). E3's fidelity half is already satisfied by the M5 parity gate + M6/E2 parity.

Assisted-By: Claude Code

Paolo Dettori added 12 commits June 24, 2026 10:50
E2 (local reconstruction cost) and E5 (budget enforcement) as an
in-process TypeScript experiments/ workspace. E2 measures Redis read
volume for openFromCheckpoint vs openFromBackend across session lengths
(no LLM); E5 gates on a no-key structural block+single-abort assertion
plus a key-gated tiny-cap live run. One production change: model +
provider become runtime inputs in run-turn.ts. No pi-fork edits.
Defers E1/E3-mobility/E4 to a sequel cluster milestone (M7).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…results

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assert rows.length === Ns.length before the strict-monotone ratio loop so a
mid-loop failure (e.g. Redis hiccup at N=5000) fails loudly instead of passing
on incomplete data.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ort + inert)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Add a Background block to §4.5 clarifying what E2 exercises: why the kept
tail sits before the compaction entry, why Redis seeks by position not
content-id, and why the resume-position marker makes cold start O(tail)
instead of O(total).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The headless runTurn path never emits session_start (only bindExtensions /
interactive / print / rpc modes do), so the voter's session_start-derived
baseline stayed null and every tool_call hit the null guard and no-opped —
the voter never fired against a live model. The M5 unit + E5 structural tests
masked this by invoking session_start manually.

Fix: drop the session_start dependency. run-turn computes the pre-turn
baseline from the loaded branch (branchSpend) and injects it via opts.baseline
(default 0), so resumed-session loaded-tail spend is still excluded. Tests now
fire only tool_call (no session_start), mirroring production; added a baseline-
subtraction case. branchSpend exported for the caller.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit eb17533 into main Jun 25, 2026
1 check passed
@pdettori
pdettori deleted the feat/m6-experiments branch June 25, 2026 21:14
pdettori added a commit that referenced this pull request Sep 15, 2026
…k 17)

Implements spec §6's #1 practical failure mitigation: a worker crash leaks
VMs. Adds the containment and cleanup layer sitting under both launcher
arms:

- internal/vmpool/cgroup.go (+cgroup_linux.go/cgroup_other.go build-tag
  split): SweepOrphans walks a systemd slice's VM cgroups, kills every pid
  in cgroup.procs (ignoring ESRCH), and rmdirs the directory (D5: rmdir,
  never rm -rf). Arm-agnostic by design (D3) and pid-based rather than
  name-based (D8: cloud-hypervisor's comm is truncated to 15 chars by the
  kernel, so a pgrep/pkill -x match would silently miss that arm).
  RaiseMemlockLimit raises RLIMIT_MEMLOCK soft to hard at worker start
  (spec §7.5: a kernel limit mistaken for a density ceiling fails at 500
  VMs after working at 20, indistinguishably from the real thing).

- launcher_firecracker.go: adds the missing --cgroup jailer flag (D1).
  --parent-cgroup alone only relocates the jailed process into the shared
  slice; it does not create a per-VM cgroup or set memory.max, so spec
  §6's mitigation #3 (ballooning command killed inside its own cgroup) was
  unimplemented. CgroupMemoryMaxBytes is now validated as required
  whenever ParentCgroup is set.

- launcher_chv.go: Cloud Hypervisor has no jailer equivalent, so its
  launcher places the VMM in a systemd-run --scope under the same parent
  slice instead (D3), with the same memory.max bound (D1). The
  unchrooted, unprivileged-uid virtiofsd confinement gap (D4) is
  documented in the package comment as a reasoned finding rather than
  shipped silently.

- cmd/microvm-worker/main.go: calls RaiseMemlockLimit and SweepOrphans
  before Probe, in the same fail-at-start posture as the rest of this
  block. Threads vmpool.PerVMBytes(cfg) through a new launcherFor
  parameter into both arms' CgroupMemoryMaxBytes, closing the gap where
  the admission-control budget and the actual cgroup bound could drift
  apart (D1: "two numbers that can drift is the bug").

- deploy/microvm/microvm-vms.slice, microvm-worker.service: the systemd
  slice and unit that own the cgroups (KillMode=control-group,
  Slice=microvm-vms.slice, AssertPathExists=/dev/kvm, LimitMEMLOCK=
  infinity, MemorySwapMax=0 on the slice).

- deploy/microvm/tests/systemd-units.test.sh: cluster-free, root-free,
  systemd-free checks on the unit files' contract, including a D8 guard
  against a name-based pkill/pgrep -x cloud-hypervisor trap and a
  slice/service cross-consistency check. Picked up automatically by
  make test-deploy's existing glob.

Verified: go build/vet/test -race clean across the whole module; gofmt
clean; make test-deploy passes including the new shell test; shellcheck
clean. Mutation-tested both of the tests most load-bearing for this task
by deliberately breaking the implementation, confirming the test failed,
restoring, and confirming it passed again:
TestFirecrackerJailerCgroupMemoryMaxAgreesWithPerVMBytes (mutated the
jailer's memory.max value) and TestSweepOrphansFindsEveryLeftoverVMCgroup
(mutated sweepOneCgroup to skip directory removal). A grep across the
whole branch found no pkill/pgrep -x cloud-hypervisor invocations (D8).

What could not be run: anything needing a real cgroup write, a real OOM
kill, or a real jailer/systemd-run/systemd invocation (no KVM host, no
root in this environment) — the brief's Step 8 crash-test procedure is
unexecuted, not merely unverified, and is not claimed as passing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
pdettori added a commit to pdettori/moca that referenced this pull request Sep 22, 2026
…bounded case (rossoctl#319 review)

Six findings. All reproduced before changing anything; the first is a correctness bug
that only appears concurrently.

MUST-FIX: the mkdir rollback could alias a live holder. acquire rolled `minted` back
when mkdir failed, which is correct single-threaded and wrong concurrently:

  A: seq=5, minted -> 6
  B: seq=6, minted -> 7, mkdir pool-6 OK      <- B holds pool-6
  A: mkdir pool-5 FAILS -> minted-- -> 6
  C: seq=6 -> mkdirAllCgroup(pool-6) returns NIL (it exists, and is a dir)
  C: writeMemoryMax, returns pool-6           <- C holds pool-6 too

Two VMMs then share one memory.max. That is D1 inverted -- admission control charged
2 x PerVMBytes while the kernel enforces a single bound over both -- so a ballooning
command in one can OOM the other's VMM, which is the outcome spec section 6 mitigation
rossoctl#3 exists to prevent. The fallout is mis-recorded as well: whichever destroys first
spins in waitForCgroupEmpty on the other's pid and counts a leak, then the second finds
it empty and pushes the SAME rel back onto free, leaving it both leak-counted and
reusable.

Reachable rather than theoretical: mkdirAllCgroup fails when the parent slice is gone,
which clearing the slice by hand does (metal runbook step 3a), and at 64 slots
concurrent acquires are the steady state.

Fixed by deleting the rollback. The counter is renamed `issued` and documented as a NAME
ALLOCATOR that never goes backwards -- an int is free, a name is not. Making the rollback
safe would mean holding mu across the mkdir, serialising the syscall this change exists
to keep off the critical path. mintedCount() now reports names allocated, which after a
failed mint exceeds the number of cgroups; no test depended on the difference.

Pinned by TestCgroupPoolNeverReclaimsANameAfterAFailedMint. The collision itself needs
concurrency to stage, so the test pins the invariant that prevents it -- a name used by a
failed mint is never handed out again. Re-introducing the rollback fails it.

SUGGESTION: acquire now verifies a popped entry and rebuilds it under the same name if it
vanished. The guard was asymmetric -- release insisted the directory still be there,
acquire trusted a rel that may have disappeared while idle -- and the review pointed out
that idle entries are the MOST exposed: an idle pooled cgroup is empty so rmdir succeeds,
while a live VM's is EBUSY and survives, so clearing the slice removes precisely what is
in `free`. It self-healed at a cost of one failed restore per stale entry, and `free` can
hold ~100 at 64 slots. This also makes isPoolVMCgroupDirName's claim that acquire
"re-creates on miss" true, which it was not.

SUGGESTION: a writeMemoryMax failure now counts a leak and logs. The directory existed,
was UNBOUNDED, never reached the free list and was never removed or counted -- the silent
accumulation this whole change removes, reappearing on the error path, and inconsistent
with release's "a leak is counted so it cannot be silent". Creation is shared by the mint
and rebuild paths in one `create` helper so both produce a BOUNDED cgroup, never one that
is merely present.

NIT: mkdirAllCgroup had landed between writeMemoryMax's doc comment and writeMemoryMax,
so godoc attributed spec section 6's mitigation to a one-line MkdirAll and left the
function that implements it undocumented. Moved above the block. (Same mistake as rossoctl#315's
vmCgroupDirFor placement -- worth noticing as a pattern when inserting helpers.)

NIT: two places still described jailer writing memory.max and creating the per-VM cgroup.
CgroupMemoryMaxBytes' doc and validate()'s error text now say the pool writes it. The
check is unchanged and matters more than before: writeMemoryMax rejects <= 0, so a zero
fails every restore rather than silently omitting a flag.

Also removed, from the no-anchor finding: vmCgroupPath and
TestVMCgroupPathIsUnderTheParentSlice. vmCgroupDirFor was its last production caller, so
by this PR's own standard -- "keeping a tested-but-unreachable path would imply per-VM
cgroups still exist" -- the name helper is in the same category as the placement helper.

Verified: go test ./... -count=1, 9 packages exit 0; -race clean on the pool; go vet,
gofmt and make lint clean; godoc attribution checked with `go doc -u` on both functions.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant