compeval

package
v0.206.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

abtest.go — the task-outcome A/B: the same entries scored FULL vs COMPACTED by an injected model-backed scorer, with the control-pair SELF-TEST gate in front. The gate is the harvested lesson this file exists for: before any A/B verdict counts, the scorer must correctly rank a known-good/known-degraded pair — a scorer that cannot tell those apart CANNOT be trusted to rank full-vs-compacted, and the run ABORTS instead of producing a confident number from a blind judge.

contextbench_gen_kv.go - the key-value memory task generator.

Ported to Go from contextbench/tasks/kv_store/generate.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0). The word table, the id and value construction and the order of random draws follow the original so the same seed streams the same operations. The operation mix is ported: the texts of the streamed operations (sentinel lines, headers, request wording) are the original's, byte for byte, because the stream digest has to match. The code and comments are written for this repository and none of the upstream's documentation or instruction prose is carried over.

The task: SET batches stream first, then GET operations. Values are random-word strings with a unique tag, so they cannot be guessed, paraphrased or summarised, and which keys will be asked about is not revealed up front.

contextbench_gen_log.go - the incident-log triage task generator.

Ported to Go from contextbench/tasks/log_triage/generate.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0). The service, level and word tables, the line construction and the order of random draws follow the original so the same seed streams the same operations. The operation mix is ported: the texts of the streamed operations (sentinel lines, headers, question wording) are the original's, byte for byte, because the stream digest has to match. The code and comments are written for this repository and none of the upstream's documentation or instruction prose is carried over.

The task: a service log streams in batches, then questions arrive. A lookup asks for the message of the line with a given request id; a count asks how many lines match a level and a service. Both need the exact log, not a summary of it.

contextbench_gen_needle.go - the needle-retention task generator.

Ported to Go from contextbench/tasks/needle_retention/generate.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0). The word table, the line and sentinel construction and the order of random draws follow the original so the same seed streams the same operations. The operation mix is ported: the texts of the streamed operations (sentinel lines, headers, the needle and filler wording) are the original's, byte for byte, because the stream digest has to match. The code and comments are written for this repository and none of the upstream's documentation or instruction prose is carried over.

The task: each streamed chunk carries a few needle lines to keep verbatim and a large filler block to let go. The grade is the share of needle lines still present in the agent's final context.

contextbench_gen_sudoku.go - the sudoku-sketchpad task generator.

Ported to Go from contextbench/tasks/sudoku_sketchpad/generate.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0). The board construction, the panel format and the order of random draws follow the original so the same seed streams the same operations. The operation mix is ported: the texts of the streamed operations (the move and new-board wording, the panel lines) are the original's, byte for byte, because the stream digest has to match. The code and comments are written for this repository and none of the upstream's documentation or instruction prose is carried over.

The task: the agent keeps a whole sudoku board as a panel of (row,col,value) tuples in its context and edits it as one fully specified move arrives per turn. Gold is a list of per-version deltas; the grade is how many of the versions it displayed.

contextbench_grade_base.go - the shared plumbing of the contextbench graders: the snapshot frame, the grade, whitespace normalisation and the text a grader scans.

Ported to Go from contextbench/graders/base.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): the normalisation, the flattening of a message list into scannable text, and the rule that a grade that cannot be computed is reported as invalid, never as a zero. The code and comments are written for this repository; the readers of snapshot files, trajectories and closing reports are not ported because the adapter keeps its frames in memory.

THE SNAPSHOT THE GRADE USES. A frame is the []agent.Msg the run recorded at one moment (CBFrame.Messages), and a grader reads exactly one field of it: the Content of every message, joined by newlines. Role, tool-call arguments and tool-call ids are not scanned. kv_store, log_triage and sudoku_sketchpad scan every frame; a reply is credited once it appears in any frame. needle_retention scans the LAST frame only: what the context still holds when the run ends.

contextbench_grade_kv.go - the key-value memory grader.

Ported to Go from contextbench/graders/kv.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): the answer-block pattern and the rule that a query is credited when the gold value appears in any answer given for its key in any frame. The code and comments are written for this repository.

Two rules differ from the original on purpose. The key an answer names is compared without its surrounding quotes and without regard to case, because a model that writes key="K00001" still answered K00001. The value is credited only when it stands as a whole in the answer: the character after it and the one before it are not letters or digits, so a value ending in its eight-hex-digit tag does not match the same words followed by a longer tag, and does not begin in the middle of a longer word. The original credits any substring.

contextbench_grade_log.go - the incident-log triage grader.

Ported to Go from contextbench/graders/log.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): the answer-block pattern, the lookup rule (the message without its trailing uniqueness tag appears in an answer) and the count rule (the answer states exactly one number and it is the gold integer). The code and comments are written for this repository.

The count rule reads the answer after two clean-ups the original does not make: a question label the model repeats ("Query 3:", "qid=3") is removed, and digit groups joined by thousands separators ("12,800") are read as one number. Otherwise the label's own number, or the groups, would be counted as a second number and a right answer would be refused.

contextbench_grade_needle.go - the needle-retention grader.

Ported to Go from contextbench/graders/needle.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): the rule that the reward is the fraction of gold needle lines present, as whole normalised lines, in the final context. The code and comments are written for this repository. The upstream fallbacks to a trajectory file and to a closing report block are not ported: the adapter always has the in-memory frames.

contextbench_grade_sudoku.go - the sudoku-sketchpad grader.

Ported to Go from contextbench/graders/sudoku.py in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): parsing sketchpad panels out of the frames, folding the gold's per-version deltas back into full boards, and scoring how many versions the agent displayed exactly. The code and comments are written for this repository. One deliberate difference: a cell value must be a single symbol; the original also accepts a multi-character run that happens to be a substring of the symbol table.

contextbench_instr.go - what the agent is told, per family.

The upstream benchmark ships its instructions as markdown scaffolds. Those are prose, not logic, and are not carried into this repository; these short texts are written for the adapter and state the same contracts: the shape of an answer block, the sentinels, and the standalone readiness marker. Because the wording differs, scores from this adapter compare harness configurations with each other, not with published numbers.

The texts deliberately contain no example that a grader could mistake for an answer: placeholders only, never a real key, query number or board tuple.

contextbench_levels.go - the levels of record: which generator knobs make which named task size, per family.

The table is data ported from contextbench/configs/paper.yaml in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0): the knob values of each published level, with the family's fixed knobs merged in. The budget of record is 32768 tokens with 2048 reserved (CBDefaultBudget, CBDefaultReserve), and the published seeds are 42 through 49.

contextbench_pyrand.go - the subset of CPython's `random.Random` the contextbench task generators draw from, reproduced bit for bit: the Mersenne Twister seeded the way `random.seed(<int>)` seeds it, and the algorithms behind `random()`, `getrandbits`, `choice`, `randint`, `shuffle`, `sample` and `choices`.

Why: a contextbench instance is a pure function of (seed, knobs) in its Python original. Reproducing the generator's random stream exactly means seed 42 here is the same instance as seed 42 there, which is what lets a result be set beside the published levels. contextbench_gen_test.go pins the byte digest of the streamed operations against output of the original generator.

contextbench_run.go - the contextbench driver: it feeds one generated task's operations to a seat, keeps the conversation inside a token budget with the production compaction ladder, records snapshots of the context, and grades them.

This file is harness code, not a port. The shape of a run:

  • The transcript starts with the instruction (system) and a one-line kickoff.
  • Each operation is delivered either as the result of a synthetic `next_op` tool call ("tool_result", the default) or as a user message ("user"). The ladder shrinks tool-result bodies (dedupe, skeleton, elision) before it drops whole turns, so tool_result is the delivery under which every rung can act; user delivery reaches only the last rung, which drops older bare messages whole. The upstream benchmark delivers operations as user messages, so "user" is the closer reproduction and "tool_result" is the one that exercises the ladder.
  • Before every send the transcript goes through agent.CompactReplay at the usable budget, exactly the call the production loop makes, and the production loop's habit of keeping the compacted transcript (the dropped content stays dropped).
  • Two snapshots per step: "sent" (what the seat was handed) and "turn" (the transcript right after the seat's reply, before the next compaction). A context the seat was never handed (one that stays over the budget) is not recorded, so a frame is always something the seat saw. The last frame is the retained context the needle grader reads.
  • A run ends when the last operation has been answered (stream_exhausted), the agent submits after the stream is drained (submit), the context cannot be made to fit (budget_wall), or the turn cap is reached (max_turns). A budget_wall before the seat has answered once measured nothing (the budget cannot hold the instruction and the first operation) and is infra_error, not a graded failure. A budget_wall before the seat has been handed a single query (kv_store and log_triage) leaves nothing to grade either: it is a timeout, the attempt hit its budget, with the term reason budget_wall_before_query. A wall once a query has been handed over, and a wall in a family that asks nothing, is graded on the frames it has. A cancelled context ends the task as not_run, also when it lands mid-request.

The outcome word of a task is decided here and nowhere else; see classify.

contextbench_stream.go - how an operation reaches the agent and how the agent asks for the next one.

The operation rendering and the standalone-marker rule are ported from contextbench/stream.py (render_op, _standalone_line_re, is_ready_line, is_submit_line) in https://github.com/RulinShao/ContextBench at commit fb533c18c78a82d3f1b2047a9c1700735cf829ae (Apache-2.0); the code and the texts sent back to the agent are written for this repository. The shell-statement parser of the original is not ported: the adapter drives a chat seat that has no shell.

contextbench_types.go - the shared shapes of the contextbench adapter: the streamed operations, the gold each family grades against, the generator knobs, and the canonical byte form of an instance.

contextbench measures what an agent keeps, updates and offloads when its input does not fit the context window. Four task families stream more content than the budget holds and are graded from the agent's own context. The adapter names every identifier `contextbench`; it is unrelated to the kv-cache reuse bench (kvbench).

Package compeval is the COMPACTION evaluation harness (OmniRoute-harvest Phase B): it replays a pinned corpus of transcript slices through the PRODUCTION compaction ladder (internal/agent.CompactReplay — never a reimplementation) and reports, per content kind: compression ratio, entity retention with explicit lost-entity lists, and a tokens-per-entry ratchet against a frozen baseline. Its reports are what gate every compaction default flip (--skeleton-prune, gcf_compact): savings claims exist ONLY as measured mean ratios stamped with the corpus hash — inherited or estimated numbers are not admissible.

Methodology provenance: the eval-and-ratchet approach is harvested from the OmniRoute compression service's test methodology (MIT); the metrics and signals here are this harness's own.

entities.go — the deterministic FORCE_PRESERVE-class entity extractor. "Entity" here means the token classes a compaction step must never silently destroy: numbers, file paths, URLs, key=value keys, error-line signal, UPPER_SNAKE identifiers, and long hex ids. Retention is measured over ALL turn bodies — the ladder edits tool bodies, but its final rung drops whole older turns, and entities lost that way must count too. Every lost entity is listed by value — a retention percentage without the lost list is not reviewable, so the list is the primary artifact and the ratio is derived.

harvest.go — trace→corpus harvest with REDACTION-AT-HARVEST. Real replay corpora are built from the standalone agent's trace files (cmd/local-agent traceRecord JSON, full []agent.Msg transcript). Real transcripts routinely carry identity-shaped content — git output alone embeds author emails — and VetPII refuses a corpus rather than scrubbing it in place (scrubbing would change the bytes the hash pins). So redaction happens HERE, before the corpus file exists: deterministic placeholder substitution over the exact refusal classes, then the VetPII gate re-runs on the result as defense-in-depth — a harvest whose output would still refuse is an error, never a written file.

Fidelity contract: the whole transcript is kept (including the system turn), ProtectedPrefix is set to the preamble length (turns before the first assistant turn), and KeepRecent to the live loop's DefaultKeepRecent — mirroring how production calls compact(), so the replay exerts the same pressure production does. Transcripts the ladder already compacted mid-run (elision markers / skeletons in tool bodies) are REFUSED with a note: their raw content is unrecoverable, and replaying compaction-of-compacted text would measure the ladder against its own output.

kvbench.go — the OmniRoute-harvest Phase D measurement core: KV-prefix reuse and REAL token accounting for the compaction ladder.

WHAT THIS MEASURES, AND WHY THE ORIGINAL PREMISE WAS WRONG. The harvest design asked us to "verify the monotonic ladder preserves llama.cpp's KV prefix cache". Measured on this stack (2026-07-24), that statement is not true as written, for a reason stronger than expected: reuse here is BINARY. Appending a turn reuses everything the server held (2429 kept, 19 prefilled), but ANY edit to the prompt discards the ENTIRE cache — a position sweep showed a one-line edit at 98% of the prompt costing all 2662 tokens, identically to an edit at 4%. Since every lossy rung edits from protectedEnd FORWARD (compaction.go — dedupe/GCF/skeleton/elide/drop all iterate `for i := protectedEnd; i < recentStart`), the step on which the ladder fires always pays a full re-prefill. What monotonicity + the idempotence guards DO buy is that the steps BETWEEN fires stay pure appends, so the cache returns immediately afterwards.

So the honest quantity is a RAMP, not a constant win:

  • no-fire step => append-only => reuse ~1.0 (measured 0.997)
  • firing step => any divergence => reuse ~0 (measured 0.0004)
  • post-fire step => append again => reuse ~1.0

And the fire's cost is not a compaction defect: NOT compacting does not keep the cache either — the transcript simply grows until the server rejects it outright (measured live as exceed_context_size 400s). The trade is a full re-prefill per fire against a request that does not complete at all. Phase D therefore measures how OFTEN the ladder fires over a real transcript and what each fire costs, against the size win compaction buys — two effects this package keeps strictly separate and NEVER sums.

Everything in this file is pure and deterministic (no clock, no network) so it is unit-testable; the live sequencing lives in kvrunner.go.

kvrunner.go — the LIVE sequencing for the Phase D KV/TTFT bench. Pure orchestration over a ProbeFunc: no HTTP here, so the whole sequence is testable against a fake server (see kvbench_test.go).

TWO SEQUENCING RULES THAT ARE NOT NEGOTIABLE ON THIS STACK:

  1. ARMS RUN IN BLOCKS, NEVER INTERLEAVED. The serving tier runs `--parallel 1` — ONE KV slot. Interleaving arm A and arm B round-robin (the textbook way to spread thermal/background drift) would make every single request a cache miss, because each arm would evict the other's prefix. Blocks confound drift with arm, which is why rounds are repeated and per-round values are reported rather than pooled.
  2. CONTROLS BRACKET EVERY RUN. Residency here is a property of the SCHEDULER, not of our code: one measured `/v1/embeddings` request was enough to evict the model and take the cache with it. Without a positive control before AND after, a table of zeros reads as "compaction destroys the KV cache" when the true cause is that the model process died. The run fails closed to INCONCLUSIVE.

metrics.go — replay + per-kind aggregation. Evaluate is DETERMINISTIC and model-free: it replays each entry through the production ladder (agent.CompactReplay) at the entry's budget and measures with the ladder's own token estimator. Reports are stamped with the corpus hash and the ladder configuration; savings exist only as these measured ratios.

ratchet.go — the tokens-per-entry ratchet. A baseline is FROZEN once from a report (an explicit operator act, like pinning a version); every later run on the SAME corpus must land within the tolerance of that baseline or the check fails loudly. Cross-corpus comparisons are refused — a ratchet is only meaningful against the pinned artifact its baseline was frozen from.

redactor_export.go — the harvest's redaction, exported for readers of recorded runs that are not transcript replays (the trace-corpus verb). It is a thin face on the same unexported redactor and the same vet class table the compaction harvest uses, so a second harvester cannot redact a different set of classes than the first one: a class added to the vet table is redacted here the day it is added.

Index

Constants

View Source
const (
	CBDefaultBudget  = 32768
	CBDefaultReserve = 2048
)

The context budget of record and the reserve held back for the reply.

View Source
const (
	CBDeliveryToolResult = "tool_result"
	CBDeliveryUser       = "user"
)

The two ways an operation reaches the seat.

View Source
const (
	CBTermStreamExhausted = "stream_exhausted"
	CBTermSubmit          = "submit"
	CBTermBudgetWall      = "budget_wall"
	CBTermMaxTurns        = "max_turns"
	CBTermSeatError       = "seat_error"
	CBTermCancelled       = "cancelled"
)

Why a run ended.

View Source
const (
	CBOutcomePass       = "pass"
	CBOutcomeTaskFail   = "task_fail"
	CBOutcomeCheat      = "cheat"
	CBOutcomeInfraError = "infra_error"
	CBOutcomeTimeout    = "timeout"
	CBOutcomeJudgeError = "judge_error"
	CBOutcomeNotRun     = "not_run"
)

The seven outcome words of the measurement gate, in the gate's fixed order.

View Source
const (
	CBAdvanceMarker = "READY_FOR_NEXT_OP"
	CBSubmitMarker  = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
)

The two markers an agent puts on a line of its own.

View Source
const (
	CBFamilyKV     = "kv_store"
	CBFamilyLog    = "log_triage"
	CBFamilyNeedle = "needle_retention"
	CBFamilySudoku = "sudoku_sketchpad"
)

The four task families.

View Source
const (
	CtrlPosPre  = "pos-pre"
	CtrlNegPre  = "neg-pre"
	CtrlAppend  = "append"
	CtrlMidEdit = "mid-edit"
	CtrlPosPost = "pos-post"
)

Control names. POS/NEG gate admissibility; APPEND and MIDEDIT are MEASURED PROPERTIES of the serving stack (they characterize what the ladder's two access patterns actually cost) and never abort a run.

View Source
const (
	PosReuseMin     = 0.90
	NegReuseMax     = 0.75
	MinPosNegMargin = 0.40
)

Admissibility thresholds.

A byte-identical resend must reuse essentially everything. An unrelated prompt must reuse only the UNAVOIDABLE COMMON FRAMING — and that floor is not zero: every production request carries the same tool specs, which the chat template renders into a shared prefix. Measured here, that floor is ~16.8% of a ~2600-token prompt (≈440 tokens of specs). An earlier absolute ceiling of 5% encoded the assumption that no common framing exists; sending the real specs (as production does) falsified it, and the gate correctly refused to publish rather than quietly passing.

So the ceiling is generous, and the LOAD-BEARING criterion is SEPARATION: the instrument is only trustworthy if it can tell reuse from no-reuse by a wide margin. That is a property of the measurement, not of the framing. NegReuseMax is a loose sanity bound only — the framing floor is legitimate and its size depends on how big the tool specs are relative to the prompt. MinPosNegMargin is the criterion that actually binds: with a large enough floor (small prompts, big spec set) the absolute numbers can both look "fine" while the metric has lost its ability to discriminate, and that is the condition worth refusing.

View Source
const (
	ArmOff = "off"
	ArmOn  = "on"
)

The two arms of a bench run: ArmOff sends the raw uncompacted transcript, ArmOn sends what the ladder produces.

View Source
const (
	// BudgetProduction reproduces Loop.inputBudget() — the budget production
	// used BEFORE token calibration (ADR 0017 decision 10) shipped in this same
	// release. It is deliberately NOT renamed away from "production" in the
	// artifacts, but it is not the current production budget: a calibrated loop
	// compacts against tokenCal.Budget(inputBudget()), which is tighter on
	// dense content. Measuring the calibrated budget requires a live agent run,
	// not a replay, because calibration is a property of the loop's observed
	// responses rather than of the transcript.
	BudgetProduction = "production-uncalibrated"
	BudgetPressure   = "pressure"
)

Budget modes — see BenchOpts.BudgetMode.

View Source
const CBEstimator = "ladder_estimate_chars_div_4"

CBEstimator names the size estimator: the ladder's own, not the original's tokenizer.

View Source
const CBPagerNotExercised = "not_exercised"

CBPagerNotExercised is the pager basis of every contextbench task: evictions are recorded, a re-fetch rate is not (see RunCBTask).

View Source
const CBReasonBudgetWallBeforeQuery = "budget_wall_before_query"

CBReasonBudgetWallBeforeQuery is the term reason of a task whose context stopped fitting the budget before the seat was handed any query operation (see RunCBTask).

View Source
const CBSchema = "contextbench/1"

CBSchema stamps the report format.

View Source
const CBSudokuSymbols = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

CBSudokuSymbols are the single-character cell values: 1-9 then A-Z.

View Source
const DefaultTolerance = 0.02

DefaultTolerance is the ±2% band from the Phase-B design.

Variables

CBFamilies is the fixed order every report and run walks the families in.

CBOutcomes lists the seven words in order.

View Source
var KnownKinds = map[string]bool{
	"tool-json": true, "tool-text": true, "logs": true,
	"code": true, "prose": true, "mixed": true,
}

KnownKinds is the closed bucket set; Load rejects entries outside it so a typo'd kind can never silently fragment the per-kind aggregation.

Functions

func Admissible

func Admissible(cs []Control) (bool, string)

Admissible reports whether the control shots prove the instrument works.

Fails CLOSED, and checks EVERY control instance rather than one per name: a multi-round run appends each round's controls, so keying by name would let a later round's pass silently overwrite an earlier round's failure — exactly the contamination the controls exist to catch.

func CBCheckBudget

func CBCheckBudget(in *CBInstance, opts CBRunOpts) error

CBCheckBudget refuses a budget that cannot hold the first send of an instance: the instruction plus the first operation, after the same compaction the run applies. Such a run would never call the seat and would measure nothing.

func CBInstruction

func CBInstruction(in *CBInstance, delivery string) string

CBInstruction is the system text for one instance. delivery is "tool_result" or "user" and only changes one sentence: where the operations come from.

func CBLevelNames

func CBLevelNames(family string) []string

CBLevelNames lists a family's level names in table order.

func ClassifyKind

func ClassifyKind(turns []Turn) string

ClassifyKind buckets an entry by what its TOOL payloads are made of — the compressible content the ladder actually works on. Byte-weighted majority (≥60%) picks the bucket; no majority is honestly "mixed"; no tool payloads at all means the transcript is user/assistant text → "prose". Deterministic: same turns, same kind, no model involved.

func CoveredRatio

func CoveredRatio(s, ctxTokens, maxOut int) float64

CoveredRatio inverts ImpliedMargin: the largest estimator error a given margin survives. (S=512 with ctx 8192 / maxOut 1024 covers r<=1.077.)

func DivergenceIndex

func DivergenceIndex(prev, cur []agent.Msg) int

DivergenceIndex returns the index of the first message where cur differs from prev, or -1 when cur is a pure APPEND of prev (the case that reuses the KV cache). Message-level is the right granularity: the ladder edits whole message bodies.

func Entities

func Entities(s string) map[string]struct{}

Entities extracts the entity SET of one string.

func ErrorClass

func ErrorClass(errText string) string

ErrorClass buckets a probe failure. Order matters: timeout BEFORE overflow.

func HarvestTraces

func HarvestTraces(dir string, opts HarvestOpts) ([]Entry, HarvestStats, error)

HarvestTraces reads every *.json trace under dir (sorted by name — the harvest is deterministic), converts, redacts, classifies, and gates. A trace that cannot be parsed or is too short, or that still holds a piece of a redacted credential value, is skipped WITH a note; residual vet-class PII after redaction fails the whole harvest.

func ImpliedMargin

func ImpliedMargin(r float64, ctxTokens, maxOut int) int

ImpliedMargin solves S >= (C - M)(1 - 1/r): the smallest safety margin that still fits when the real token count is r times the ladder's estimate.

Derivation (kept here because the constant is otherwise unfalsifiable): the ladder compacts until EST <= C - M - S; the server then sees REAL = r*EST; the request fits when REAL + M <= C.

func Median

func Median(xs []float64) float64

Median of a float slice (0 for empty). Does not mutate the input.

func PIIClasses

func PIIClasses(s string) []string

PIIClasses names the vet classes that still match s, sorted. A harvest runs it over every string it is about to write, after redaction, as the exit gate: a non-empty answer means the redactor and the vet have drifted and nothing may be written.

func Percentile

func Percentile(xs []float64, p float64) float64

Percentile (nearest-rank, p in [0,1]). Deterministic; 0 for empty.

func Render

func Render(msgs []agent.Msg) string

Render flattens a transcript slice to the text a scorer reads (role-tagged, deterministic).

func Retention

func Retention(before, after []agent.Msg) (ratio float64, lost []string)

Retention compares entity sets over ALL turn bodies before and after compaction (the drop rung destroys non-tool turns too). Returns the retention ratio in [0,1] (1 when the original had no entities) and the sorted lost-entity list.

func ReuseFrac

func ReuseFrac(r ProbeResult) float64

ReuseFrac is cache_n/(cache_n+prompt_n) — the fraction of the prompt served from cache. Denominator is the REAL prompt length, never prompt_n alone (that would report >1 on a cache hit).

func SameTranscript

func SameTranscript(a, b []agent.Msg) bool

SameTranscript reports byte-for-byte equality of two message slices.

func SaveBaseline

func SaveBaseline(path string, b Baseline) error

SaveBaseline / LoadBaseline round-trip the frozen artifact as JSON.

func SelfTest

func SelfTest(ctx context.Context, score Scorer, pairs []ControlPair) error

SelfTest runs every control pair through the scorer and errors on the FIRST mis-ranking (ties count as failures — a scorer with no discrimination is as unusable as an inverted one).

func ToMsgs

func ToMsgs(turns []Turn) []agent.Msg

ToMsgs converts a wire transcript to the ladder's message type.

func WriteCorpus

func WriteCorpus(path string, entries []Entry) (string, error)

WriteCorpus writes entries as corpus JSONL and returns the corpus hash — obtained by RE-LOADING the bytes through Load, the strict production reader, so a written corpus is round-trip-proven loadable and the returned hash is exactly the one every eval artifact will be stamped with. The write is atomic-by-rename: the re-load runs against a temp file, so a refused corpus never exists at the destination path.

Types

type ABReport

type ABReport struct {
	CorpusHash string     `json:"corpus_hash"`
	Ladder     string     `json:"ladder"`
	ModelIDs   []string   `json:"model_ids,omitempty"`
	GatePassed bool       `json:"gate_passed"`
	Results    []ABResult `json:"results"`
	Delta      float64    `json:"delta"`
	DeltaLo    float64    `json:"delta_lo"`
	DeltaHi    float64    `json:"delta_hi"`
}

ABReport is the A/B artifact: per-entry paired scores plus the bootstrap delta (compact − full; CI from eval.BootstrapDeltaMean). GatePassed records that the control-pair gate ran and passed — a report cannot exist without it.

func RunAB

func RunAB(ctx context.Context, score Scorer, entries []Entry, corpusHash string, opts LadderOpts, pairs []ControlPair, modelIDs []string) (ABReport, error)

RunAB gates on SelfTest, then scores each entry full-vs-compacted and aggregates the paired bootstrap delta. Entries whose scoring errors abort the run (a partial A/B silently missing entries would bias the delta).

type ABResult

type ABResult struct {
	ID           string  `json:"id"`
	Kind         string  `json:"kind"`
	ScoreFull    float64 `json:"score_full"`
	ScoreCompact float64 `json:"score_compact"`
}

ABResult is one entry's paired scores.

type ArmStats

type ArmStats struct {
	Arm        string `json:"arm"`
	Samples    int    `json:"samples"`
	Fires      int    `json:"fires"`
	FirstSteps int    `json:"first_steps"` // conversation-start requests, excluded from the ramp medians
	// Evictions counts samples excluded because the tier was torn down between
	// requests (an extension that did not reuse). Reported, never hidden: a
	// high count means the box was busy and the medians rest on less data.
	Evictions int `json:"evictions_excluded"`
	// Unmeasured counts samples whose backend reported no timings block — kept
	// out of every rate, counted so the exclusion is visible.
	Unmeasured int `json:"unmeasured_excluded"`
	// NoFireSamples / OnFireSamples are the class counts behind the medians:
	// a class with zero samples reports a 0.0 median, and only these counts
	// distinguish that from a measured zero.
	NoFireSamples int `json:"no_fire_samples"`
	OnFireSamples int `json:"on_fire_samples"`
	// ExtensionReuse is the median reuse over CLEAN extension steps — the
	// direct, high-n answer to "do appends reuse?", far more robust than the
	// single append control shot.
	ExtensionReuse float64 `json:"median_extension_reuse"`

	MedianReuseFrac float64 `json:"median_reuse_frac"`
	MedianPromptMS  float64 `json:"median_prompt_ms"`
	MedianWallMS    float64 `json:"median_wall_ms"`

	// Split by ladder behavior — the whole point of the ramp. A single mean
	// across both classes hides the effect in both directions.
	MedianReuseNoFire    float64 `json:"median_reuse_no_fire"`
	MedianReuseOnFire    float64 `json:"median_reuse_on_fire"`
	MedianPromptMSNoFire float64 `json:"median_prompt_ms_no_fire"`
	MedianPromptMSOnFire float64 `json:"median_prompt_ms_on_fire"`

	// Real prompt tokens actually PREFILLED across the arm — the cost that
	// matters, and the one place the size win shows up.
	TotalPrefilled  int `json:"total_prefilled_tokens"`
	TotalReused     int `json:"total_reused_tokens"`
	TotalRealTokens int `json:"total_real_prompt_tokens"`
}

ArmStats aggregates one arm honestly: medians plus the raw vectors, never a parametric interval over a handful of wall-clock numbers.

func Summarize

func Summarize(arm string, samples []Sample) ArmStats

Summarize aggregates samples for one arm. Pure.

type Baseline

type Baseline struct {
	CorpusHash     string         `json:"corpus_hash"`
	Ladder         string         `json:"ladder"`
	TokensPerEntry map[string]int `json:"tokens_per_entry"`
}

Baseline is the frozen reference: per-entry compacted token counts plus the pins that make comparison meaningful.

func Freeze

func Freeze(rep Report) Baseline

Freeze derives a Baseline from a report.

func LoadBaseline

func LoadBaseline(path string) (Baseline, error)

type BenchOpts

type BenchOpts struct {
	Ladder LadderOpts
	// Arms names the arms to run, in order: "off" (raw, uncompacted) and "on"
	// (the ladder). Empty means both.
	Arms []string
	// Rounds repeats the whole (controls + both arms) block; more rounds is
	// the only honest defence against drift given rule 1 above.
	Rounds int
	// StepStride samples every Nth step of a transcript (1 = every step). The
	// final step of an entry is always measured regardless of stride.
	StepStride int
	// MaxEntries caps how many corpus entries are replayed (0 = all).
	MaxEntries int
	// CtxTokens / MaxOut describe the SERVED window and the reserved output
	// budget; they parameterize the safety-margin decision table and, in
	// production budget mode, the ladder budget itself.
	CtxTokens int
	MaxOut    int
	// BudgetMode selects how the on-arm ladder budget is derived:
	//
	//   "production" — ctxTokens - maxOut - margin, i.e. exactly what
	//     Loop.inputBudget() uses. Fire counts are then meaningful as a
	//     statement about this corpus at this window.
	//   "pressure"   — 60% of each entry's own estimate (what Evaluate uses).
	//     Guarantees the ladder engages so the RAMP is observable, but the
	//     fire COUNT is then a property of the fixture, not of production.
	//
	// Whichever is used is stamped in the report; the distinction is the
	// difference between a measurement and an artifact.
	BudgetMode string
	// Margin is the production safety margin (agent's compactionMargin) used
	// by production budget mode.
	Margin int
	// RunNonce makes every body request unique to this run+arm so the server's
	// MULTI-PROMPT cache cannot serve one arm from another arm's entries, or
	// this run from a previous run's. Auto-generated when empty; recorded in
	// the report. See salt().
	//
	// Give two runs the SAME value only on a cold seat: a body prompt the
	// ladder leaves unchanged is then byte-identical across the runs, so the
	// second run is served from the first run's cache and its prefill and reuse
	// numbers are inflated. Proving a pair a no-op does not need it:
	// Sample.SentSHA256 is taken before the salt.
	RunNonce string
	// ControlNonce salts the calibration controls. It is drawn fresh for every
	// run and is deliberately independent of RunNonce, so reusing a RunNonce
	// never replays a previous run's negative control into a warm cache. Set
	// it only to make a test deterministic.
	ControlNonce string
}

BenchOpts configures a bench run.

type Breach

type Breach struct {
	EntryID  string  `json:"entry_id"`
	Baseline int     `json:"baseline_tokens"`
	Current  int     `json:"current_tokens"`
	Delta    float64 `json:"delta"` // (current-baseline)/baseline, signed
}

Breach names one entry outside the tolerance band.

func Check

func Check(b Baseline, rep Report, tolerance float64) ([]Breach, error)

Check compares a report against a frozen baseline. Refuses (error) on a corpus-hash or ladder mismatch, or on entries missing from either side — silence there would let the ratchet rot. Returns the breaches beyond ±tolerance (empty = ratchet holds). The band is TWO-SIDED on purpose: an IMPROVEMENT breaches too — any ladder-behavior change is an explicit operator act (re-freeze), never silent drift. tolerance 0 = strict equality; negative = DefaultTolerance.

type CBFrame

type CBFrame struct {
	Kind     string      `json:"kind"`
	Step     int         `json:"step"`
	Tokens   int         `json:"tokens"`
	Messages []agent.Msg `json:"-"`
}

CBFrame is one snapshot of the agent's context. Kind is "sent" (the context handed to the seat after compaction) or "turn" (the context right after the seat replied, before any compaction). Messages is the whole transcript at that moment.

type CBGold

type CBGold struct {
	KV          []CBKVQuery     `json:"kv,omitempty"`
	Log         []CBLogQuery    `json:"log,omitempty"`
	NeedleLines []string        `json:"needle_lines,omitempty"`
	Side        int             `json:"side,omitempty"`
	InitialGrid string          `json:"initial_grid,omitempty"`
	Deltas      []CBSudokuDelta `json:"deltas,omitempty"`
}

CBGold is what a family's grader scores against. Only the fields of the instance's own family are set.

type CBGrade

type CBGrade struct {
	Reward  float64            `json:"reward"`
	Valid   bool               `json:"grader_valid"`
	Note    string             `json:"grader_note,omitempty"`
	Matched int                `json:"matched"`
	Total   int                `json:"total"`
	Frames  int                `json:"frames"`
	Sub     map[string]float64 `json:"rewards,omitempty"`
}

CBGrade is a family grader's result. Reward is the family's primary score in [0, 1]. Valid false means the grade could not be computed (nothing to read, or a gold the grader refuses); the reward is then meaningless and Note says why.

func GradeCB

func GradeCB(in *CBInstance, frames []CBFrame) CBGrade

GradeCB scores a run's frames against an instance's gold with the family's grader.

type CBInstance

type CBInstance struct {
	ID     string         `json:"id"`
	Family string         `json:"family"`
	Level  string         `json:"level"`
	Seed   int64          `json:"seed"`
	Ops    []CBOp         `json:"ops"`
	Gold   CBGold         `json:"gold"`
	Meta   map[string]any `json:"meta"`
	// QueryStart is the index of the first query operation: the operations before it only
	// stream content, and from it on every operation asks something. It is 0 for a family
	// that asks nothing (needle_retention, sudoku_sketchpad), which has no query block.
	QueryStart int `json:"query_start,omitempty"`
}

CBInstance is one generated task: the operation stream, the gold, and the numbers that describe it. It is a pure function of (family, seed, knobs).

func BuildCBTasks

func BuildCBTasks(family, level string, seed int64, n int) ([]*CBInstance, error)

BuildCBTasks generates n instances per selected family, with seeds seed..seed+n-1. family is one family name or "all"; level (optional) names a published level and is only valid with a single family.

func GenerateCB

func GenerateCB(family, level string, seed int64) (*CBInstance, error)

GenerateCB builds one instance of a family at a level for a seed.

func GenerateKV

func GenerateKV(seed int64, k CBKnobs) *CBInstance

GenerateKV builds one kv_store instance.

func GenerateLog

func GenerateLog(seed int64, k CBKnobs) *CBInstance

GenerateLog builds one log_triage instance.

func GenerateNeedle

func GenerateNeedle(seed int64, k CBKnobs) *CBInstance

GenerateNeedle builds one needle_retention instance.

func GenerateSudoku

func GenerateSudoku(seed int64, k CBKnobs) *CBInstance

GenerateSudoku builds one sudoku_sketchpad instance. When k.Turns is positive it overrides k.Boards and boards keep chaining until that many operations exist.

func (*CBInstance) OpsJSONL

func (in *CBInstance) OpsJSONL() []byte

OpsJSONL is the stream in the upstream wire form: one line per operation, `{"index": N, "header": "...", "body": "..."}` with Python's separators. Two instances from the same (family, seed, knobs) have identical bytes.

type CBKVQuery

type CBKVQuery struct {
	QID   int    `json:"qid"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

CBKVQuery is one GET: the key asked about and the value that was set for it.

type CBKnobs

type CBKnobs struct {
	// kv_store
	Records, ValueWords, Queries, RecordsPerChunk int
	// log_triage (Queries is shared)
	Lines, LinesPerBatch int
	// needle_retention
	Chunks, NeedlesPerChunk, FillerLines, WordsPerLine int
	// sudoku_sketchpad
	Box, Givens, Boards, Turns int
}

CBKnobs are the generator parameters. A family reads only its own.

type CBLevel

type CBLevel struct {
	Name  string
	Knobs CBKnobs
}

CBLevel is one named task size.

func CBLookupLevel

func CBLookupLevel(family, name string) (CBLevel, error)

CBLookupLevel finds a level by family and name; an empty name selects the default.

type CBLogQuery

type CBLogQuery struct {
	QID    int    `json:"qid"`
	Type   string `json:"type"`
	Prompt string `json:"prompt"`
	Answer string `json:"answer"`
}

CBLogQuery is one log question. Type is "lookup" or "count".

type CBOp

type CBOp struct {
	Index  int    `json:"index"`
	Header string `json:"header"`
	Body   string `json:"body"`
}

CBOp is one streamed operation, delivered to the agent as one turn.

type CBReport

type CBReport struct {
	Schema    string         `json:"schema"`
	Seat      string         `json:"seat"`
	Budget    int            `json:"budget_tokens"`
	Reserve   int            `json:"reserve_tokens"`
	Estimator string         `json:"size_estimator"`
	Delivery  string         `json:"delivery"`
	Ladder    string         `json:"ladder"`
	PassAt    float64        `json:"pass_at"`
	Results   []CBTaskResult `json:"results"`
	Counts    map[string]int `json:"outcome_counts"`
	// MeanReward is the mean reward over graded tasks, per family; absent for a family
	// with none. Read it beside the counts: it says nothing about tasks that did not
	// reach a verdict.
	MeanReward map[string]float64 `json:"mean_reward_by_family,omitempty"`
}

CBReport is the artifact of a contextbench run. It carries no timestamps: two runs of the same configuration against a deterministic seat are byte-identical.

func RunCB

func RunCB(ctx context.Context, instances []*CBInstance, seat CBSeat, opts CBRunOpts, seatName string) CBReport

RunCB runs every instance in order and assembles the report. A cancelled context marks the tasks it never reached not_run.

type CBRunOpts

type CBRunOpts struct {
	// Budget and Reserve are tokens, counted with the ladder's own estimator. The
	// ladder fits the transcript to Budget-Reserve before every send. Default: the
	// published 32768 and 2048.
	Budget, Reserve int
	// MaxOut caps the reply, in tokens. Default 4096 (a sudoku panel is about a
	// thousand tokens).
	MaxOut int
	// MaxTurns caps seat replies per task, nudges included. Default 3*ops+10. A task
	// that reaches it ends as timeout: it hit its step budget, which says nothing about
	// the agent's score, so it is not graded. (The other timeout is a budget wall before
	// any query; see RunCBTask.)
	MaxTurns int
	// KeepRecent is the ladder's keep-recent window in messages. Default
	// agent.DefaultKeepRecent, the production value.
	KeepRecent int
	// Ladder selects the optional rungs.
	Ladder LadderOpts
	// Delivery is CBDeliveryToolResult (default) or CBDeliveryUser.
	Delivery string
	// PassAt is the reward at or above which a graded task is `pass`. Default 1.0: every
	// item right. The reward itself is always reported beside the word.
	PassAt float64
}

CBRunOpts configures a run. Zero values take the defaults noted per field.

type CBSeat

type CBSeat func(ctx context.Context, msgs []agent.Msg, maxOut int) (string, error)

CBSeat is the model seam: one chat completion over the transcript, returning the reply text. The CLI wires the production client; tests inject a fake. An error means the seat could not answer and ends the task as infra_error.

type CBSudokuDelta

type CBSudokuDelta struct {
	V     int               `json:"v"`
	Reset bool              `json:"reset,omitempty"`
	Cells map[string]string `json:"cells"`
}

CBSudokuDelta is the gold for one sketchpad version: the changed cells, or the full board when Reset is set (version 0 and every new board).

type CBTaskResult

type CBTaskResult struct {
	ID             string             `json:"id"`
	Family         string             `json:"family"`
	Level          string             `json:"level"`
	Seed           int64              `json:"seed"`
	Outcome        string             `json:"outcome"`
	Reward         *float64           `json:"reward"`
	Matched        int                `json:"matched"`
	Total          int                `json:"total"`
	Rewards        map[string]float64 `json:"rewards,omitempty"`
	TerminatedBy   string             `json:"terminated_by"`
	TermReason     string             `json:"term_reason,omitempty"`
	Turns          int                `json:"turns"`
	OpsDelivered   int                `json:"ops_delivered"`
	OpsSent        int                `json:"ops_sent"`
	OpsTotal       int                `json:"ops_total"`
	Compactions    int                `json:"compactions"`
	PeakSentTokens int                `json:"peak_sent_tokens"`
	Pager          *agent.PagerReport `json:"pager,omitempty"`
	Detail         string             `json:"detail,omitempty"`
}

CBTaskResult is one task's record. Reward is nil unless the task was graded: a task that never reached a verdict has no score, and a zero would read as one.

TermReason refines TerminatedBy when the outcome word turns on a case of it; today only CBReasonBudgetWallBeforeQuery, and empty otherwise. OpsDelivered counts the operations appended to the transcript, the one that did not fit at a budget wall included; OpsSent counts those the seat was actually handed.

func RunCBTask

func RunCBTask(ctx context.Context, in *CBInstance, seat CBSeat, opts CBRunOpts) CBTaskResult

RunCBTask drives one instance to its end and classifies it.

type Control

type Control struct {
	Name      string      `json:"name"`
	Probe     ProbeResult `json:"probe"`
	ReuseFrac float64     `json:"reuse_frac"`
}

Control is one calibration shot. The bench is only admissible when the controls prove the instrument works ON THIS BOX AT THIS MOMENT — residency here is a property of the scheduler, and a single embedding request was measured to evict the model and zero the cache.

func RunControls

func RunControls(ctx context.Context, probe ProbeFunc, phase, nonce string) ([]Control, error)

RunControls issues the calibration shots. phase is "pre" or "post": the pre phase measures all four properties, the post phase re-checks residency only.

The APPEND and MIDEDIT controls do NOT gate admissibility — they are MEASURED PROPERTIES of the serving stack that decide how the body samples must be read (append-only reuse working while mid-prompt divergence collapses the cache is exactly what makes the ladder's fires expensive).

type ControlPair

type ControlPair struct {
	Name     string `json:"name"`
	Good     string `json:"good"`
	Degraded string `json:"degraded"`
}

ControlPair is a known-ordering probe: Good must outscore Degraded.

type Entry

type Entry struct {
	ID   string `json:"id"`
	Kind string `json:"kind"` // tool-json | tool-text | logs | code | prose | mixed
	// Turns is the transcript slice in the EXPLICIT wire casing below (lowercase
	// snake_case, matching the OpenAI transcript shape). The harness replays the
	// WHOLE slice so protected-prefix/keep-recent semantics match production.
	Turns []Turn `json:"turns"`
	// BudgetTokens is the compaction budget to replay at. 0 = derived as 60% of
	// the entry's own estimated tokens (forces the ladder to actually work).
	BudgetTokens int `json:"budget_tokens,omitempty"`
	// KeepRecent / ProtectedPrefix mirror the production knobs. Defaults: keep
	// the final turn, protect the first (objective-style) turn.
	KeepRecent      int `json:"keep_recent,omitempty"`
	ProtectedPrefix int `json:"protected_prefix,omitempty"`
}

Entry is one corpus instance: a transcript slice to replay through the ladder at a fixed budget. Kind buckets results by content class so a mean ratio is never quoted across unlike content.

func Load

func Load(path string) ([]Entry, string, error)

Load reads a JSONL corpus and returns the entries plus the CORPUS HASH — sha256 over the raw file bytes. The hash is the pin: every report and every baseline is stamped with it, and a ratchet comparison across different hashes is refused. Malformed lines are an ERROR here (a corpus is a fixed artifact, not a best-effort stream).

func (Entry) Msgs

func (e Entry) Msgs() []agent.Msg

Msgs is the Entry's transcript as ladder messages.

type EntryResult

type EntryResult struct {
	ID              string   `json:"id"`
	Kind            string   `json:"kind"`
	TokensBefore    int      `json:"tokens_before"`
	TokensAfter     int      `json:"tokens_after"`
	Budget          int      `json:"budget"`
	FitBudget       bool     `json:"fit_budget"`
	Ratio           float64  `json:"ratio"` // after/before (lower = more compression)
	EntityRetention float64  `json:"entity_retention"`
	LostEntities    []string `json:"lost_entities,omitempty"`
}

EntryResult is one entry's replay measurement.

type EstimatorFit

type EstimatorFit struct {
	Samples int     `json:"samples"`
	P50     float64 `json:"ratio_p50"`
	P95     float64 `json:"ratio_p95"`
	P99     float64 `json:"ratio_p99"`
	Max     float64 `json:"ratio_max"`
	// ByKind isolates content-dependence — the reason a single global margin
	// is the wrong lever if the error is dense-JSON-specific.
	ByKind map[string]float64 `json:"ratio_p95_by_kind"`
	// Note warns that the ratio conflates a FIXED per-request payload (tool
	// specs, invisible to estimateTokens) with content density. Small prompts
	// are dominated by the fixed term, so a single multiplicative r read off
	// this distribution overstates the margin needed by large prompts — the
	// ones that actually overflow. tokencal.go models both terms; this
	// distribution does not.
	Note string `json:"note"`
}

EstimatorFit reports how far the ladder's chars/4 estimator is from the server's real token count. This is eviction-immune (token counts are exact however many times the process restarted), so it is measurable even when the KV leg is not.

func FitEstimator

func FitEstimator(samples []Sample) EstimatorFit

FitEstimator computes the real/estimated ratio distribution. Ratios come from samples that were actually measured; unmeasured rows are skipped.

type HarvestNote

type HarvestNote struct {
	File   string `json:"file"`
	Reason string `json:"reason"`
}

HarvestNote records one skipped trace file and why.

type HarvestOpts

type HarvestOpts struct {
	// MinTurns skips traces whose transcript is shorter (default 3 — a
	// transcript with no tool exchange exerts no compaction pressure).
	MinTurns int
	// MaxEntries caps the harvest (0 = all traces).
	MaxEntries int
	// IDPrefix namespaces harvested entry ids (default "hv-").
	IDPrefix string
}

HarvestOpts tunes a harvest pass.

type HarvestStats

type HarvestStats struct {
	Files     int           `json:"files"`
	Harvested int           `json:"harvested"`
	Skipped   []HarvestNote `json:"skipped,omitempty"`
	// PreCompacted counts traces refused because their transcript already
	// carried ladder artifacts (see the fidelity gate in HarvestTraces).
	PreCompacted int            `json:"pre_compacted,omitempty"`
	Redactions   map[string]int `json:"redactions,omitempty"` // class → substitutions
	Kinds        map[string]int `json:"kinds"`                // kind → entries
}

HarvestStats is the harvest's honest accounting: every input file is either harvested or named in Skipped — silent drops would read as coverage.

type KVReport

type KVReport struct {
	CorpusHash string `json:"corpus_hash"`
	// EntriesReplayed disambiguates the hash: --max-entries truncates the
	// corpus, so two runs over the same file can legitimately differ. The hash
	// alone would claim they are the same artifact.
	EntriesReplayed int    `json:"entries_replayed"`
	Ladder          string `json:"ladder"`
	Rounds          int    `json:"rounds"`
	// BudgetMode records how the on-arm ladder budget was derived — the fire
	// COUNT is a direct consequence of it and means nothing without it.
	BudgetMode string `json:"budget_mode"`
	// RunNonce is the per-run marker that isolates this run's body requests
	// (and each arm within it) from the server's multi-prompt cache. A report
	// repeating a nonce is not proof of the same run: --nonce can hand one
	// value to two runs.
	RunNonce string `json:"run_nonce"`
	// ControlNonce is the marker on the calibration controls. It is fresh per
	// run, whatever RunNonce was set to.
	ControlNonce string `json:"control_nonce"`

	// Verdict is ADMISSIBLE or INCONCLUSIVE. On INCONCLUSIVE the samples are
	// still emitted (they are evidence about the environment) but no headline
	// number may be quoted from them.
	Verdict            string    `json:"verdict"`
	InadmissibleReason string    `json:"inadmissible_reason,omitempty"`
	Controls           []Control `json:"controls"`
	// FramingFloorReuse is what an UNRELATED prompt still reuses: the shared
	// template + tool-spec prefix every production request carries. It is the
	// zero point every other reuse number should be read against, not an
	// anomaly — measured ~0.17 once the real tool specs are sent.
	FramingFloorReuse float64 `json:"framing_floor_reuse"`

	Arms        []ArmStats    `json:"arms"`
	Overflow    OverflowStats `json:"overflow"`
	Paired      PairedTotals  `json:"paired_totals"`
	SizeVsCache SizeVsCache   `json:"size_vs_cache"`
	Estimator   EstimatorFit  `json:"estimator_fit"`
	MarginTable []MarginRow   `json:"margin_table"`
	Samples     []Sample      `json:"samples"`
	Limits      []string      `json:"limits"`
}

KVReport is the bench artifact. Samples are RAW — every headline number below can be re-derived from them.

func RunBench

func RunBench(ctx context.Context, probe ProbeFunc, entries []Entry, corpusHash string, opts BenchOpts) (KVReport, error)

RunBench executes the full measurement: controls, both arms in blocks, then closing controls — repeated for opts.Rounds. It NEVER returns a headline number without an admissible instrument.

type KindStats

type KindStats struct {
	Kind           string  `json:"kind"`
	Entries        int     `json:"entries"`
	MeanRatio      float64 `json:"mean_ratio"`
	MeanRetention  float64 `json:"mean_retention"`
	FitBudgetShare float64 `json:"fit_budget_share"`
	TotalLostCount int     `json:"total_lost_count"`
}

KindStats aggregates one content-kind bucket.

type LadderOpts

type LadderOpts struct {
	GCF      bool `json:"gcf"`
	Skeleton bool `json:"skeleton"`
	// Search and Logs switch on the two default-off rungs (thin older search
	// listings; fold runs of near-identical lines in older build and test output).
	Search bool `json:"search"`
	Logs   bool `json:"logs"`
}

LadderOpts selects the optional rungs for a replay run (mirrors production flags --gcf-compact / --skeleton-prune).

func (LadderOpts) Label

func (o LadderOpts) Label() string

Label is the ladder id stamped into reports: the enabled rungs joined by "+" in the fixed order gcf, skeleton, search, logs ("gcf+skeleton+search"), or "base" when none is on.

type MarginRow

type MarginRow struct {
	RatioCovered  float64 `json:"ratio_covered"` // real/estimated this margin survives
	ImpliedS      int     `json:"implied_margin"`
	InputBudget   int     `json:"input_budget"`    // ctx - maxOut - S
	BudgetCostPct float64 `json:"budget_cost_pct"` // budget lost vs S=0
}

MarginRow is one line of the safety-margin decision table.

func MarginTable

func MarginTable(ratios []float64, ctxTokens, maxOut int) []MarginRow

MarginTable builds the operator-facing decision table. It deliberately returns a TABLE, not a recommendation: raising the margin buys safety by unconditionally shrinking usable context on every request, and that is the operator's trade to make.

type OverflowStats

type OverflowStats struct {
	OffErrors int `json:"off_errors"`
	OnErrors  int `json:"on_errors"`
	// Timeouts and OtherErrors keep every failure visible. A client timeout
	// carries the text "context deadline exceeded", which a naive substring
	// match on "context"/"exceed" would file as an overflow — i.e. as evidence
	// FOR the phase's own headline. Timeouts are therefore classified first
	// and counted separately, and anything unrecognised lands in OtherErrors
	// rather than nowhere.
	Timeouts    int `json:"timeouts"`
	OtherErrors int `json:"other_errors"`
}

OverflowStats counts requests the SERVER REJECTED for exceeding the context window, per arm. This is not noise: it is the failure the ladder exists to prevent, and an off-arm overflow means that request would simply not have completed at all.

type PIIFinding

type PIIFinding struct {
	EntryID string
	Class   string
}

PIIFinding names one refusal hit (entry + class only — the matched text is deliberately NOT echoed back).

func VetPII

func VetPII(entries []Entry) []PIIFinding

VetPII scans every turn body AND every tool-call name/args (raw tool arguments are exactly where harvested transcripts carry credentials) and returns the findings. A non-empty result means the corpus is NOT usable — callers refuse to evaluate it.

type PairedTotals

type PairedTotals struct {
	PairedSteps int `json:"paired_steps"`
	UnpairedOff int `json:"unpaired_off"`
	UnpairedOn  int `json:"unpaired_on"`

	OffRealPromptTokens int `json:"off_real_prompt_tokens"`
	OnRealPromptTokens  int `json:"on_real_prompt_tokens"`
	// SizeEffectTokens: real prompt tokens saved by a smaller transcript (off-on).
	SizeEffectTokens int `json:"size_effect_tokens"`
	OffPrefilled     int `json:"off_prefilled_tokens"`
	OnPrefilled      int `json:"on_prefilled_tokens"`
	// PrefillDeltaTokens = on - off. POSITIVE means compaction made the server
	// do MORE prefill work despite sending fewer tokens, because each fire
	// discards the KV cache.
	PrefillDeltaTokens int `json:"prefill_delta_tokens"`
}

PairedTotals compares the arms over the INTERSECTION of steps that succeeded in BOTH — the only apples-to-apples comparison. Totals over unequal sample sets would silently overstate whichever arm had fewer (usually larger) requests. Unpaired steps are reported, never dropped in silence.

type PrefixRelation

type PrefixRelation string

PrefixRelation classifies how a request relates to the one before it — the distinction that decides whether the KV cache survives. Measured on this stack: EXTENSION and TRUNCATION reuse; DIVERGENT collapses the whole cache (a sliding-window model cannot truncate mid-sequence and continue).

const (
	RelExtension  PrefixRelation = "extension"  // previous stream is a prefix of this one (or identical)
	RelTruncation PrefixRelation = "truncation" // this stream is a strict prefix of the previous
	RelDivergent  PrefixRelation = "divergent"  // they part company mid-stream
	RelNone       PrefixRelation = "none"       // nothing cached yet
)

func Relation

func Relation(prev, cur []agent.Msg) (rel PrefixRelation, sharedChars int, sharedFrac float64)

Relation classifies prev→cur, reporting how many bytes they share and what fraction of the previous stream survived.

MEASURED RULE (gemma-4-e4b, llama.cpp b50, --cache-reuse unset, 2026-07-24): reuse is BINARY, not proportional. An EXTENSION reuses everything the server already held — appending a turn to a 2429-token prompt reused 2429 and prefilled only the 19 new tokens, corroborated by ~80 append steps per arm reusing a median 0.88 of their (larger) prompts. ANY divergence discards the WHOLE cache regardless of how much was shared: a position sweep editing one line at 4%, 17%, 33%, 50%, 62%, 75%, 83%, 92% and 98% of a 120-line prompt returned cache_n of 1,1,1,1,1,0,0,0,0 — even a divergence two lines from the end cost all 2662 tokens. SharedFrac is therefore recorded as evidence, NOT as a predictor: on this stack only the relation matters.

This is why the compaction ladder cannot be "KV-friendly" by being monotonic: it edits older turns, and any edit at all is a full re-prefill.

type ProbeFunc

type ProbeFunc func(ctx context.Context, msgs []agent.Msg) (ProbeResult, error)

ProbeFunc issues ONE measured request and returns the server's accounting.

type ProbeResult

type ProbeResult struct {
	CacheN            int     `json:"cache_n"`
	PromptN           int     `json:"prompt_n"`
	PromptMS          float64 `json:"prompt_ms"`
	PredictedMS       float64 `json:"predicted_ms"`
	UsagePromptTokens int     `json:"usage_prompt_tokens"`
	UsageCachedTokens int     `json:"usage_cached_tokens"`
	WallMS            float64 `json:"wall_ms"`
	// Measured: the backend reported SOME accounting (usage and/or timings).
	// KVMeasured: it reported the TIMINGS block, the only source of KV reuse.
	// A backend that emits usage but no timings (vLLM, OpenAI, most proxies)
	// is Measured && !KVMeasured — reporting reuse=0 for it would be exactly
	// the "unmeasured read as measured zero" the design forbids.
	Measured   bool `json:"measured"`
	KVMeasured bool `json:"kv_measured"`
}

ProbeResult is one measured request as the SERVER reported it. Measured is false when the backend reported no accounting at all — an unmeasured request must never be read as "zero reuse".

func (ProbeResult) RealPromptTokens

func (r ProbeResult) RealPromptTokens() int

RealPromptTokens is the server's true prompt length: reused + prefilled. Prefer usage.prompt_tokens when present (it is the same number by a different route and cross-checks the timings block).

type Redactor

type Redactor struct {
	// contains filtered or unexported fields
}

Redactor substitutes stable placeholders for vet-class matches. The same matched text always yields the same placeholder (numbered by first appearance, per class), so two different values stay two different values after redaction and a re-run over the same input is byte-identical.

func NewRedactor

func NewRedactor() *Redactor

NewRedactor returns a fresh redactor; use one per corpus so placeholders number from 1.

func (*Redactor) Hits

func (x *Redactor) Hits() map[string]int

Hits returns the substitutions made so far, by vet class (a copy).

func (*Redactor) Redact

func (x *Redactor) Redact(s string) string

Redact returns s with every vet-class match replaced by its placeholder.

func (*Redactor) Residual

func (x *Redactor) Residual(s string) []string

Residual names what is still wrong with s after this redactor has run over it: the vet classes that still match; "value-tail" when 12 or more consecutive characters of a credential value this redactor replaced are still in s (a tail such as ".payload.signature" matches no vet class); and the name of the keyword check (piishape.KeywordRunClass) when a credential header keyword (cookie, authorization, api key, auth token, security token) is followed within a few characters by a long value run, whatever shape stands between them. The last one fails closed: it does not read shapes, so it catches the ones the classes do not know, and it also stops text that merely follows a keyword (see piishape.KeywordRun). Run it over every string about to be written; a non-empty answer means nothing may be written.

type Report

type Report struct {
	CorpusHash string        `json:"corpus_hash"`
	Ladder     string        `json:"ladder"`
	ModelIDs   []string      `json:"model_ids,omitempty"`
	Entries    []EntryResult `json:"entries"`
	PerKind    []KindStats   `json:"per_kind"`
}

Report is the eval artifact. CorpusHash pins WHICH corpus produced it; Ladder pins which rungs ran; ModelIDs record the serving context for runs whose scores involve a model (the deterministic replay itself is model-free, so ModelIDs may be empty there — honesty over decoration).

func Evaluate

func Evaluate(entries []Entry, corpusHash string, opts LadderOpts) Report

Evaluate replays every entry and aggregates per kind. Pure of I/O.

type Sample

type Sample struct {
	Arm       string `json:"arm"` // "off" | "on"
	Round     int    `json:"round"`
	EntryID   string `json:"entry_id"`
	EntryKind string `json:"entry_kind"`
	Step      int    `json:"step"` // prefix length (message count) replayed

	// FirstStep marks the first request of an entry: the cache holds the
	// PREVIOUS entry, so a near-zero reuse here is conversation-start, not a
	// ladder property. Aggregation counts these separately in both directions.
	FirstStep bool `json:"first_step"`

	// Ladder facts (offline, deterministic).
	Fired           bool `json:"fired"`            // the ladder changed the transcript on this step
	DropFired       bool `json:"drop_fired"`       // a whole turn was dropped (turn count shrank)
	Exhausted       bool `json:"exhausted"`        // ladder ran and still could not fit the budget
	DivergenceIndex int  `json:"divergence_index"` // first message index differing from the previously SENT transcript; -1 = pure append
	// PrefixRelation/PrefixSharedChars describe the BYTE-stream relationship to
	// the previous request — the actual predictor of KV survival.
	PrefixRelation    string  `json:"prefix_relation"`
	PrefixSharedChars int     `json:"prefix_shared_chars"`
	PrefixSharedFrac  float64 `json:"prefix_shared_frac"` // how much of the PREVIOUS stream survived
	// PrevRealTokens is the server-reported length of the PREVIOUS successful
	// request — the yardstick the eviction invariant needs (see
	// SuspectedEviction); 0 when there was no previous request.
	PrevRealTokens int `json:"prev_real_tokens"`
	EstTokens      int `json:"est_tokens"` // the ladder's own chars/4 estimate of what was sent
	SentMsgs       int `json:"sent_msgs"`
	SentChars      int `json:"sent_chars"`
	// SentSHA256 is the sha256 of the transcript the ladder produced, taken
	// BEFORE the nonce salt and over its canonical encoding, not over the HTTP
	// request body. It does not depend on the run's nonce or arm, so equal
	// values for one step prove a pair of runs sent the same transcript.
	SentSHA256 string `json:"sent_sha256"`

	// Server facts (measured).
	Probe     ProbeResult `json:"probe"`
	ReuseFrac float64     `json:"reuse_frac"`
	// Error is set when the server REJECTED the request — data, not a run
	// failure: the compaction-off arm is expected to overflow the window on
	// long transcripts, which is exactly the failure the ladder prevents.
	Error string `json:"error,omitempty"`
	// ErrorClass is "overflow" | "timeout" | "other" — a timeout carries the
	// text "context deadline exceeded" and must never be filed as an overflow.
	ErrorClass string `json:"error_class,omitempty"`
	// EvictionSuspected marks a sample the SCHEDULER ruined rather than the
	// ladder — see SuspectedEviction. Recorded per row so the exclusion is
	// auditable rather than silent.
	EvictionSuspected bool `json:"eviction_suspected,omitempty"`
	// EstRatio is real/estimated — the estimator's error on this exact
	// payload, the only sound basis for tuning the compaction safety margin.
	EstRatio float64 `json:"est_ratio"`
}

Sample is one row of the bench: a single measured request plus the offline facts needed to interpret it. Rows are emitted RAW and never pre-aggregated, so a reader can re-derive every headline number.

func (Sample) SuspectedEviction

func (s Sample) SuspectedEviction() bool

SuspectedEviction reports whether this sample measured the SCHEDULER instead of the ladder.

The test needs no extra requests, which is the point: injecting inline control shots between body requests would itself destroy the cache continuity being measured. It uses a measured INVARIANT — on a pure prefix EXTENSION the server keeps everything it already held — so an extension that LOST that content was torn down between the two requests. Mid-run evictions are not theoretical here: a single /v1/embeddings call causes one.

The comparison is cache_n vs the PREVIOUS prompt's real length, NOT the reuse fraction. Reuse is a fraction of the NEW prompt, so appending a 750-token tool result onto a 17-token prefix legitimately scores 0.02 while the cache did its job perfectly — an earlier version of this check used that fraction and silently deleted ~20% of the body, biasing every median upward.

type Scorer

type Scorer func(ctx context.Context, rendered string) (float64, error)

Scorer scores one rendered transcript (higher = better task signal). The concrete signal is injected — the CLI wires the pipeline's accept+grounded OUTCOME scorer (see compaction_eval.go); tests inject deterministic fakes.

type SizeVsCache

type SizeVsCache struct {
	OffRealPromptTokensUnpaired int `json:"off_real_prompt_tokens_unpaired_diagnostic"`
	OnRealPromptTokensUnpaired  int `json:"on_real_prompt_tokens_unpaired_diagnostic"`
	OffPrefilledUnpaired        int `json:"off_prefilled_tokens_unpaired_diagnostic"`
	OnPrefilledUnpaired         int `json:"on_prefilled_tokens_unpaired_diagnostic"`
	// Cache effect per arm: tokens the SERVER skipped via KV reuse.
	OffCacheEffectTokens int    `json:"off_cache_effect_tokens"`
	OnCacheEffectTokens  int    `json:"on_cache_effect_tokens"`
	Note                 string `json:"note"`
}

SizeVsCache is a PER-ARM diagnostic only: raw totals over each arm's own successful samples, which are NOT the same step set (the off arm loses steps to overflow rejections). Differences between these columns are not a valid comparison — PairedTotals is. Field names carry the warning so a reader grepping the JSON cannot mistake one for the other.

type TraceRecord

type TraceRecord struct {
	ID         string      `json:"id"`
	Goal       string      `json:"goal"`
	StopReason string      `json:"stop_reason"`
	Steps      int         `json:"steps"`
	Output     string      `json:"output"`
	Error      string      `json:"error,omitempty"`
	Transcript []agent.Msg `json:"transcript"`
}

TraceRecord mirrors cmd/local-agent's on-disk trace shape: record fields are snake_case-tagged there; the embedded agent.Msg fields are UNTAGGED, so the transcript decodes with Go's default capitalized keys — decoding straight into []agent.Msg matches the writer byte-for-byte.

type Turn

type Turn struct {
	Role       string         `json:"role"`
	Content    string         `json:"content"`
	ToolCalls  []TurnToolCall `json:"tool_calls,omitempty"`
	ToolCallID string         `json:"tool_call_id,omitempty"`
}

Turn is the corpus wire format for one message — EXPLICIT lowercase tags so a corpus can never half-parse: agent.Msg's fields are untagged, and Go's case-insensitive fallback would accept "Role" but silently MISS snake_case keys like "tool_call_id", producing empty pairing fields and replay behavior that differs from production without any error. This struct + strict decoding is the contract; ToMsg converts to the ladder's type.

func MsgsToTurns

func MsgsToTurns(msgs []agent.Msg) []Turn

MsgsToTurns is ToMsgs' inverse: ladder messages → the corpus wire format. agent.Msg's IsError has no wire slot on purpose — the production ladder never reads it, so carrying it would imply a replay distinction that doesn't exist.

type TurnToolCall

type TurnToolCall struct {
	ID   string `json:"id"`
	Name string `json:"name,omitempty"`
	Args string `json:"args,omitempty"`
}

TurnToolCall mirrors agent.ToolCall in wire casing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL