Perf take 5 P0 (§60.0): the harness tells the truth — schema 2 (units, status, result counts, client shape, fingerprints), command-bearing offers measured by a real execute phase with applyEdit capture, offerkinds/offerqueue phases, cold sweep tries actually cold; reference re-taken on the unchanged 0.50.0 binary
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 34s

This commit is contained in:
lucio committed 2026-09-07 14:35:12 -05:00
1 parent 9c75b7a4e5
commit 501b36d8b8
13 files changed
+1750 -263

No files matched your search

+21 -6
View File
@@ -5688,33 +5688,48 @@ reported with the measured remaining stage, never hidden.
### 60.0 P0 — the harness tells the truth (tools/perf only)
Plan §P0. Files: `tools/perf/*` and its README; no production change.
- [ ] units and status on every new record (`ms` is latency only; RSS
Done 2026-09-07; `docs/features/perf5-p0/README.md`, experiment
`P0-2026-09-07` in the tracker.
- [x] units and status on every new record (`ms` is latency only; RSS
and store size in their own fields with units; `status`
ok/error/refused; result counts; a normalized fingerprint of
edits/warnings); the schema versioned, the take-4 rows still
readable
- [ ] edit-bearing offers → `codeAction/resolve`; command-bearing
— `tools/perf/schema.py` (new); `record()` validates, `samples()`
replaces `Session.ms` so a failed request is never a fast success
- [x] edit-bearing offers → `codeAction/resolve`; command-bearing
offers (extract, inline) → a separate execute-command scenario
that captures the server's `workspace/applyEdit` payload and
replies `applied: false` (reason recorded as a client capture,
distinct from an engine refusal or an error); created files,
edits, refusals, warnings counted
- [ ] the owner's two supplemental probes become phases
— phase `execute`: extraction 257 / 245–247 ms, 2 edits / 2 files
/ 1 created, status `capture`; both `aes_wrap.sv` 66:2 offers
`refused` with the engine's own sentence
- [x] the owner's two supplemental probes become phases
(`offerkinds`: the `context.only` families at the five cursors;
`offerqueue`: leader/follower); scan completion vs first useful
answer separated; fresh-process rows distinguished from repeats
- [ ] `sweep.sh`: the scratch format cache reset before *each* cold
- [x] `sweep.sh`: the scratch format cache reset before *each* cold
try, warm rows explicitly primed; cold rows show zero hits
- [ ] the baseline reproduced on the unchanged binary with the
— verified on `hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`
- [x] the baseline reproduced on the unchanged binary with the
corrected harness — the tracker's "Reference" cells for every
row P1/P2 will touch (pinmux comment all-family and `only: []`,
`aes`/`aes_reg_top`/`tb.sv` offers, tail rename, `aes` rename,
blockers, refactor resolves, the CLI cells) — and a
`docs/perf/README.md` note if any baseline row changes meaning
- [ ] QA: a deliberately rejected request lands as an error; the
— 114 rows, zero guard kills, corpus unchanged after all 16 runs;
every CLI stdout hash byte-identical to the baseline's; three rows
disagree beyond tolerance and are named, not adjusted
- [x] QA: a deliberately rejected request lands as an error; the
inline/extract rows show a command and an applyEdit payload or a
refusal; cold sweep rows have zero hits; a sample of reference
cells re-taken
— PASS, 2026-09-07: `docs/features/perf5-p0/README.md` QA log; ten
REF cells re-taken (two fingerprints byte-identical), all four
acceptance experiments and the schema/`resolve_rows` attacks verified
independently, the three named disagreements reproduce and are real
### 60.1 P1 — code-action discovery stops repeating work
+433
View File
@@ -0,0 +1,433 @@
# perf5-p0 — the harness tells the truth
Take 5 §P0 / TODO §60.0. Harness only: no Rust source is touched.
## Goal
Before any of take 5's optimizations is measured, the measuring instrument
has to mean what it says. `docs/performance_take5.md` §P0 names four ways
`tools/perf` did not: `phase_refactor` sent extract and inline offers —
which carry a **command**, not an edit — to `codeAction/resolve`, where
dispatch handed them to the ports resolver and got a refusal, so their tiny
times measured nothing; `Session.ms` discarded the response, so a request
that *failed* was recorded as a fast success; `phase_rss` put idle RSS in a
field called `ms`, which is neither a latency nor a peak; and
`sweep.sh::run_cell` deleted the format cache once before three "cold" tries,
so two of every three were warm. This stage fixes all four, adds an explicit
record schema (version, units, status, result count, client shape,
fresh-process flag, edit fingerprint), promotes the owner's two supplemental
scratch probes into committed phases, and reproduces the owner's baseline on
the unchanged 0.50.0 binary with the corrected harness so later stages have a
reference measured by the instrument they will be judged with.
## Assumptions
- The corpus (`/Users/guoliangchen/repo/opentitan` at `0098135264`) is
read-only and stays at its three pre-existing modified files. Every edit a
request returns is discarded, and the new `execute` scenario answers the
server's `workspace/applyEdit` with `applied: false`.
- `target/release/lucisv{,-server}` at 0.50.0 are the baseline binaries
(sha256 `894054128…` / `27e0a0df…`); no `cargo` command runs during a timed
phase.
- A refusal returned as JSON-RPC `RequestFailed` (-32803) is the engine's own
sentence; any other error code is a genuine failure. That split is what
distinguishes `status: refused` from `status: error`.
- `ps -o rss=` polled at 50 ms is an acceptable stand-in for peak RSS on this
workload; the row says so rather than claiming a kernel high-water mark.
- The machine runs a live desktop session. Load is recorded before and after
every phase and was 2.92–5.21 throughout, against the baseline's 2.92–4.59.
## Handshakes
- **With `lucisv-server` (consumed, unchanged).** The client now advertises
`workspace.applyEdit: true` and `workspace.workspaceEdit.resourceOperations:
["create", …]` in the `execute` phase, which is what
`main.rs::apply_edit_support` and `create_files_support` read. That takes
the branch a real editor takes: `server/client.rs::deliver` pushes the edit
instead of returning it. No server change is requested or needed.
- **With `docs/perf/take5-baseline/` (consumed, never written).** The
baseline's rows are schema 1 and stay exactly as they are. Schema 2 is
additive: a row without a `schema` key is schema 1, read with take 4's
prose.
- **With `docs/perf/take5-tracking.md` (produced).** This stage fills the
P0 row's candidate identity, every "Reference — agent fills" cell it
measured, and one experiment entry. Baseline cells are never overwritten.
- **Promised to P1–P4.** New rows carry `schema`, `units`, `status`,
`result_count`, `client`, `fresh_process`, and — where an edit exists —
`edits`/`files`/`created`/`fingerprint`. **No document may quote a row whose
`status` is not `ok` or `capture`**, the sole exception being a row whose
`expected_status` names the rejection it was built to get (the transport
floor). `schema.quotable(row)` is that rule in code.
## Status / TODO
- [x] `schema.py`: schema 2 — version, units, status vocabulary, result
count, normalized edits, `counts()`, `fingerprint()`, `quotable()`
- [x] `harness.record()` stamps and validates schema/units/status; a failing
status without a message, an unknown status, or `units: ms` with no
`ms` list raises instead of reaching a document
- [x] `harness.samples()` replaces `Session.ms` in every phase: the responses
are kept, so an error is recorded as an error
- [x] `lspclient`: `workspace/applyEdit` captured, timed, and declined with
`schema.CAPTURE_REASON`; `workspace.applyEdit` / `resourceOperations`
capabilities; `client_shape()`; answered server requests no longer
accumulate in the inbox
- [x] `phases_p0.execute`: command-bearing offers run through
`workspace/executeCommand`; edit-computation and delivery halves timed
separately; edits/files/created counted and fingerprinted
- [x] `phases_new.resolve_rows`: an offer with an `edit` needs nothing, one
with only a `command` is routed to `execute` and **not** timed as a
resolve, one with neither is resolved
- [x] `phases_p0.offerkinds` — the owner's `context.only` probe, promoted
- [x] `phases_p0.offerqueue` — the owner's leader/follower probe, promoted,
with `leader_ms` and `follower_ms` in their own fields
- [x] `scan` reports settled time and first-useful-answer separately, in
separate fresh sessions, so the settled series stays comparable
- [x] `phase_rss`: `rss_kib` / `peak_rss_kib` / `store_kib`, `units: KiB`,
no `ms` field; peak from a 50 ms `ps` poll across the scan
- [x] `sweep.sh`: the scratch format cache deleted before **each** cold try;
warm cells primed by one explicit untimed run; `sweeptable.py` prints
the hits per try and flags a cold try with a hit
- [x] verified on `hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`
- [x] `tools/perf/README.md` documents the schema, the phases, the status
vocabulary and the quoting rule
- [x] the baseline reproduced on the unchanged binary; tracker reference
cells and the P0 experiment entry filled
- [x] QA — PASS, 2026-09-07 (see QA log)
## Work log
### 2026-09-07 — dev (Opus)
**Environment, checked first.** `lucisv 0.50.0`; sha256 of
`target/release/lucisv` `894054128495b764…` and `lucisv-server`
`27e0a0df5b77102e…` — both identical to `take5-baseline/metadata.json`, so
**no rebuild was needed and none was run**. Corpus `git status --porcelain`
showed exactly the three expected files before the round and after every
phase. A CI runner's `cargo build --release -p lucisv` (an `act` host
executor, not this tree) was found at 100% of a core at the start of the
session; **no timing was taken until it exited**, and load was back to
4.04–4.54 before the first timed phase.
**What changed, file by file.**
- `tools/perf/schema.py` (new, 168 lines). The record vocabulary: `SCHEMA`,
`STATUSES`, `REQUEST_FAILED`, `CAPTURE_REASON`, `status_of`, `quotable`,
`worst`, `result_count`, `normalized`, `counts`, `fingerprint`, `edit_of`.
`status_of` splits an engine refusal (`RequestFailed`, -32803) from a real
error by code. `fingerprint` is sha256 over the sorted
`(uri, start, end, newText)` edits, the sorted created paths and the sorted
warnings — both `changes` and `documentChanges` shapes are read, because an
extraction that creates a file cannot use the map.
- `tools/perf/lspclient.py`. `Session(apply_edit=, create_files=)`;
`workspace/applyEdit` answered by `_capture_apply_edit`, which stamps the
arrival instant, stores the payload and replies `applied: false` with the
capture reason; `take_applied()`; `client_shape()`; the capability block
gained `workspace.applyEdit` and `resourceOperations`; `_drain_locked` now
moves answered server→client requests into `server_requests` instead of
leaving them in the inbox forever.
- `tools/perf/harness.py`. `record()` stamps `schema`/`units`/`status`/
`fresh_process` and *validates*; `Samples`/`samples()` keep every response
and expose `.row()` (the `ms`/`status`/`result_count`/`message` a request
row always carries); `session()` passes the two new capabilities;
`result_count` now comes from `schema`; the old `tries()` was removed
because `samples()` supersedes it and nothing else used it.
- `tools/perf/phases_p0.py` (new, 304 lines). `execute`, `offerkinds`,
`offerqueue`, and `first_useful_rows()` (called by `scan`), plus
`shape_of` / `command_of` / `open_and_settle`, which `phases_new` and
`bench` also use.
- `tools/perf/phases_new.py`. `resolve_rows()` does the routing; `refactor`,
`tailrename`, `didopen`, `tailcompletion`, `hierarchy` write schema-2 rows;
`phase_rss` rewritten around `rss_kib`/`peak_rss_kib`/`store_kib` and a
`Sampler` thread.
- `tools/perf/bench.py`. Every phase moved to `samples()`; `codeaction`,
`portaction`, `probe` record offer shapes; `blockers` records the leader in
`ms` and each follower in `follower_ms`; `scan` calls
`phases_p0.first_useful_rows()`; the transport floor carries
`expected_status: "error"`.
- `tools/perf/sweep.sh`. Cold cache reset **per try**; warm cells primed by
one untimed run behind a `--- prime (untimed, not a try) ---` marker; an
optional sixth argument narrows the tree list.
- `tools/perf/sweeptable.py`. Reads only the blocks after a `--- try N ---`
marker (so a prime is never a trial) and prints the format-cache hits per
try, flagging any cold try with a hit.
- `tools/perf/README.md`. The file table, the new phases, and a
"The record schema (`schema` 2)" section: every field, the status
vocabulary, the quoting rule, and why `execute` exists.
**The execute rows — the thing take 4 could not measure.** With
`workspace.applyEdit` and `resourceOperations: ["create"]` advertised, the
server pushes the edit instead of returning it, and the push is timed and
declined.
| Site | Command | Status | ms (executeCommand → applyEdit) | edits / files / created |
|---|---|---|---:|---|
| `aes.sv` 220:0–222:53 selection | `lucisv.extractModule` | `capture` | 257.33 / 245.05–247.00 | 2 / 2 / **1** |
| `aes_wrap.sv` 66:2 | `lucisv.inlineModule` | `refused` | 6.58 / 5.87–6.20 | — |
| `aes_wrap.sv` 66:2 (extract, also offered there) | `lucisv.extractModule` | `refused` | 817.37 / 793.77–809.07 | — |
The extraction's `applyEdit` label is `lucisv: lucisv.extractModule`;
`deliver_ms` (our `applied: false` → the command's response) is
0.015–0.033 ms, so essentially all of the 250 ms is the edit computation. The
fingerprint is `090e92e7736e0a5a…`. **Nothing was written**: the corpus status
was unchanged and `aes_extracted.sv`, which the server's own warning says the
edit would create, does not exist.
The phase was run twice (the second time after a cosmetic fix to the row's
`note` and to the fingerprint of a *refused* row, which now records `null`
rather than the hash of an empty edit). The second run reproduced the first:
extraction 255.90 / 242.17–245.70 ms, inline refusal 6.66 / 6.07–6.49,
extract refusal 820.93 / 794.46–806.51, and — the point of the fingerprint —
**the same `090e92e7736e0a5a…` for the extraction's edit**. The tracker
quotes the first run; both are in the raw evidence
(`results.jsonl`, `results-execute2.jsonl`).
Two findings fall straight out of these rows and are recorded, not fixed:
- The inline cursor's *extract* offer costs **793–817 ms to refuse**. A
refusal is not a measurement of an extraction, but it is a real interactive
cost of clicking an offer the engine will decline, and it is the second
~800 ms user-command path in this corpus after the tail rename.
- Take 4's `refactor` rows named `extract-module resolve: …` and
`inline-module resolve: …` are exactly the invalid rows §P0 describes.
They are gone; the phase now records those offers as `offer is a command:
… | timed by the \`execute\` phase, not by resolve`.
**Baseline reproduction.** 15 phases, `--tries 3`, one guarded run each, in
the order the baseline used, then the paired CLI experiment with the
configuration order alternating per trial. 114 rows: 110 `ok`, 1 `capture`
(the extraction), 2 `refused` (both engine sentences at the inline cursor),
1 `error` (the transport floor, with `expected_status: "error"`). Corpus
unchanged after all 16 runs; no guard kill; load 2.92–5.21.
Every reference cell agreed with the owner's baseline inside the tracker's
tolerance except three; all three are recorded in the tracker's experiment
entry and neither number was adjusted:
- `tb.sv` comment lazy: 3.80–4.79 ms against 3.22–3.50 (+27.9% on the
medians). A ~4 ms row on a machine whose load band differed slightly.
- `didChange` flush: 0.93–1.01 ms against 0.66–0.72 (+35.5%).
- `nav definition` (+132%) and the transport floor (+10.6%) are both
sub-millisecond and are **not read**, per the round's own rule.
The CLI cells are stronger than the timings alone: the **stdout sha256 of
every configuration matches the baseline's byte for byte** (default,
all-style, all-style minus `unused-import`, format cold, format warm), and
the paired means are within 2.6% except `default`, whose baseline first trial
the owner already flagged as an outlier.
**Two observations worth carrying into P4** (measured, not acted on):
- The first useful answer during a **cold** scan arrives in 84–86 ms with a
correct result, while the same request during a **warm** scan takes
206–219 ms. A warm cache does not make the first answer faster here.
- Peak RSS across the scan equals idle RSS to the KiB in all six sessions:
the server's resident set rises monotonically to its idle value and there
is no transient above it on this workload.
**Deviations from the brief.**
- The two supplemental probes became `offerkinds` and `offerqueue`; the CLI
probe stayed a scratch script (as the owner's was), because folding its
`--ignore unused-import` cell into `sweep.sh` would change the committed
sweep's cell set for all five trees. `sweep.sh` got only the cold-cache fix
it was asked for, plus an optional tree-list argument.
- `scan`'s first-useful-answer rows are measured in *separate* fresh sessions
from the settled rows, not the same ones. Serving a request during a scan
perturbs the scan, and the settled series has to stay comparable with take
4's, which had nothing in flight. Both are `scan` rows and both fields are
named; the perturbed settle is kept beside the first answer as
`settled_ms`.
- The `scan` phase was run twice. The first run's first-useful rows carried a
hard-coded `result_count: 1`; that was a bug in the new code, fixed
(`result_counts` now holds the real per-session counts), and all four
workspace scan cells are quoted from the second run so they come from one
consistent build of the harness. Both runs are in the raw evidence.
**Gates.** `python3 -m py_compile tools/perf/*.py` and `bash -n
tools/perf/*.sh` clean. No Rust changed, so `cargo` was not run — and could
not have been, mid-round.
## QA log
### 2026-09-07 — QA (Sonnet)
**Scope.** Verified TODO §60.0 / `docs/performance_take5.md` §P0 against the
working tree (`tools/perf/{schema.py,phases_p0.py}` new;
`{bench.py,harness.py,lspclient.py,phases_new.py,sweep.sh,sweeptable.py,
README.md}` changed) and the dev's evidence in
`~/.cache/lucisv-perf/take5-p0/`. Everything below was re-run independently
on the same binaries under `tools/guard.sh -m 8 -t 1800`; my own raw evidence
is in
`/private/tmp/.../scratchpad/qa-p0/{results.jsonl,attack*.jsonl,schema_attack.jsonl,resolve_attack.jsonl,sweep/,sweep2/}`.
Nothing in this section touches the dev's files or the baseline.
**Environment, checked first and after.** `git -C
/Users/guoliangchen/repo/opentitan status --porcelain` showed exactly the
three expected files (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
before any run and after every phase, every attack script and both sweeps;
no `aes_extracted.sv` or any other new file ever appeared. `sha256`
of `target/release/lucisv` (`894054128…`) and `lucisv-server` (`27e0a0df5b…`)
matched the recorded baseline both before and after the whole session — no
`cargo` command was run by QA. Zero guard kills across every invocation.
**1. Static.** `python3 -m py_compile tools/perf/*.py` and `bash -n
tools/perf/*.sh` both clean. Line counts: `bench.py` 476, `lspclient.py` 471,
`phases_p0.py` 304, `phases_new.py` 263, `schema.py` 168, `harness.py` 183,
`sites.py` 122, `sweeptable.py` 126, `sweep.sh` 76, `outcomes.sh` 47 — all
under the 500-line target. `tools/perf/README.md`'s "The record schema"
section documents every schema-2 field, the four-value status vocabulary and
`quotable()`'s rule, matching `schema.py` exactly. Take-4 rows (schema 1, no
`schema` key) in `docs/perf/take5-baseline/results.jsonl` and
`~/.cache/lucisv-perf/take4/results.jsonl` are plain JSON objects with no
`schema` key; every schema-2 reader (`harness.py`, `phases_new.py`,
`bench.py`) accesses fields with `.get()`/dict literals rather than requiring
`schema==2`, so they remain parseable — confirmed by loading both files with
`json.loads` line by line without error.
**2. Acceptance experiments — all four reproduced independently.**
- **(a) Rejected requests land as errors, never `ok`.** Ran the `baseline`
phase myself: the transport floor (`$/lucisvNoSuchMethod`) recorded
`status: error`, `code -32601: unhandled method`, distinct from an engine
refusal. I then hand-crafted two further bad requests through
`lspclient.Session` directly (not through a committed phase): a
`textDocument/codeAction` with a missing `range` field came back
`status: error, code -32602: missing field 'range'`; a `textDocument/rename`
at an out-of-bounds position came back `status: refused,
"lucisv: there is no symbol to rename at this position."`. Both were
correctly *not* logged as `ok` by `record()`/`samples()`. (One weaker probe
— `codeAction` on a URI the server had never opened — came back `ok` with
`result_count: 0`; that is the server choosing to answer an empty menu
rather than reject, which is correct LSP behavior and not a harness gap:
the zero count is exactly what `result_count` exists to make legible.)
- **(b) `execute` rows show a command and either an applyEdit payload or a
refusal.** Re-ran `execute` myself: extraction at `aes.sv` 220:0–222:53 —
**258.83 / 241.39–243.00 ms** (dev: 257.33 / 245.05–247.00), status
`capture`, 2 edits / 2 files / **1 created**, and the fingerprint came back
**byte-identical**: `090e92e7736e0a5a93557d75befa65a5bea0c2f44494d71dc67e3f8d70d05835`.
Inline at `aes_wrap.sv` 66:2 refused in 6.11–6.37 ms (dev: 6.58/5.87–6.20)
with the same `generate`-construct sentence; extract at the same cursor
refused after 798.22–816.94 ms (dev: 817.37/793.77–809.07) with the same
`h2d_intg` sentence. Corpus unchanged, no `aes_extracted.sv` created.
- **(c) Cold sweep tries have zero hits independently.** Ran `sweep.sh` on
`hw/top_earlgrey/ip` (46 files, all already needing reformatting, so it
cannot exercise a warm hit) — cold `0/0/0`, confirming the cold-per-try
fix. Then ran the full `hw/ip` cell as the plan suggested as a fallback:
**cold `0/0/0`, warm `30/30/30`**, byte-for-byte the number the dev
reported, plus matching summary lines (445 default violations, 7751 select
violations, 1772 files would reformat / 30 unchanged / 4 failed).
- **(d) RSS rows carry units, never `ms`.** Ran `rss` fresh: both rows had
`units: "KiB"`, `rss_kib`/`peak_rss_kib`/`store_kib` populated, and **no
`ms` key present at all** (checked with `'ms' in row` → `False`).
`store_kib` was **45404**, identical to the dev's. Idle/peak: cold
527.6/529.3/531.7 MiB, warm 575.8/575.7/573.8 MiB — both within the
tracker's REF band.
**3. Re-taken REF cells (ten, exceeding the eight required), both numbers
per cell (baseline/dev-REF vs my re-take, all on the unchanged 0.50.0
binary):**
| Cell | Dev REF | QA re-take |
|---|---|---|
| Pinmux comment, all families (`offerkinds`, `None`) | 333.89 / 307.35–312.97 | 343.03 / 306.82–311.74 |
| Pinmux comment, `only: []` | 81.72 / 82.27–84.11 | 82.29 / 82.51–84.68 |
| Offerqueue leader/follower | 339.53/339.47 (p1), 309.08/309.07 (p2), 309.73/309.72 (p3) | 341.77/342.65 (p1), 309.59/309.57 (p2), 308.65/308.63 (p3) |
| `aes_reg_top` lazy offer (`codeaction`) | 30.64 / 22.72–24.42 | 31.15 / 22.51–24.59 |
| `state_q` tail rename | 813.44 / 778.77–782.13; 5/2/0; fp `b39defb21265…` | 823.09 / 779.96–788.93; 5/2/0; fp **identical** `b39defb212655f29e68c0e15b88dda405d2779a24c4b522a1798b6f44c9a04f7` |
| `aes` rename | 167.60 / 140.46–142.13; 14/9/0; fp `fa7e31c78382…` | 168.84 / 140.58–141.67; 14/9/0; fp **identical** `fa7e31c78382176d5f96d661228ce82328df8bc77bd6d8575dd38717814cb26c` |
| Connect-missing-ports resolve | 171.37 / 165.77–167.45 | 171.995 / 165.26–166.15 |
| Cold workspace scan (3 fresh) | 2860.12–2868.45 | 2828.26–2848.97 (baseline 2830.30–2853.06) |
| Warm workspace scan (3 fresh) | 1346.02–1352.80 | 1312.68–1361.91 (baseline 1322.24–1344.03) |
| `didopen` pinmux row (3 fresh) | 119.01–131.85 | 109.12–135.15 |
All ten agree with the dev's REF within the tracker's tolerance (the two
fingerprinted rows match to the full 64-hex-character hash, which is the
strongest form of agreement available). The scan and didopen rows are
fresh-process ranges and show the expected extra spread of a 3-sample
wall-clock measurement on a shared desktop, but stay centered on the same
values.
**4. Schema attacks — all four raised, plus two negative controls.** Called
`harness.record()` directly (`schema_attacks.py`):
- `units="ms"` with no `ms` field → raised `ValueError: row 'a' says ms but
carries none`.
- `status="bogus"` → raised `ValueError: status 'bogus' is not one of (...)`.
- `status="error"`/`"refused"`/`"capture"` with no `message` → each raised
`ValueError: a '<status>' row must carry its message`.
- Negative controls (a well-formed `error` row with a message, and a `KiB`
row with no `ms`) did **not** raise, confirming the checks are precise, not
overzealous.
`resolve_rows()` (`resolve_attack.py`): called it with a fake `Session`
whose `.request()` raises `AssertionError` if invoked, and a synthetic
command-only action (`{"command": {"command": "lucisv.extractModule", ...}}`,
no `edit`). `resolve_rows` never called `.request()` — it recorded the
offer as `"... offer is a command: ..."`, `note: "timed by the execute
phase, not by resolve"`, confirming a command-only offer can never land as a
fast `ok` resolve.
**5. The three "disagrees beyond tolerance" rows — re-taken, and stable, not
noise.**
- `tb.sv` comment, lazy (`codeaction`, "comment line, lazy"): my re-take was
**7.73 / 4.42–5.42 ms**, still elevated over baseline's 3.22–3.50 and, if
anything, further from it than the dev's 3.80–4.79. Same direction, same
order of magnitude as a ~1–5 ms row on this desktop.
- `didChange` flush: my re-take was **1.35–1.64 ms** (first 2.19), against
baseline's 0.65–0.72 and the dev's 0.93–1.01 — again elevated, and by more
than the dev's own reading.
- Format-cold peak RSS: the dev's paired CLI run reported 246.5 MiB against
baseline 202.2. My independent `sweep.sh` run on `hw/ip` (not the paired
CLI script, but the same cell) reported **239 MB** peak RSS for
`format --check` cold — same elevated band, nowhere near the baseline's
202.2.
All three disagreements reproduce independently and in the same direction on
a second, unrelated invocation, which argues for a real (if small,
machine/load-dependent) effect rather than a one-off noisy sample. Correctly
left unadjusted by the dev; nothing here changes that.
**6. Traceability.** Sampled 20 numbers from the tracker's REF cells and the
`P0-2026-09-07` experiment entry and searched
`~/.cache/lucisv-perf/take5-p0/*.jsonl` for each. All 20 trace to the raw
evidence; the handful that did not match on a first plain-text `grep` (e.g.
`333.89`, `245.05`, `2860.12`, `535.2`) turned out to be the tracker's
2-decimal rounding of a longer float (`333.8862499804236`,
`245.04641597741283`, `2860.1173329807352`, `548032.0`/1024 = `535.19`
MiB) — confirmed by loading the exact row and comparing the full-precision
value. Nothing was actually missing.
**Verdict: PASS.**
No findings. All four §P0 acceptance criteria hold under independent
re-execution; ten re-taken REF cells (two with byte-identical 64-character
fingerprints) agree with the dev's numbers within tolerance; the schema and
`resolve_rows` attacks behave exactly as specified, including the negative
controls; the three named disagreements reproduce in the same direction on a
second run, supporting "real, not noise, and correctly left unadjusted";
traceability is complete once rounding is accounted for. Corpus, binaries
and guard were clean throughout. No fix was needed in `tools/perf`.
## Review
**2026-09-07 (lead).** Accepted. Read `schema.py`, `resolve_rows`, the
sweep change, the tracker's REF cells and experiment entry, both logs.
- The four §P0 defects are fixed the way the plan asked and nothing else
was touched: no production code, the baseline evidence untouched,
schema 2 additive over schema 1. `record()` refusing a malformed row
and `quotable()` as the quoting rule in code are the right place for
the discipline — a document cannot quote a rejection by accident.
- The reference re-take is the useful result: every row P1/P2 will be
judged against was re-measured by the instrument that will judge them,
on the same binary, and agrees with the owner's baseline inside
tolerance except three sub-5 ms rows that both dev and QA reproduce in
the same direction. Left unadjusted, correctly.
- Two new facts feed later stages: the extract command at the inline
cursor spends ~800 ms producing a refusal (P1 measures it after the
selector reuse, P2 owns it if it is scope work); and the first useful
answer during a warm scan is slower than during a cold one (206–219 vs
84–86 ms), a P4a lead.
- Deviation accepted: the CLI probe stays a scratch script beside
`sweep.sh` rather than changing the committed sweep's cell set.
+46
View File
@@ -1194,3 +1194,49 @@ every conclusion above is a 0.49.0-vs-0.43.0 pair from that window. Nothing
under 0.5 ms is read. No guard kill; the largest resident set anything reached
was 588 MB, 7% of the 8 GB limit. The opentitan checkout was never written and
its `git status --porcelain` was checked after every phase.
---
## 2026-09-07 — take 5 §P0: two take-4 row meanings are superseded
TODO §60.0, `docs/features/perf5-p0/README.md`. **No performance number here
changes**: P0 touched `tools/perf/` only, and the 0.50.0 binaries it measured
are byte-identical to the ones the take-5 baseline used. Two *meanings* do
change, and this note exists so nobody reads a take-4 row the wrong way.
- **The `rss` phase's `ms` field was never a latency.** Take 4's and the take-5
baseline's `rss` rows put idle RSS (KiB) in `ms` and the store size (KiB) in
`n`. Those rows stand as recorded; **new rows use `rss_kib`, `peak_rss_kib`
and `store_kib` with `units: "KiB"` and carry no `ms` at all.** Peak RSS is
new (a 50 ms `ps -o rss=` poll across the scan); on this workload it equals
idle RSS to the KiB in every session, so the resident set has no transient
above its idle value.
- **Take 4's `extract-module resolve` and `inline-module resolve` rows
measured a refusal, not a refactoring.** Those offers carry a *command*, not
an edit; `codeAction/resolve` on them reached the ports resolver, which
rejects an offer without its data. Nothing in take 4's document quoted them
in a conclusion, and the take-5 baseline README already excluded them. They
are now **removed from the harness**, and a new `execute` phase measures the
commands for real: `workspace/executeCommand`, the server's
`workspace/applyEdit` captured and timed, then declined with
`applied: false` so the corpus is never written. First readings on
opentitan at 0.50.0: `lucisv.extractModule` at `aes.sv` 220:0–222:53 costs
**257 / 245–247 ms** and pushes 2 edits across 2 files plus **1 created
file**; `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused**
(a `generate` construct) in 6 ms; and the *extract* offer at that same
cursor spends **793–817 ms** to produce a refusal — a second ~800 ms
user-command path beside §49's tail rename, filed for take 5's P1/P2.
Also fixed: `sweep.sh` deleted the scratch formatter cache once before three
"cold" tries, so tries 2 and 3 read what try 1 wrote. It now deletes it before
**each** cold try and primes warm cells with one untimed run, and
`sweeptable.py` prints the `N files from cache` each try reported. Verified on
`hw/ip` at 0.50.0: cold `0 / 0 / 0`, warm `30 / 30 / 30`. **Take 4's §7 cold
sweep numbers were measured with the old behaviour** and should be read as
"one cold try plus two warm ones", not as three cold tries.
Every new row is schema 2 — version, units, status, result count, client
capability shape, fresh-process flag, edit fingerprint — and **no document may
quote a row whose `status` is not `ok` or `capture`**. `tools/perf/README.md`
has the full vocabulary; the reference measurements are in
`docs/perf/take5-tracking.md`.
+225 -73
View File
@@ -8,20 +8,20 @@ Do not overwrite the baseline, silently replace a workload, omit refusals, or re
| Field | Recorded baseline | Candidate — agent fills |
|---|---|---|
| Source | `bbdbfe9045e8a85f8ea471529ea739af6cade77f`, version 0.50.0 | — |
| Source modifications | None to implementation; analysis/evidence docs only | — |
| Server SHA-256 | `27e0a0df5b77102ec79c23279da64e722bffd440c604ad6d03ff66c2f6398ad3` | — |
| CLI SHA-256 | `894054128495b764bb966e7b923e08267e57aea83fdc611fad4b4ed7a66b51e3` | — |
| Build | release, locked dependencies, workspace LTO enabled | — |
| Corpus | OpenTitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97` | — |
| Modified corpus inputs | Three existing files, listed/hashed in `metadata.json` | — |
| Host / OS | M1 Max; macOS 27.0 `26A5425a` | — |
| Date / zone | 2026-09-07, America/Chicago | — |
| Load, standard phases | 1-minute samples 2.92–4.59 | — |
| Guard | 8 GiB / 1800 s; zero kills in retained runs | — |
| Harness | `tools/perf` at baseline HEAD, supplementary probes in evidence README | — |
| Warmth / scope / capabilities | Warm workspace, lazy client unless metric says otherwise | — |
| Raw evidence | `take5-baseline/*.jsonl`, `metadata.json` | — |
| Source | `bbdbfe9045e8a85f8ea471529ea739af6cade77f`, version 0.50.0 | **P0 (§60.0): same binaries.** Tree at `9c75b7a4e517bdf91151b85814ecbb43e0d8679d` plus the uncommitted P0 working tree; no Rust changed |
| Source modifications | None to implementation; analysis/evidence docs only | None to implementation; `tools/perf/*` and docs only |
| Server SHA-256 | `27e0a0df5b77102ec79c23279da64e722bffd440c604ad6d03ff66c2f6398ad3` | `27e0a0df5b77102ec79c23279da64e722bffd440c604ad6d03ff66c2f6398ad3` — identical, verified before timing; **no rebuild** |
| CLI SHA-256 | `894054128495b764bb966e7b923e08267e57aea83fdc611fad4b4ed7a66b51e3` | `894054128495b764bb966e7b923e08267e57aea83fdc611fad4b4ed7a66b51e3` — identical |
| Build | release, locked dependencies, workspace LTO enabled | unchanged artifacts; no `cargo` command ran in this round |
| Corpus | OpenTitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97` | same |
| Modified corpus inputs | Three existing files, listed/hashed in `metadata.json` | same three; `git status --porcelain` identical after all 16 timed runs |
| Host / OS | M1 Max; macOS 27.0 `26A5425a` | same host |
| Date / zone | 2026-09-07, America/Chicago | 2026-09-07, America/Chicago |
| Load, standard phases | 1-minute samples 2.92–4.59 | 1-minute samples **2.92–5.21**, recorded before and after every phase |
| Guard | 8 GiB / 1800 s; zero kills in retained runs | 8 GiB / 1800 s on every phase, `lucisv` run and sweep; **zero kills** |
| Harness | `tools/perf` at baseline HEAD, supplementary probes in evidence README | **`tools/perf` in the working tree of §60.0, uncommitted** — schema 2; the two supplemental probes promoted to the `offerkinds` / `offerqueue` phases; the CLI probe re-run as a scratch script |
| Warmth / scope / capabilities | Warm workspace, lazy client unless metric says otherwise | same, and the shape is now **in every row** (`client`: `resolveSupport` / `applyEdit` / `createFiles`); `execute` is the only phase advertising `applyEdit` + `createFiles` |
| Raw evidence | `take5-baseline/*.jsonl`, `metadata.json` | `~/.cache/lucisv-perf/take5-p0/{results.jsonl,results-scan2.jsonl,cli-results.jsonl,runs.jsonl,logs/}` |
Before timing, record the exact revision/diff, binaries, compiler, machine, corpus hashes, enabled rules/settings, client capabilities and open-buffer set. Build first and stop all builds before measurements. Keep reference/candidate caches separate; alternate run order. Record actual commands and whether each trial is a new process. Three samples are the historical comparison minimum; for a close decision use at least three sessions and 20 measured requests per session, keep first requests separate and record the full distributions. Do not derive p95/p99 from the three-repeat baseline.
@@ -31,7 +31,7 @@ The order follows the plan. Later stages are conditional on the preceding measur
| Stage | Work | Depends on | Owner / commit | Status | Evidence and decision |
|---|---|---|---|---|---|
| P0 | Harness status/units/command execution/cold-cache corrections | — | — | Not started | — |
| P0 | Harness status/units/command execution/cold-cache corrections | — | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | `docs/features/perf5-p0/README.md`; experiment `P0-2026-09-07` below. Schema 2 shipped; `execute` phase measures the extract/inline commands for the first time; cold sweep tries verified at 0 hits, warm at 30; baseline reproduced on the unchanged binary |
| P1a | Gate lint/fence/config by requested kinds; avoid fence work without fixes | P0 | — | Not started | — |
| P1b | Shared parsed selectors; revision-bound fence reuse; invalidate any additional cache correctly | P1a | — | Not started | — |
| P1c | Engine-owned lightweight ports/import offers | Reprofile P1b | — | Not started | — |
@@ -48,76 +48,228 @@ The order follows the plan. Later stages are conditional on the preceding measur
Ordinary latency cells are **first / min–max of three repeats, milliseconds**. Fresh-session rows instead show all-session range. Baseline raw row names below make the comparison auditable. Fill candidate raw samples, median/distribution and counts in an experiment entry; this table is the readable overview. Use paired reference/candidate medians for improvement: `100 × (reference − candidate) / reference`. A cross-day comparison is context only.
**P0 note.** P0 changed no production code, so its "candidate" is the *same
binary re-measured with the corrected harness*. Those cells are marked
**REF** and are the reference P1+ must be compared against; their "paired
change" is the reference-against-baseline agreement check, never an
improvement claim. Baseline cells are untouched.
| Metric / baseline source | Baseline | Proposed goal or guardrail | Candidate | Paired change | Verdict |
|---|---:|---|---|---|---|
| Pinmux comment, lazy all families (`offer-breakdown`) | 328.41 / 296.78–311.73 ms; 0 actions | Repeated <16 ms; first-after-edit separate | — | — | — |
| Pinmux comment, `only: []` | 78.88 / 79.43–81.62 ms; 0 actions | Return near transport floor; no lint/parse | — | — | — |
| Pinmux comment, quickfix only | 79.54 / 79.73–80.06 ms; 0 actions | Avoid repeated lint/fence work safely | — | — | — |
| Pinmux comment → queued definition (`offer-queue`) | 300.66–304.11 ms follower, 3 pipelines | Repeated follower <16 ms if no other blocker | — | — | — |
| `tb.sv` comment, lazy (`codeaction`) | 6.15 / 3.22–3.50 ms; 0 actions | Repeated <5 ms; no added parse | — | — | — |
| `aes` lazy offer (`codeaction`) | 12.39 / 8.15–9.11 ms; 1 action | Repeated <5 ms | — | — | — |
| `aes_reg_top` lazy offer (`codeaction`) | 32.81 / 22.45–25.09 ms; 2 actions | Repeated <10 ms | — | — | — |
| `aes_reg_top` ports-only offer (`offer-breakdown`) | 21.72 / 21.55–21.78 ms; 0 port actions | Remove throwaway edit computation | — | — | — |
| `state_q` tail rename (`tailrename`) | 821.59 / 789.50–809.83 ms; 2 files | At least 2× faster; stretch <200 ms | — | — | — |
| Ordinary `aes` rename (`rename`) | 168.67 / 139.34–140.35 ms; 9 files | No regression; exact edit/warning parity | — | — | — |
| Definition behind ordinary rename (`blockers`) | 145.99–168.79 ms, 3 pipelines | Falls with rename work | — | — | — |
| Connect missing ports resolve (`refactor`) | 170.77 / 164.79–165.82 ms; 1 file | Measure collateral benefit; exact edit parity | — | — | — |
| Expand wildcard resolve (`refactor`) | 73.02 / 70.35–70.73 ms; 1 file, 32 connections | No lost connections/refusals | — | — | — |
| Eager 128-fan-out offer (`codeaction`) | 518.32 / 495.60–499.69 ms | Compatibility/perf guardrail; not first priority | — | — | — |
| Cold workspace scan (`scan`, 3 fresh sessions) | 2830.30–2853.06 ms; mean 2843.00 | Investigation goal <2300 ms | — | — | — |
| Warm workspace scan (`scan`, 3 fresh sessions) | 1322.24–1344.03 ms; mean 1332.41 | Investigation goal <1000 ms | — | — | — |
| Cold idle RSS (`rss`, 3 fresh sessions) | 528.0–530.9 MiB | Investigate ≥15% reduction; counts unchanged | — | — | — |
| Warm idle RSS (`rss`, 3 fresh sessions) | 566.4–573.8 MiB | Investigate ≥15% reduction; measure peak too | — | — | — |
| Index store allocated size (`rss`, `du -sk`) | 44.34 MiB | Record codec/version and contents | — | — | — |
| Pinmux open → definition (`didopen`, 3 fresh sessions) | 128.13–129.96 ms | Preserve §46 benefit | — | — | — |
| `tb.sv` dirty-buffer folding barrier (`flush`) | 1.05 / 0.65–0.72 ms | No material regression | — | — | — |
| Diagnostics publication (`diagnostics`) | 158.02 / 155.95–157.62 ms | Preserve debounce/burst coalescing | — | — | — |
| Unblocked definition (`nav`) | 0.365 / 0.048–0.084 ms; 1 location | Transport-sensitive regression control | — | — | — |
| Transport floor (`baseline`) | 0.240 / 0.066–0.070 ms | Record contemporaneous noise | — | — | — |
| CLI default, hw/ip | 0.59 / 0.40–0.40 s; 445 findings | First trial outlier; compare paired repeats | — | — | — |
| CLI all-style, hw/ip | 0.58 / 0.56–0.58 s; mean 0.573 s; 7751 findings | Retain all findings | — | — | — |
| CLI all-style minus unused-import, attribution only | 0.44 / 0.44–0.47 s; mean 0.450 s; 7734 findings | Save ≥half of 123 ms increment with rule enabled | — | — | — |
| CLI all-style peak RSS | 208.4 MiB max of 3 | No material memory increase | — | — | — |
| Format check independently cold, hw/ip | 0.67 / 0.59–0.68 s | 0 cache hits; unchanged outcomes | — | — | — |
| Format check warm, hw/ip | 0.69 / 0.61–0.63 s | 30 hits; unchanged outcomes | — | — | — |
| Pinmux comment, lazy all families (`offer-breakdown`) | 328.41 / 296.78–311.73 ms; 0 actions | Repeated <16 ms; first-after-edit separate | **REF (P0, same binary, `offerkinds`)** 333.89 / 307.35–312.97 ms; 0 actions | +4.1% on repeat medians | Agrees within tolerance; reference for P1 |
| Pinmux comment, `only: []` | 78.88 / 79.43–81.62 ms; 0 actions | Return near transport floor; no lint/parse | **REF** 81.72 / 82.27–84.11 ms; 0 actions | +1.7% | Agrees; reference for P1a |
| Pinmux comment, quickfix only | 79.54 / 79.73–80.06 ms; 0 actions | Avoid repeated lint/fence work safely | **REF** 82.76 / 82.50–85.06 ms; 0 actions | +5.5% | Agrees; reference for P1a |
| Pinmux comment → queued definition (`offer-queue`) | 300.66–304.11 ms follower, 3 pipelines | Repeated follower <16 ms if no other blocker | **REF (`offerqueue`)** follower 339.47 / 309.07 / 309.72 ms; leader 339.53 / 309.08 / 309.73; 3 pipelines, now in `leader_ms`/`follower_ms` | +2.0% on pipelines 2–3 | Agrees; leader and follower no longer share one `ms` array |
| `tb.sv` comment, lazy (`codeaction`) | 6.15 / 3.22–3.50 ms; 0 actions | Repeated <5 ms; no added parse | **REF** 5.53 / 3.80–4.79 ms; 0 actions | **+27.9%** — outside tolerance, see experiment entry | Disagrees; a ~4 ms row, neither number adjusted |
| `aes` lazy offer (`codeaction`) | 12.39 / 8.15–9.11 ms; 1 action | Repeated <5 ms | **REF** 13.87 / 7.33–9.66 ms; 1 action | −8.0% | Agrees (1–20 ms band) |
| `aes_reg_top` lazy offer (`codeaction`) | 32.81 / 22.45–25.09 ms; 2 actions | Repeated <10 ms | **REF** 30.64 / 22.72–24.42 ms; 2 actions | +1.0% | Agrees; reference for P1 |
| `aes_reg_top` ports-only offer (`offer-breakdown`) | 21.72 / 21.55–21.78 ms; 0 port actions | Remove throwaway edit computation | **REF (`offerkinds`)** 22.27 / 22.46–22.56 ms; 0 port actions | +3.3% | Agrees; reference for P1c |
| `state_q` tail rename (`tailrename`) | 821.59 / 789.50–809.83 ms; 2 files | At least 2× faster; stretch <200 ms | **REF** 813.44 / 778.77–782.13 ms; **5 edits / 2 files / 0 created**, fingerprint `b39defb21265…` | −1.4% | Agrees; reference for P2, now with an edit fingerprint to compare against |
| Ordinary `aes` rename (`rename`) | 168.67 / 139.34–140.35 ms; 9 files | No regression; exact edit/warning parity | **REF** 167.60 / 140.46–142.13 ms; **14 edits / 9 files / 0 created**, fingerprint `fa7e31c78382…` | +1.2% | Agrees; reference for P2 |
| Definition behind ordinary rename (`blockers`) | 145.99–168.79 ms, 3 pipelines | Falls with rename work | **REF** 163.43 / 161.55 / 161.11 ms, 3 pipelines (now `follower_ms.definition`) | inside the baseline range | Agrees |
| Connect missing ports resolve (`refactor`) | 170.77 / 164.79–165.82 ms; 1 file | Measure collateral benefit; exact edit parity | **REF** 171.37 / 165.77–167.45 ms; 1 file | +0.4% | Agrees |
| Expand wildcard resolve (`refactor`) | 73.02 / 70.35–70.73 ms; 1 file, 32 connections | No lost connections/refusals | **REF** 73.61 / 71.67–73.01 ms; 1 file, 32 connections | +2.2% | Agrees |
| Eager 128-fan-out offer (`codeaction`) | 518.32 / 495.60–499.69 ms | Compatibility/perf guardrail; not first priority | **REF** 523.16 / 495.13–496.77 ms; 2 actions | +0.1% | Agrees |
| Extract command actually executed (`execute`, **new**) | not measured — take 4's `extract-module resolve` rows are invalid | Measure the command, not a refusal | **REF** `lucisv.extractModule` at `aes.sv` 220:0–222:53: **257.33 / 245.05–247.00 ms** executeCommand→applyEdit; 2 edits / 2 files / **1 created**; `deliver_ms` 0.015–0.033; status `capture`; fingerprint `090e92e7736e…` | new row | The gap the tracker's work-count table named is closed |
| Inline command actually executed (`execute`, **new**) | not measured | Measure the command, not a refusal | `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused** (`generate` construct); 6.58 / 5.87–6.20 ms. Not a timing of an inline | new row | Refusal recorded as `refused`; **not quotable** as an inline cost |
| Extract offered at the inline cursor, refused (`execute`, **new**) | not measured | — | `lucisv.extractModule` at `aes_wrap.sv` 66:2 refused after **817.37 / 793.77–809.07 ms** | new row | A second ~800 ms user-command path; filed as a finding, not fixed |
| Cold workspace scan (`scan`, 3 fresh sessions) | 2830.30–2853.06 ms; mean 2843.00 | Investigation goal <2300 ms | **REF** 2860.12–2868.45 ms; mean 2863.85 | +0.7% on means | Agrees |
| Warm workspace scan (`scan`, 3 fresh sessions) | 1322.24–1344.03 ms; mean 1332.41 | Investigation goal <1000 ms | **REF** 1346.02–1352.80 ms; mean 1348.94 | +1.2% on means | Agrees |
| First useful answer during the scan (`scan`, **new**, 3 fresh sessions) | not measured | Stay responsive during a scan (P4) | **REF** cold **84.42–85.87 ms**, warm **206.12–218.72 ms**; 1 location in every session | new row | Warm is 2.5× *slower* than cold to first answer — carried to P4a |
| Cold idle RSS (`rss`, 3 fresh sessions) | 528.0–530.9 MiB | Investigate ≥15% reduction; counts unchanged | **REF** 526.7 / 530.2 / 535.2 MiB (`rss_kib`, no longer in `ms`) | +0.8% on the maximum | Agrees |
| Warm idle RSS (`rss`, 3 fresh sessions) | 566.4–573.8 MiB | Investigate ≥15% reduction; measure peak too | **REF** 575.0 / 572.5 / 575.6 MiB | +0.3% on the maximum | Agrees |
| Peak RSS across the scan (`rss`, **new**) | not measured | Measure peak, not only idle | **REF** cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — **equal to idle to the KiB in all six sessions** (`ps -o rss=` at 50 ms) | new row | The resident set rises monotonically; there is no transient above idle on this workload |
| Index store allocated size (`rss`, `du -sk`) | 44.34 MiB | Record codec/version and contents | **REF** 45 404 KiB = **44.34 MiB** (`store_kib`) | 0.0% | Identical |
| Pinmux open → definition (`didopen`, 3 fresh sessions) | 128.13–129.96 ms | Preserve §46 benefit | **REF** 119.01–131.85 ms | −3.8% on medians | Agrees; §46's fix intact |
| `tb.sv` dirty-buffer folding barrier (`flush`) | 1.05 / 0.65–0.72 ms | No material regression | **REF** 1.90 / 0.93–1.01 ms | **+35.5%** — outside tolerance, see experiment entry | Disagrees; a ~1 ms row, neither number adjusted |
| Diagnostics publication (`diagnostics`) | 158.02 / 155.95–157.62 ms | Preserve debounce/burst coalescing | **REF** 156.72 / 152.74–160.55 ms | +1.6% | Agrees |
| Unblocked definition (`nav`) | 0.365 / 0.048–0.084 ms; 1 location | Transport-sensitive regression control | **REF** 0.528 / 0.145–0.206 ms; 1 location | +132% but **sub-millisecond: not read** | Not read, per the round's own rule |
| Transport floor (`baseline`) | 0.240 / 0.066–0.070 ms | Record contemporaneous noise | **REF** 0.207 / 0.061–0.102 ms; `status: error` with `expected_status: error` (an unknown method, rejected without work) | +10.6% but **sub-millisecond: not read** | Not read; the row's rejection is now explicit |
| CLI default, hw/ip | 0.59 / 0.40–0.40 s; 445 findings | First trial outlier; compare paired repeats | **REF** 0.39 / 0.38–0.39 s; 445 findings; stdout sha256 **identical to baseline** | −3.0% on repeats (baseline's first trial excluded as the owner flagged) | Agrees on repeats; outcome byte-identical |
| CLI all-style, hw/ip | 0.58 / 0.56–0.58 s; mean 0.573 s; 7751 findings | Retain all findings | **REF** 0.58 / 0.59–0.59 s; mean **0.587 s**; 7751 findings; stdout sha256 identical | +2.4% on means | Agrees; reference for P3 |
| CLI all-style minus unused-import, attribution only | 0.44 / 0.44–0.47 s; mean 0.450 s; 7734 findings | Save ≥half of 123 ms increment with rule enabled | **REF** 0.46 / 0.43–0.46 s; mean **0.450 s**; 7734 findings; stdout sha256 identical | 0.0% on means; the increment reproduces at **137 ms (23.3% of all-style)** against the baseline's 123 ms (21.5%) | Agrees; P3's target is ≥half of the increment measured on its own reference |
| CLI all-style peak RSS | 208.4 MiB max of 3 | No material memory increase | **REF** 217.0 MiB max of 3 | +4.1% | Agrees |
| Format check independently cold, hw/ip | 0.67 / 0.59–0.68 s | 0 cache hits; unchanged outcomes | **REF** 0.67 / 0.61–0.70 s; **0 cache hits in all three tries**; 1772 would reformat, 30 unchanged, 4 failed; stdout sha256 identical | +2.0% on means | Agrees, and cold is now provably cold |
| Format check warm, hw/ip | 0.69 / 0.61–0.63 s | 30 hits; unchanged outcomes | **REF** 0.67 / 0.65–0.66 s; **30 hits in all three tries**; same outcomes; stdout sha256 identical | +2.6% on means | Agrees |
## Work counts and gaps that must be filled before attributing gains
| Measurement | Baseline knowledge | Reference — agent fills | Candidate — agent fills |
|---|---|---|---|
| Additional parses per no-offer all-family action | 5 text-parse entry points confirmed in source; no runtime counter | — | — |
| Lint/config/fence time separately | About 80 ms combined on generated file; unseparated | — | — |
| Selector time by family and file size | Filtered ablations preserved in raw data | — | — |
| Tail rename selected paths / input bytes / selection reasons | Not measured; **2 output files is not input count** | — | — |
| Tail rename watched vs edited paths | Edited 2; watched unmeasured | — | — |
| Tail rename index / parse / analysis / resolution / verification stage times | Not measured | — | — |
| Ordinary rename selected bytes / stages | Edited 9; other counts unmeasured | — | — |
| Ambiguous-use all-sources fallback frequency | Not measured | — | — |
| Per-file parses for CLI census and lint | Multiple paths confirmed; runtime counts unmeasured | — | — |
| CLI package-census vs unused-import body time | Combined 123 ms wall increment; stages unseparated | — | — |
| Startup discovery / hash / decode / merge / candidates / includes / compact | Only combined scan time measured | — | — |
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | — | — |
| First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | — | — |
| Actual inline/extract command time and applyEdit payload | Not measured; existing resolve rows invalid for this purpose | — | — |
| First offer after didChange vs repeated unchanged offer | Separate distribution needed | — | — |
| Additional parses per no-offer all-family action | 5 text-parse entry points confirmed in source; no runtime counter | Still no runtime counter — P0 is harness-only and adds no production instrumentation. The wire-side attribution is reproduced (`offerkinds`): 82.80 ms shared base at the pinmux cursor, +52.7 to +57.6 ms for any one selector family | — |
| Lint/config/fence time separately | About 80 ms combined on generated file; unseparated | Reproduced but still unseparated: pinmux `only: []` 82.80 ms, quickfix 84.13 ms. Separating them needs P1's counters | — |
| Selector time by family and file size | Filtered ablations preserved in raw data | **Promoted to the committed `offerkinds` phase**: 7 families × 5 cursors × 4 requests, result counts in every row. All-family repeat medians by cursor — tb 1.54 / aes-reg-instance 23.51 / aes-core 10.42 / spi 14.43 / pinmux 309.60 ms. Pinmux by family: `[]` 82.80, quickfix 84.13, extract 140.42, inline 136.37, ports 137.97, organizeImports 135.45 | — |
| Tail rename selected paths / input bytes / selection reasons | Not measured; **2 output files is not input count** | Still not measured (needs P2a's server-side instrumentation). What P0 adds is the **output** side, exactly: 5 edits / 2 files / 0 created, fingerprint `b39defb21265…` | — |
| Tail rename watched vs edited paths | Edited 2; watched unmeasured | Edited 2, confirmed by `files`; watched still unmeasured — P2a | — |
| Tail rename index / parse / analysis / resolution / verification stage times | Not measured | Not measured — P2a | — |
| Ordinary rename selected bytes / stages | Edited 9; other counts unmeasured | Edited 9 confirmed (14 edits, fingerprint `fa7e31c78382…`); stages unmeasured — P2a | — |
| Ambiguous-use all-sources fallback frequency | Not measured | Not measured — P2a | — |
| Per-file parses for CLI census and lint | Multiple paths confirmed; runtime counts unmeasured | Not measured — P3 | — |
| CLI package-census vs unused-import body time | Combined 123 ms wall increment; stages unseparated | Increment reproduced on the same binary at **137 ms, 23.3% of all-style** (means 0.587 vs 0.450 s, three trials, alternating order, stdout hashes identical to baseline). Stages still unseparated — P3 | — |
| Startup discovery / hash / decode / merge / candidates / includes / compact | Only combined scan time measured | Still only combined — P4a. P0 adds the scan's *other* half: first useful answer, cold **84.42–85.87 ms** vs warm **206.12–218.72 ms**, and the settle of those same perturbed sessions (cold 2855–2877, warm 1340–1358 ms) | — |
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — equal to idle to the KiB in all six sessions, i.e. no transient above idle. Refactoring peak still unmeasured — P2a | — |
| First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | **First useful response measured** (above), each session a fresh process, kept in separate sessions from the settled rows so the settled series stays comparable. Open buffers 1 / 10 / 100 not measured — P4a | — |
| Actual inline/extract command time and applyEdit payload | Not measured; existing resolve rows invalid for this purpose | **Measured, phase `execute`.** `lucisv.extractModule` (`aes.sv` 220:0–222:53): 257.33 / 245.05–247.00 ms from `executeCommand` to `workspace/applyEdit`, payload 2 edits / 2 files / 1 created, label `lucisv: lucisv.extractModule`, fingerprint `090e92e7736e…`, declined with `applied: false` (status `capture`), delivery half 0.015–0.033 ms. `lucisv.inlineModule` (`aes_wrap.sv` 66:2) **refused** (`generate` construct) in 6.58 / 5.87–6.20 ms; the extract offer at that same cursor **refused** after 817.37 / 793.77–809.07 ms. Take 4's `*-module resolve` rows are removed, not reinterpreted | — |
| First offer after didChange vs repeated unchanged offer | Separate distribution needed | Not measured. Every row separates the *first request of a session* from its repeats, but no row yet issues a `didChange` and then re-offers — P1's measurement | — |
## Correctness and integration gates
P0 changed no production code, so most of these gates have nothing to test at
this stage; each says so rather than being left ambiguous.
| Gate | Required evidence | Candidate result / log |
|---|---|---|
| Action parity | Titles/kinds/counts/commands/data or edits/refusals; empty/prefix filters; cursor and selection | — |
| Reuse freshness | didChange, unsaved overlays, config/options/tab width/waiver changes, index generation, closed files changed on disk | — |
| Fence parity | All aliases, class/statement fences, malformed source, raw scan backstop, insertions and multi-edit fixes | — |
| Refactor whole-scope parity | Exact edits, warnings, refusal sentences; old/new common names, unresolved and ambiguous uses | — |
| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | — |
| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | — |
| CLI output | Compare full findings/fixes/waivers/exit codes, not just counts; disabled-rule run stays attribution-only | — |
| Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | — |
| Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | — |
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | — |
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | — |
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | — |
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | — |
| Action parity | Titles/kinds/counts/commands/data or edits/refusals; empty/prefix filters; cursor and selection | **P0: recorded, not yet a comparison.** Every offer row now carries `titles`, the shape of each offer (`edit`/`command`/`data`), `result_count` and the `only` filter it asked with; `offerkinds` walks 7 filters at 5 cursors. This is the reference P1 must match |
| Reuse freshness | didChange, unsaved overlays, config/options/tab width/waiver changes, index generation, closed files changed on disk | Not applicable at P0 — nothing is reused or cached in production |
| Fence parity | All aliases, class/statement fences, malformed source, raw scan backstop, insertions and multi-edit fixes | Not applicable at P0 |
| Refactor whole-scope parity | Exact edits, warnings, refusal sentences; old/new common names, unresolved and ambiguous uses | **P0 supplies the instrument**: `fingerprint` (sha256 over sorted edits + created paths + warnings) and `edits`/`files`/`created` on every edit-bearing row, plus refusal sentences captured verbatim in `message`. First reference values recorded (tail rename, `aes` rename, extraction) |
| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | Not applicable at P0 — no selector shared or narrowed |
| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | Not applicable at P0 — the engine's verifiers are untouched |
| CLI output | Compare full findings/fixes/waivers/exit codes, not just counts; disabled-rule run stays attribution-only | **Passed.** stdout sha256 of all five configurations byte-identical to the baseline's; exit codes 1 (lint findings) / 2 (four pre-existing format failures) as before; the `--ignore unused-import` run is recorded as attribution only |
| Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | Not applicable at P0. Store size unchanged at 44.34 MiB and the scan's own `$/progress` end messages recorded per cell (`124 → 3976 files indexed, 3975 from cache, 3 skipped` warm) |
| Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | Not applicable at P0 |
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB |
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean |
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | Not applicable at P0 (no Rust). No benchmark overlapped a build: the one competing `cargo build` (a CI runner outside this tree) was waited out before the first timed phase |
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded |
## Experiment record — P0-2026-09-07 (stage P0)
- **Experiment ID / stage / date / owner:** `P0-2026-09-07` / P0 (TODO §60.0)
/ 2026-09-07, America/Chicago / dev agent (Opus).
- **Hypothesis and exact expected work reduction:** none — P0 changes no
production code. The hypothesis is about the *instrument*: that four named
defects (command-bearing offers timed as resolves, responses discarded by
`Session.ms`, RSS in a field called `ms`, the format cache reset once per
cold cell instead of once per cold try) made specific rows mean something
other than their names, and that fixing them leaves the surviving rows
agreeing with the owner's baseline within tolerance.
- **Reference commit, candidate commit or diff hash, binary hashes:** tree at
`9c75b7a4e517bdf91151b85814ecbb43e0d8679d` plus the uncommitted §60.0
working tree (`tools/perf/*` and docs only). Binaries **unchanged and
unrebuilt**: server `27e0a0df5b77102ec79c23279da64e722bffd440c604ad6d03ff66c2f6398ad3`,
CLI `894054128495b764bb966e7b923e08267e57aea83fdc611fad4b4ed7a66b51e3`,
both verified against `take5-baseline/metadata.json` before any timing.
- **Files changed / API contracts amended / topology references:**
`tools/perf/{schema.py (new), phases_p0.py (new), lspclient.py, harness.py,
bench.py, phases_new.py, sweep.sh, sweeptable.py, README.md}`;
`docs/features/perf5-p0/README.md` (new); this file; a note in
`docs/perf/README.md`; TODO §60.0's dev lines. **No production Rust, no
`topo.md` edge.** The only new contract is the record schema, stated in
`tools/perf/README.md` and enforced by `harness.record()` and
`schema.quotable()`.
- **Workload, corpus/input hashes, open files, cursor/range, rules, client
capabilities:** OpenTitan `0098135264`, the same three pre-existing modified
files (hashes in `take5-baseline/metadata.json`), unchanged after all 16
timed runs. Cursors and selections are `tools/perf/sites.py`'s, resolved
from file text at run time: `aes.sv` 220:0–222:53 (extract selection),
`aes_wrap.sv` 66:2 (inline), pinmux/spi/aes-core/tb comments, the five
fan-out cursors, `entropy_src_main_sm.sv` `state_q`. Client shape is in
every row; `execute` is the only session advertising `workspace.applyEdit`
and `resourceOperations: ["create","rename","delete"]`.
- **Machine, compiler/profile, threads, load before/after, competing
activity:** M1 Max, macOS 27.0 `26A5425a`, release+LTO artifacts, default
worker count. Load 2.92–5.21, recorded before and after every phase. A CI
runner's `cargo build --release -p lucisv` (an `act` host executor in
`~/.cache/act`, not this tree) was at 100% of a core at session start; **no
timing was taken until it exited**. The desktop session ran throughout, as
in take 4 and the baseline.
- **Commands, cache reset/prime steps, trial ordering and fresh-session
count:** 15 guarded `bench.py <phase>` runs (`baseline codeaction offerkinds
offerqueue refactor execute tailrename rename blockers didopen scan rss
flush diagnostics nav`, `--tries 3`), then `scan` once more (below), then
the paired CLI script. Every child through `tools/guard.sh -m 8 -t 1800`.
Index caches under a scratch `--storage`; the formatter cache under a
scratch `--cache-dir` deleted before each cold try. CLI configuration order
alternated per trial; three trials. Fresh-process rows: `scan` (3 per cell),
`rss` (3 per cell), `didopen` (3), `blockers` (3 per leader).
- **Raw evidence path, explicit units, full sample arrays:**
`~/.cache/lucisv-perf/take5-p0/` — `results.jsonl` (114 rows, schema 2),
`results-scan2.jsonl` (the second `scan` run),
`results-execute2.jsonl` (the second `execute` run), `cli-results.jsonl`,
`runs.jsonl` (per-phase command, exit, load before/after, corpus check),
`logs/`. Units are in every row (`units`); latency is `ms` only, memory is
`rss_kib` / `peak_rss_kib`, store size is `store_kib`, CLI is `s`.
- **Reference first / repeat median / range; candidate first / repeat median /
range:** the Before/after table above carries all of them; the arrays are in
`results.jsonl`. P0 has no candidate distinct from the reference.
- **Work counts: reads, parses, analyzed/selected/watched/edited files and
bytes:** no production counters (P0 adds none). Output-side counts are now
in the rows: tail rename 5 edits / 2 files / 0 created; `aes` rename 14 / 9
/ 0; extract command 2 / 2 / **1**; every offer row carries its
`result_count` and the shape of each offer (`edit` / `command` / `data`).
- **Result/status/count/fingerprint comparisons, warnings and refusal
checks:** 114 rows — 110 `ok`, 1 `capture` (the extraction's declined
`applyEdit`), 2 `refused` (both engine sentences at `aes_wrap.sv` 66:2),
1 `error` (the transport floor, carrying `expected_status: "error"`).
Result counts match the baseline everywhere they are comparable. The five
CLI configurations' **stdout sha256 are byte-identical to the baseline's**.
Fingerprints recorded for the tail rename (`b39defb21265…`), the `aes`
rename (`fa7e31c78382…`) and the extraction (`090e92e7736e…`); the baseline
has none to compare against, so these are the first reference values. The
`execute` phase was run a second time (after a cosmetic fix to a refused
row's `note` and `fingerprint`) and reproduced within 1.5% — with the
**identical** extraction fingerprint `090e92e7736e…`, which is the first
independent check that the fingerprint is stable across runs.
- **Idle RSS / peak RSS / cache size / guard outcomes:** idle cold 526.7 /
530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB; peak equal to idle to
the KiB in all six sessions; store 44.34 MiB (unchanged); CLI peak 190.3
(default) / 217.0 (all-style) / 191.4 (all-style minus the rule) / 246.5
(format cold) / 217.3 (format warm) MiB. **Zero guard kills.**
- **Target achieved or missed; paired improvement and variability:** P0's
targets are the plan's four acceptance criteria, all met: a deliberately
rejected request is recorded as an error (the transport floor, and both
engine refusals); the inline/extract rows show a command and either an
`applyEdit` payload or a refusal sentence; cold formatter tries report
**0 / 0 / 0** cache hits and warm **30 / 30 / 30** on `hw/ip`; RSS and peak
RSS have their own fields with explicit units. **No performance claim is
made — the binary did not change.**
- **Where the reference disagrees with the baseline beyond tolerance
(neither number adjusted):**
- `tb.sv` comment, lazy: repeat median 4.46 ms against the baseline's 3.49,
**+27.9%**, outside the ±20% band a 1–20 ms row gets. A ~4 ms row on a
desktop machine; the same cursor's `offerkinds` reading (1.54 ms at a
different comment on the same file, with a `context` the phase builds
slightly differently) shows how sensitive this row is. Flagged for QA to
re-take.
- `didChange` folding barrier: 0.96 ms against 0.71, **+35.5%**. A ~1 ms
row, above the round's 0.5 ms floor but only just.
- `nav definition` (+132%) and the transport floor (+10.6%) are both
**sub-millisecond and are not read**, per take 4 §9's rule that nothing
under 0.5 ms is a reading. Recorded, not treated as movement.
- `format-cold` peak RSS 246.5 MiB against the baseline's 202.2 (+21.9%).
Not a tracker cell; recorded here because it is the one memory number
that moved by more than a few percent.
- Everything else agrees within ±5.5%.
- **Correctness tests and logs:** `python3 -m py_compile tools/perf/*.py` and
`bash -n tools/perf/*.sh` clean. No Rust changed, so the cargo gates were
not run (and could not be, mid-round). The corpus check is the correctness
gate that mattered: `git -C ~/repo/opentitan status --porcelain` after every
phase and every CLI trial, always the same three files, plus a direct check
that `aes_extracted.sv` — the file the extraction's own warning says its
edit would create — **does not exist**.
- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:**
the instrument now says what it measures, and the two rows take 4 could not
measure are measured. Two findings came out of the new `execute` phase:
the extraction costs **~250 ms** of edit computation (delivery is 0.02 ms,
so it is all engine), and the *extract* offer at `aes_wrap.sv` 66:2 spends
**793–817 ms** to produce a refusal — a second ~800 ms user-command path
beside the tail rename, and one that returns nothing. A third observation
for P4a: the first useful answer during a **cold** scan arrives in 85 ms,
while during a **warm** scan it takes 210 ms. Rejected alternatives: wrapping
the server in `/usr/bin/time -l` for a kernel peak-RSS figure (the guard
already owns that slot, so a 50 ms `ps` poll is used and the row says so);
folding the CLI `--ignore unused-import` cell into `sweep.sh` (it would
change the committed sweep's cell set for all five trees, so the paired CLI
experiment stayed a scratch script as the owner's was); measuring the
first-useful-answer inside the same sessions as the settled scan (serving a
request perturbs the scan and would have broken comparability with take 4).
- **Decision: retain / revise / reject / defer; next stage justified by
evidence:** **retain.** P1 is justified and unblocked: it now has a
same-binary reference for every row it will move, measured by the instrument
it will be judged with, plus the family attribution (82.80 ms shared base
at the pinmux cursor, +52.7 to +57.6 ms per selector family) it must reduce.
- **QA result and lead review link:** pending — `docs/features/perf5-p0/README.md`.
## Experiment record — copy for every stage or rejected attempt
+78 -5
View File
@@ -6,17 +6,21 @@ take 2's *prose*. This directory is the fix. Everything a performance round
needs is here, in Python 3 with **no third-party packages**, so it runs from a
clean checkout given an opentitan path and a pair of binaries.
Written for take 4 (`docs/performance_take4.md`, TODO §58). Take 5 reuses it.
Written for take 4 (`docs/performance_take4.md`, TODO §58). Take 5 reuses it,
and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see
[the record schema](#the-record-schema-schema-2) below.
| File | What it is |
|---|---|
| `lspclient.py` | framed JSON-RPC over a `lucisv-server` child process: the `workspace/configuration` pull answered per session, per-session client capabilities (with and without `codeAction.resolveSupport`), `storagePath` cache control, `window/logMessage` capture including a `--verbose` server's own `timing:` lines |
| `lspclient.py` | framed JSON-RPC over a `lucisv-server` child process: the `workspace/configuration` pull answered per session, per-session client capabilities (with and without `codeAction.resolveSupport`, with and without `workspace.applyEdit`), `storagePath` cache control, `window/logMessage` capture including a `--verbose` server's own `timing:` lines, and `workspace/applyEdit` capture — timed, counted and declined |
| `sites.py` | every opentitan position a phase measures, named by the *text* it wants rather than a line number |
| `harness.py` | what every phase shares: the registry, the run's configuration, the session factory, the recorder |
| `schema.py` | what a `results.jsonl` row means, written into the row: the version, the units, the status vocabulary, the result count, the edit fingerprint |
| `harness.py` | what every phase shares: the registry, the run's configuration, the session factory, the recorder, `samples()` |
| `bench.py` | the command line, and the phases that reproduce take 3's tables |
| `phases_new.py` | the phases for what 0.44–0.49 added: the new offer sites, §49's surface, §46's `didOpen` fix, `moduleHierarchy`, index size and RSS |
| `phases_p0.py` | take 5 §P0's phases: `execute` (what an extract/inline command really costs), `offerkinds` (the `context.only` families), `offerqueue` (leader/follower), and `scan`'s first-useful-answer half |
| `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` |
| `sweeptable.py` | those logs → the document's §7 Markdown table |
| `sweeptable.py` | those logs → the document's §7 Markdown table, plus the format-cache hits each try reported |
| `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff |
## The rules every run obeys
@@ -69,7 +73,10 @@ apart in `results.jsonl`; run each phase once per binary.
| `completion` | §6d | the typed-prefix curve |
| `tailcompletion` | §6d | completion after an instance head and a `.` |
| `hierarchy` | §6 | `lucisv/moduleHierarchy`, the snapshot the DUT sidebar consumes |
| `rss` | §6 | server RSS after the workspace scan, and the index store's size on disk |
| `rss` | §6 | idle and peak server RSS after the workspace scan, and the index store's size on disk — `rss_kib` / `peak_rss_kib` / `store_kib`, never `ms` |
| `execute` | §P0 | the extract and inline **commands**, run for real: `workspace/executeCommand`, the `workspace/applyEdit` the server pushes back captured and declined, the edit counted and fingerprinted |
| `offerkinds` | §P0 | the seven `context.only` families at five cursors, four requests each, result counts beside every time |
| `offerqueue` | §P0 | the pinmux no-offer comment as leader, an `aes` definition as follower, in separate fields |
| `probe` | — | ad-hoc: `--probe FILE:LINE:CHAR` (0-based) prints what a cursor offers. This is how `sites.REFACTOR_SITES` was found |
## The CLI sweeps
@@ -79,11 +86,23 @@ tools/perf/sweep.sh ~/.cache/lucisv-baselines/lucisv-0.49.0 0.49.0 "$OT" "$SP/sw
python3 tools/perf/sweeptable.py "$SP/sweep" --labels 0.49.0,0.43.0,0.39.0
```
A sixth argument narrows the tree list (`… "$SP/sweep" 3 "hw/ip"`).
`sweep.sh` writes one log per (label, tree, command, cache state) holding the
three tries' `/usr/bin/time -l` blocks; `sweeptable.py` reads them all and
prints the table plus the summary line each run reported, so a timing that
moved because the *work* moved is not mistaken for a timing change.
**Cache warmth is per try, not per cell** (take 5 §P0). A cold try deletes the
scratch `--cache-dir` immediately before itself; a warm cell is primed by one
explicit *untimed* run, whose block sits in the log behind a
`--- prime (untimed, not a try) ---` marker and is counted nowhere. Before
this, the cache was deleted once for the whole cold cell, so tries 2 and 3 read
what try 1 had written and two of every three "cold" numbers were warm.
`sweeptable.py` therefore prints the `N files from cache` each try reported and
flags any cold try with a hit. Verified on `hw/ip` at 0.50.0: cold `0 / 0 / 0`,
warm `30 / 30 / 30`.
## The outcome diff
```sh
@@ -102,3 +121,57 @@ One JSON object per row: `phase`, `label`, `row`, `ms` (the try list, first
try first), and whatever else the phase knows — `n` (a result count, a file
count, a byte count), `titles`, `note`. Nothing in the document may quote a
number that is not in this file or in a `sweep.sh` / `outcomes.sh` log.
### The record schema (`schema` 2)
Take 4's rows carried no `schema` key. **A row without one is schema 1**; read
it with take 4's prose, where `rss.ms` held KiB, `offer-queue.ms` held a leader
and a follower rather than repeats, and a request the server *rejected* was
recorded as a fast success. Nothing was rewritten, so both versions live in one
file; `schema.py` is the vocabulary for new rows.
| Field | Meaning |
|---|---|
| `schema` | `2`. Absent means schema 1 — take 4's rows |
| `units` | what the row's values are counted in. `ms` means the `ms` list is **latency and nothing else**; a memory row says `KiB` and carries no `ms` at all |
| `status` | `ok`, `error`, `refused` or `capture` (below) |
| `message` | mandatory whenever `status` is not `ok`: the server's own sentence |
| `result_count` | how many things the answer carried, so a timing that moved because the *answer* moved is not read as a timing change |
| `client` | the capability shape that asked: `resolveSupport`, `applyEdit`, `createFiles`. The same cursor answers differently to each |
| `fresh_process` | whether each try was its own server (scan, `didOpen`, RSS, blockers) or a repeat inside one session |
| `edits` / `files` / `created` | what a `WorkspaceEdit` does: text edits, files touched, files created |
| `fingerprint` | sha256 over the sorted `(uri, start, end, newText)` edits, the sorted created paths and the sorted warnings — two runs' refactorings compared without copying corpus text out |
| `rss_kib` / `peak_rss_kib` / `store_kib` | idle resident set, the maximum of a 50 ms `ps -o rss=` poll across the scan, and `du -sk` of the index store |
| `leader_ms` / `follower_ms` | a pipelined pair, each in its own field |
| `settled_ms` / `first_answer_ms` | when the scan went quiet, and when the first useful answer arrived — separate numbers, and `scan` measures them in separate sessions so the settled series stays comparable with take 4's |
**The status vocabulary.**
- `ok` — the server answered.
- `error` — the request failed. Its time is the time of a failure, not of the
operation the row is named after.
- `refused` — the engine declined, in its own sentence (JSON-RPC
`RequestFailed`). A refusal is a correct answer to a wrong question, but it
is still not a measurement of the refactoring.
- `capture` — *this client* declined an edit the server pushed at it. The
corpus is read-only, so `execute` answers every `workspace/applyEdit` with
`applied: false` and a capture reason. The work was done and measured; only
the writing was refused, by us.
**No document may quote a row whose `status` is not `ok` or `capture`** — with
one exception, a row whose `expected_status` names the rejection it was built
to get. The transport floor (`$/lucisvNoSuchMethod`) is the only such row:
being rejected without work is the whole point of it. `schema.quotable(row)`
is that rule in code.
**Why `execute` exists.** An extract or inline offer carries a `command`, not
an `edit`. Take 4's `refactor` phase sent every offer without an `edit` to
`codeAction/resolve`; dispatch handed those to the ports resolver, which
rejects an offer without its data — so their tiny times measured a refusal.
`refactor` now records such an offer as belonging to `execute` and does not
time it; `execute` sends `workspace/executeCommand`, times the request up to
the `workspace/applyEdit` arriving (that instant is the end of the edit
computation), records the reply-to-response half separately as `deliver_ms`,
counts and fingerprints the pushed edit, and declines it. Nothing is written:
verified after each run with `git -C <opentitan> status --porcelain`, and by
the absence of any file an extraction said it would create.
+115 -75
View File
@@ -25,13 +25,15 @@ import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import harness # noqa: E402
import schema # noqa: E402
import sites # noqa: E402
from harness import ( # noqa: E402
ARGS, at, code_action_params, doc, phase, pos, record, result_count,
session, settled, tries,
ARGS, at, code_action_params, counts, doc, edit_of, fingerprint, phase,
pos, record, samples, session, settled,
)
import phases_new # noqa: E402,F401 — registers its own phases
import phases_p0 # noqa: E402,F401 — registers take 5 §P0's phases
# =========================================================================
@@ -43,12 +45,20 @@ import phases_new # noqa: E402,F401 — registers its own phases
def phase_baseline():
with session("workspace") as s:
init = s.initialize()
record(phase="baseline", row="initialize", ms=[init])
record(phase="baseline", row="initialize", ms=[init], result_count=1,
client=s.client_shape(), fresh_process=True)
s.did_open(sites.path(sites.TB))
s.wait_quiet(1.5)
s.take_notifications()
ms = tries(s, "$/lucisvNoSuchMethod", {}, 4)
record(phase="baseline", row="transport baseline ($/lucisvNoSuchMethod)", ms=ms)
got = samples(s, "$/lucisvNoSuchMethod", {}, 4)
# The floor is an unknown method: the server rejects it without doing
# any work, which is the whole point of the row. The rejection is
# recorded honestly as an error *and* named in `expected_status`, so
# the row stays quotable while a row that failed by accident does not.
record(phase="baseline", row="transport baseline ($/lucisvNoSuchMethod)",
client=s.client_shape(), expected_status="error",
note="an unknown method, rejected without work — by design",
**got.row())
@phase("verbose")
@@ -72,11 +82,11 @@ def phase_verbose():
params["range"] = {"start": params.pop("position"), "end": None}
params["range"]["end"] = params["range"]["start"]
params["context"] = {"diagnostics": []}
ms = tries(s, "textDocument/codeAction", params, 4)
got = samples(s, "textDocument/codeAction", params, 4)
server_ms = [t[1] for t in s.take_timings("textDocument/codeAction")]
record(phase="verbose", row=label, ms=ms,
record(phase="verbose", row=label,
note="verbose" if verbose else "quiet",
server_ms=server_ms)
server_ms=server_ms, client=s.client_shape(), **got.row())
# =========================================================================
@@ -111,7 +121,13 @@ def phase_scan():
and n["params"]["value"].get("kind") == "end"
]
note = " | ".join(ends[-2:])
record(phase="scan", row="%s, %s cache" % (scope, cache), ms=runs, note=note)
record(phase="scan", row="%s, %s cache" % (scope, cache), ms=runs,
settled_ms=runs, fresh_process=True, result_count=len(runs),
note=note + " | nothing in flight during the scan")
# The other half of §P0's split: when the *first useful answer* arrives,
# measured in its own fresh sessions so the settled series above stays
# comparable with take 4's.
phases_p0.first_useful_rows()
@phase("scopes")
@@ -131,21 +147,18 @@ def phase_scopes():
for name, method, extra in asks:
params = dict(at(sites.TB, " aes #(", 1, 2))
params.update(extra)
ms = tries(s, method, params)
_, message = s.request(method, params)
record(phase="scopes", row="%s @ %s" % (name, scope), ms=ms,
n=result_count(message))
ms = tries(s, "workspace/symbol", {"query": "aes"})
_, message = s.request("workspace/symbol", {"query": "aes"})
record(phase="scopes", row="workspace/symbol 'aes' @ %s" % scope, ms=ms,
n=result_count(message))
got = samples(s, method, params)
record(phase="scopes", row="%s @ %s" % (name, scope),
client=s.client_shape(), **got.row())
got = samples(s, "workspace/symbol", {"query": "aes"})
record(phase="scopes", row="workspace/symbol 'aes' @ %s" % scope,
client=s.client_shape(), **got.row())
hint = {"textDocument": doc(sites.TB),
"range": {"start": {"line": 0, "character": 0},
"end": {"line": 9999, "character": 0}}}
ms = tries(s, "textDocument/inlayHint", hint)
_, message = s.request("textDocument/inlayHint", hint)
record(phase="scopes", row="inlayHint @ %s" % scope, ms=ms,
n=result_count(message))
got = samples(s, "textDocument/inlayHint", hint)
record(phase="scopes", row="inlayHint @ %s" % scope,
client=s.client_shape(), **got.row())
# =========================================================================
@@ -184,9 +197,9 @@ def phase_nav():
for row, method, params in rows:
with session("workspace") as s:
settled(s)
ms = tries(s, method, params, ARGS.tries + 1)
_, message = s.request(method, params)
record(phase="nav", row=row, ms=ms, n=result_count(message), method=method)
got = samples(s, method, params, ARGS.tries + 1)
record(phase="nav", row=row, method=method, client=s.client_shape(),
**got.row())
@phase("flush")
@@ -195,11 +208,18 @@ def phase_flush():
with session("workspace") as s:
settled(s)
text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read()
runs = []
runs, statuses, last = [], [], {}
for version in range(2, 2 + ARGS.tries + 1):
s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version)
runs.append(s.ms("textDocument/foldingRange", {"textDocument": doc(sites.TB)}))
record(phase="flush", row="didChange flush (foldingRange barrier)", ms=runs)
got = samples(s, "textDocument/foldingRange",
{"textDocument": doc(sites.TB)}, 1)
runs.append(got.ms[0])
statuses.append(got.status)
last = got.last
status = schema.worst(statuses)
record(phase="flush", row="didChange flush (foldingRange barrier)", ms=runs,
status=status, message=None if status == "ok" else "a barrier failed",
result_count=schema.result_count(last), client=s.client_shape())
# =========================================================================
@@ -218,19 +238,21 @@ def phase_codeaction():
s.wait_quiet(0.6)
s.take_notifications()
params = code_action_params(relative, needle, occurrence, offset)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
offered = got.last.get("result") or []
record(phase="codeaction",
row="%s (fan-out %d), %s" % (label, fanout, "lazy" if lazy else "eager"),
ms=ms, n=result_count(message),
titles=[a.get("title") for a in (message.get("result") or [])])
titles=[a.get("title") for a in offered],
shapes=[phases_p0.shape_of(a) for a in offered],
client=s.client_shape(), file=relative,
position=params["range"]["start"], **got.row())
with session("workspace", resolve_support=lazy) as s:
settled(s)
params = code_action_params(sites.TB, " // ", 1, 2)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
record(phase="codeaction", row="comment line, %s" % ("lazy" if lazy else "eager"),
ms=ms, n=result_count(message))
client=s.client_shape(), file=sites.TB,
position=params["range"]["start"], **got.row())
@phase("portaction")
@@ -243,24 +265,15 @@ def phase_portaction():
s.wait_quiet(0.6)
s.take_notifications()
params = code_action_params(sites.AES_WRAP, " aes #(", 1, 2)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
offered = got.last.get("result") or []
record(phase="portaction",
row="aes_wrap.sv offer, %s" % ("lazy" if lazy else "eager"),
ms=ms, n=len(offered),
titles=[a.get("title") for a in offered],
has_edit=[("edit" in a) for a in offered])
shapes=[phases_p0.shape_of(a) for a in offered],
client=s.client_shape(), **got.row())
if lazy and offered:
resolves = [s.ms("codeAction/resolve", offered[0])
for _ in range(ARGS.tries + 1)]
_, resolved = s.request("codeAction/resolve", offered[0])
edit = (resolved.get("result") or {}).get("edit") or {}
files = edit.get("changes") or {u: 1 for u in
(c.get("textDocument", {}).get("uri")
for c in edit.get("documentChanges") or [])}
record(phase="portaction", row="aes_wrap.sv codeAction/resolve", ms=resolves,
n=len(files), titles=[(resolved.get("result") or {}).get("title")])
phases_new.resolve_rows(s, "portaction", "aes_wrap.sv", offered[:1])
# =========================================================================
@@ -273,15 +286,17 @@ def phase_rename():
with session("workspace") as s:
settled(s)
where = at(sites.TB, " aes #(", 1, 2)
ms = tries(s, "textDocument/prepareRename", where, ARGS.tries + 1)
_, message = s.request("textDocument/prepareRename", where)
record(phase="rename", row="prepareRename on aes", ms=ms,
note=json.dumps(message.get("result")))
got = samples(s, "textDocument/prepareRename", where, ARGS.tries + 1)
record(phase="rename", row="prepareRename on aes", client=s.client_shape(),
note=json.dumps(got.last.get("result")), **got.row())
params = dict(where, newName="aes_renamed")
ms = tries(s, "textDocument/rename", params, ARGS.tries + 1)
_, message = s.request("textDocument/rename", params)
record(phase="rename", row="rename aes -> aes_renamed", ms=ms,
n=len(phases_new.edited_uris(message)))
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
edit = edit_of(got.last)
record(phase="rename", row="rename aes -> aes_renamed",
client=s.client_shape(), fingerprint=fingerprint(edit),
titles=sorted(os.path.basename(u)
for u in phases_new.edited_uris(got.last)),
**dict(got.row(), **counts(edit)))
@@ -303,16 +318,31 @@ def phase_blockers():
lambda: {"textDocument": doc(sites.TB)}),
]
for row, method, make in leaders:
own, behind = [], []
own, behind, statuses = [], [], []
follower_ms = {name: [] for name, _, _ in followers}
for _ in range(ARGS.tries):
with session("workspace") as s:
settled(s)
lead = s.send(method, make())
ids = [(name, s.send(m, mk())) for name, m, mk in followers]
own.append(s.await_id(lead)[0])
behind.append([(name, s.await_id(rid)[0]) for name, rid in ids])
record(phase="blockers", row=row, ms=own,
note=" | ".join("; ".join("%s %.2f" % (n, v) for n, v in one)
leader_ms, leader_message = s.await_id(lead)
own.append(leader_ms)
statuses.append(schema.status_of(leader_message)[0])
one = []
for name, rid in ids:
elapsed, message = s.await_id(rid)
one.append((name, elapsed))
follower_ms[name].append(elapsed)
statuses.append(schema.status_of(message)[0])
behind.append(one)
shape = s.client_shape()
status = schema.worst(statuses)
record(phase="blockers", row=row, ms=own, leader_ms=own,
follower_ms=follower_ms, fresh_process=True, status=status,
message=None if status == "ok" else "a pipelined request failed",
result_count=len(own), client=shape,
note="ms is the leader; each follower has its own field. " +
" | ".join("; ".join("%s %.2f" % (n, v) for n, v in one)
for one in behind))
@@ -332,6 +362,7 @@ def phase_widen():
for cache in ("cold", "warm"):
runs = {relative: [] for relative in sites.WIDEN_FILES}
seconds = {relative: [] for relative in sites.WIDEN_FILES}
statuses = {relative: [] for relative in sites.WIDEN_FILES}
for _ in range(ARGS.tries):
with session(scope, cold=(cache == "cold"),
storage_name="widen-" + scope) as s:
@@ -339,16 +370,24 @@ def phase_widen():
for relative in sites.WIDEN_FILES:
started = time.perf_counter()
s.did_open(sites.path(relative))
s.ms("textDocument/definition", at(relative, "module ", 1, 0))
first = samples(s, "textDocument/definition",
at(relative, "module ", 1, 0), 1)
runs[relative].append((time.perf_counter() - started) * 1000.0)
seconds[relative].append(
s.ms("textDocument/definition", at(relative, "module ", 1, 0)))
second = samples(s, "textDocument/definition",
at(relative, "module ", 1, 0), 1)
seconds[relative].append(second.ms[0])
statuses[relative].extend([first.status, second.status])
s.wait_quiet(0.5)
s.take_notifications()
shape = s.client_shape()
for relative in sites.WIDEN_FILES:
status = schema.worst(statuses[relative])
record(phase="widen",
row="%s @ %s, %s" % (os.path.basename(relative), scope, cache),
ms=runs[relative],
ms=runs[relative], fresh_process=True, status=status,
message=None if status == "ok" else "a definition failed",
result_count=len(runs[relative]), client=shape,
second_definition_ms=seconds[relative],
note="second definition " + " / ".join(
"%.2f" % v for v in seconds[relative]))
@@ -378,7 +417,8 @@ def phase_diagnostics():
time.sleep(0.001)
runs.append((time.perf_counter() - started) * 1000.0)
record(phase="diagnostics", row="publish after didChange (incl. ~150 ms debounce)",
ms=runs)
ms=runs, result_count=len(runs), client=s.client_shape(),
note="a notification barrier, not a request round trip")
@phase("completion")
@@ -392,10 +432,9 @@ def phase_completion():
s.did_change(sites.path(sites.TB), body, version)
where = {"textDocument": doc(sites.TB),
"position": {"line": body.count("\n") - 1, "character": len(prefix)}}
ms = tries(s, "textDocument/completion", where, ARGS.tries + 1)
_, message = s.request("textDocument/completion", where)
record(phase="completion", row="completion after %r" % prefix, ms=ms,
n=result_count(message))
got = samples(s, "textDocument/completion", where, ARGS.tries + 1)
record(phase="completion", row="completion after %r" % prefix,
client=s.client_shape(), **got.row())
@phase("probe")
@@ -410,11 +449,12 @@ def phase_probe():
s.take_notifications()
params = {"textDocument": doc(relative), "range": {"start": where, "end": where},
"context": {"diagnostics": []}}
ms = tries(s, "textDocument/codeAction", params, 2)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
record(phase="probe", row="%s %s:%s" % (relative, line, character), ms=ms,
n=len(offered), titles=[a.get("title") for a in offered])
got = samples(s, "textDocument/codeAction", params, 2)
offered = got.last.get("result") or []
record(phase="probe", row="%s %s:%s" % (relative, line, character),
titles=[a.get("title") for a in offered],
shapes=[phases_p0.shape_of(a) for a in offered],
client=s.client_shape(), **got.row())
def main():
+75 -20
View File
@@ -6,6 +6,11 @@ configuration lives in exactly one place.
`ARGS` is a `Namespace` that is *mutated* by [`configure`], never rebound, so
`from harness import ARGS` in another module keeps seeing the live values.
Every row [`record`] writes is schema 2 (`schema.py`): units, status, result
count, client shape and fresh-process flag are in the row, not in prose.
Phases call [`samples`], never `Session.ms`, because `ms` throws the response
away and a request that *failed* would be recorded as a fast success.
"""
import argparse
@@ -13,8 +18,12 @@ import json
import os
import time
import schema as rowschema
import sites
from lspclient import Session, find_position, summarize, uri # noqa: F401
from schema import ( # noqa: F401 — the phases' record helpers
counts, edit_of, fingerprint, result_count,
)
PHASES = {}
@@ -46,23 +55,47 @@ def phase(name):
def record(**fields):
"""Append one row to results.jsonl and echo it as a readable line."""
"""Append one schema-2 row to results.jsonl and echo a readable line.
`units`, `status` and `fresh_process` are stamped when a phase does not
say otherwise; a status outside `schema.STATUSES`, or a failing status
with nothing to say, is a bug in the phase and raises here rather than
reaching a document. `units="ms"` means the `ms` list is latency and
nothing else — memory and size rows pass their own units and their own
fields (`rss_kib`, `store_kib`), never `ms`.
"""
fields.setdefault("ts", time.strftime("%Y-%m-%dT%H:%M:%S"))
fields.setdefault("label", ARGS.label)
fields.setdefault("schema", rowschema.SCHEMA)
fields.setdefault("units", "ms")
fields.setdefault("status", "ok")
fields.setdefault("fresh_process", False)
if fields["status"] not in rowschema.STATUSES:
raise ValueError("status %r is not one of %r" % (fields["status"],
rowschema.STATUSES))
if fields["status"] != "ok" and not fields.get("message"):
raise ValueError("a %r row must carry its message" % fields["status"])
if fields["units"] == "ms" and "ms" not in fields:
raise ValueError("row %r says ms but carries none" % fields.get("row"))
with open(ARGS.out, "a", encoding="utf-8") as handle:
handle.write(json.dumps(fields) + "\n")
ms = fields.get("ms")
shown = " ".join("%.3f" % v for v in ms) if ms else ""
tail = fields.get("note") or ""
if fields["status"] != "ok":
tail = "[%s] %s %s" % (fields["status"], fields.get("message", ""), tail)
print("%-11s %-52s %s %s" % (fields["phase"], fields.get("row", ""), shown,
fields.get("note", "")), flush=True)
tail), flush=True)
def session(scope="workspace", cold=False, resolve_support=True, verbose=False,
storage_name=None):
storage_name=None, apply_edit=False, create_files=False):
"""A session at one scope, its index store under `--storage/<name>`.
Never the default store: the corpus must not be written near, and cache
warmth has to be controllable per cell.
warmth has to be controllable per cell. `apply_edit` makes the session
capture and decline a pushed `workspace/applyEdit` (the execute phase);
`create_files` lets an extraction answer with a new file.
"""
store = os.path.join(ARGS.storage, storage_name or scope)
return Session(
@@ -73,6 +106,8 @@ def session(scope="workspace", cold=False, resolve_support=True, verbose=False,
resolve_support=resolve_support,
verbose=verbose,
cold=cold,
apply_edit=apply_edit,
create_files=create_files,
)
@@ -85,10 +120,42 @@ def settled(s, open_file=sites.TB):
return s
def tries(s, method, params, n=None):
"""`n` identical requests; returns the millisecond list."""
n = n or ARGS.tries
return [s.ms(method, params) for _ in range(n)]
class Samples:
"""`n` identical requests: their times, their status, the last answer."""
def __init__(self, ms, statuses, messages):
self.ms = ms
self.statuses = statuses
self.messages = messages
self.status = rowschema.worst([s for s, _ in statuses])
self.message = next((m for s, m in statuses if s != "ok"), None)
self.last = messages[-1] if messages else {}
self.result_count = rowschema.result_count(self.last)
def row(self):
"""The schema-2 fields every request row carries."""
fields = {"ms": self.ms, "status": self.status,
"result_count": self.result_count}
if self.message:
fields["message"] = self.message
return fields
def samples(s, method, params, n=None, extra=0):
"""`n` (+ `extra`) identical requests, keeping every response.
`Session.ms` discards the answer, so a request the server *rejected* was
recorded as a fast success (take 5 §P0). This keeps each response, so the
row can say `status=error` with the server's own message.
"""
n = (n or ARGS.tries) + extra
ms, statuses, messages = [], [], []
for _ in range(n):
elapsed, message = s.request(method, params)
ms.append(elapsed)
statuses.append(rowschema.status_of(message))
messages.append(message)
return Samples(ms, statuses, messages)
def pos(relative, needle, occurrence=1, offset=0):
@@ -114,15 +181,3 @@ def code_action_params(relative, needle, occurrence=1, offset=0):
"range": {"start": where, "end": where},
"context": {"diagnostics": []},
}
def result_count(message):
"""How many things an answer carried — a list, an item list, or one thing."""
result = message.get("result")
if result is None:
return 0
if isinstance(result, list):
return len(result)
if isinstance(result, dict) and "items" in result:
return len(result["items"])
return 1
+84 -7
View File
@@ -19,6 +19,12 @@ What it does that a generic client does not, and why each exists:
is ever written near the corpus.
- **`window/logMessage` is captured**, so a `--verbose` server's own
`timing: <method> answered in <n> ms` lines can be read beside the wire.
- **`workspace/applyEdit` is captured, timed and declined.** A command-bearing
offer (extract, inline) does not answer with its edit: it pushes one at a
client that said `workspace.applyEdit`. `Session(apply_edit=True)` says so,
records the payload and the instant it arrived — that instant is the end of
the server's edit computation — and answers `applied: false` with a capture
reason, so the corpus is never written. See `schema.CAPTURE_REASON`.
Everything is timed with `time.perf_counter` from just before the write to
just after the matching response is parsed: what an editor experiences.
@@ -32,6 +38,8 @@ import subprocess
import threading
import time
import schema
# The server's own timing line, from `--verbose` (docs/features/verbose-timing).
TIMING_LINE = re.compile(r"timing: (\S+) answered in ([0-9.]+) ?ms")
@@ -59,17 +67,23 @@ class Session:
verbose=False,
cold=False,
guard=None,
apply_edit=False,
create_files=False,
):
self.server = server
self.root = os.path.abspath(root)
self.storage = os.path.abspath(storage)
self.scope = scope if scope is not None else {}
self.resolve_support = resolve_support
self.apply_edit = apply_edit
self.create_files = create_files
self.verbose = verbose
self.next_id = 1
self.notifications = [] # every server->client notification, in order
self.log_messages = [] # window/logMessage texts only
self.timings = [] # (method, ms) from a --verbose server
self.server_requests = [] # every server->client request, answered
self.applied = [] # captured workspace/applyEdit pushes, in order
self.pending = {} # id -> (method, sent_at) for in-flight requests
self.proc = None
self._reader = None
@@ -167,6 +181,9 @@ class Session:
def _answer_server_request(self, message):
method = message["method"]
if method == "workspace/applyEdit":
self._capture_apply_edit(message)
return
if method == "workspace/configuration":
items = message.get("params", {}).get("items", [])
self._write(
@@ -181,6 +198,38 @@ class Session:
else:
self._write({"jsonrpc": "2.0", "id": message["id"], "result": None})
def _capture_apply_edit(self, message):
"""Record a pushed edit, then decline it. Nothing is ever written.
`arrived` is the end of the server's edit computation and `replied` is
when this client let it go on, so a phase can report the two halves of
an `executeCommand` separately. The answer is `applied: false` with
`schema.CAPTURE_REASON`: an intentional benchmark refusal, recorded as
status `capture`, never confused with an engine refusal.
"""
arrived = time.perf_counter()
params = message.get("params") or {}
self._write({
"jsonrpc": "2.0",
"id": message["id"],
"result": {"applied": False, "failureReason": schema.CAPTURE_REASON},
})
replied = time.perf_counter()
with self._cond:
self.applied.append({
"arrived": arrived,
"replied": replied,
"label": params.get("label"),
"edit": params.get("edit") or {},
})
self._cond.notify_all()
def take_applied(self):
"""Consume and return the `workspace/applyEdit` pushes captured."""
with self._cond:
found, self.applied = self.applied, []
return found
# -- traffic -----------------------------------------------------------
def notify(self, method, params):
@@ -226,7 +275,12 @@ class Session:
"""Move server notifications out of the inbox into the log."""
kept = []
for message in self._inbox:
if "method" in message and "id" not in message:
if "method" in message and "id" in message:
# A server->client request, already answered from the reader
# thread. Logged and dropped so the inbox cannot grow without
# bound across a long session.
self.server_requests.append(message["method"])
elif "method" in message and "id" not in message:
self.notifications.append(message)
if message["method"] == "window/logMessage":
text = message.get("params", {}).get("message", "")
@@ -289,13 +343,23 @@ class Session:
}
if self.resolve_support:
code_action["resolveSupport"] = {"properties": ["edit"]}
# `resourceOperations: ["create"]` with `documentChanges` is what the
# server reads as "this client can be given a new file", which is what
# decides whether an extraction puts the new module in a file of its
# own or beside the old one (`extract.rs::execute`).
workspace_edit = {"documentChanges": True}
if self.create_files:
workspace_edit["resourceOperations"] = ["create", "rename", "delete"]
workspace = {
"configuration": True,
"workspaceEdit": workspace_edit,
"symbol": {"dynamicRegistration": False},
"didChangeConfiguration": {"dynamicRegistration": False},
}
if self.apply_edit:
workspace["applyEdit"] = True
return {
"workspace": {
"configuration": True,
"workspaceEdit": {"documentChanges": True},
"symbol": {"dynamicRegistration": False},
"didChangeConfiguration": {"dynamicRegistration": False},
},
"workspace": workspace,
"textDocument": {
"synchronization": {"dynamicRegistration": False},
"codeAction": code_action,
@@ -314,6 +378,19 @@ class Session:
"window": {"workDoneProgress": True},
}
def client_shape(self):
"""The capability shape this session asked with, for the record.
The same cursor answers differently to each shape: a resolving client
gets a lazy offer, a client that cannot be pushed an edit gets a
command's edit as the result instead.
"""
return {
"resolveSupport": self.resolve_support,
"applyEdit": self.apply_edit,
"createFiles": self.create_files,
}
def initialize(self):
"""`initialize` + `initialized`; returns the request's milliseconds."""
params = {
+141 -69
View File
@@ -12,65 +12,87 @@ table, this is what changed since it.
import json
import os
import subprocess
import threading
import time
import phases_p0
import schema
from harness import (
ARGS, Session, at, code_action_params, doc, phase, pos, record,
result_count, session, settled, sites, tries,
ARGS, Session, at, code_action_params, counts, doc, edit_of, fingerprint,
phase, pos, record, samples, session, settled, sites,
)
def resolve_rows(s, phase_name, label, offered):
"""Resolve the offers that need resolving; route the rest to their phase.
Take 4 sent every offer without an `edit` to `codeAction/resolve`,
including the extract and inline offers, which carry only a **command**.
Dispatch handed those to the ports resolver, which rejects an offer
without its data — so their tiny times measured a refusal. Now a
command-bearing offer is recorded as belonging to the `execute` phase and
is not timed here.
"""
for action in offered:
shape = phases_p0.shape_of(action)
if shape == "edit":
edit = action.get("edit") or {}
record(phase=phase_name, row="%s offer carries its edit: %s" % (
label, action.get("title")),
ms=[0.0], result_count=1, client=s.client_shape(),
fingerprint=fingerprint(edit), note="no resolve needed",
**counts(edit))
continue
if shape == "command":
call = phases_p0.command_of(action) or {}
record(phase=phase_name, row="%s offer is a command: %s" % (
label, action.get("title")),
ms=[0.0], result_count=1, client=s.client_shape(),
command=call.get("command"),
note="timed by the `execute` phase, not by resolve")
continue
got = samples(s, "codeAction/resolve", action, ARGS.tries + 1)
edit = edit_of(got.last)
record(phase=phase_name, row="%s resolve: %s" % (label, action.get("title")),
client=s.client_shape(), fingerprint=fingerprint(edit),
**dict(got.row(), **counts(edit)))
@phase("refactor")
def phase_refactor():
"""The offer sites 0.44–0.49 added: what is offered, and what it costs."""
for label, relative, needle, occurrence, offset in sites.REFACTOR_SITES:
with session("workspace", resolve_support=True) as s:
settled(s)
s.did_open(sites.path(relative))
s.wait_quiet(0.6)
s.take_notifications()
phases_p0.open_and_settle(s, relative)
params = code_action_params(relative, needle, occurrence, offset)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
record(phase="refactor", row="%s offer" % label, ms=ms, n=len(offered),
offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
offered = offer.last.get("result") or []
record(phase="refactor", row="%s offer" % label,
titles=[a.get("title") for a in offered],
file=relative, position=params["range"]["start"])
for action in offered:
if "edit" in action:
continue
resolves = [s.ms("codeAction/resolve", action) for _ in range(ARGS.tries + 1)]
_, resolved = s.request("codeAction/resolve", action)
edit = (resolved.get("result") or {}).get("edit") or {}
record(phase="refactor", row="%s resolve: %s" % (label, action.get("title")),
ms=resolves, n=len(edit.get("changes") or
edit.get("documentChanges") or []))
shapes=[phases_p0.shape_of(a) for a in offered],
client=s.client_shape(), file=relative,
position=params["range"]["start"], **offer.row())
resolve_rows(s, "refactor", label, offered)
# `extract module` is a selection, not a point.
relative, first, first_n, last, last_n = sites.EXTRACT_SELECTION
start = pos(relative, first, first_n)
end = pos(relative, last, last_n)
end = {"line": end["line"], "character": end["character"] + len(last)}
with session("workspace", resolve_support=True) as s:
settled(s)
s.did_open(sites.path(relative))
s.wait_quiet(0.6)
s.take_notifications()
phases_p0.open_and_settle(s, relative)
params = {"textDocument": doc(relative),
"range": {"start": start, "end": end},
"context": {"diagnostics": []}}
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
record(phase="refactor", row="extract-module offer (selection)", ms=ms, n=len(offered),
titles=[a.get("title") for a in offered], file=relative,
position=start, note="selection %d:%d-%d:%d" % (
start["line"], start["character"], end["line"], end["character"]))
for action in offered:
if "edit" in action:
continue
resolves = [s.ms("codeAction/resolve", action) for _ in range(ARGS.tries + 1)]
record(phase="refactor", row="extract-module resolve: %s" % action.get("title"),
ms=resolves)
offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
offered = offer.last.get("result") or []
record(phase="refactor", row="extract-module offer (selection)",
titles=[a.get("title") for a in offered],
shapes=[phases_p0.shape_of(a) for a in offered],
client=s.client_shape(), file=relative, position=start,
note="selection %d:%d-%d:%d" % (
start["line"], start["character"], end["line"], end["character"]),
**offer.row())
resolve_rows(s, "refactor", "extract-module", offered)
@phase("tailrename")
@@ -85,17 +107,18 @@ def phase_tailrename():
s.take_notifications()
where = at(relative, needle, occurrence, offset)
record(phase="tailrename", row="tail rename cursor", ms=[0.0],
note=json.dumps(where["position"]), file=relative)
result_count=0, note=json.dumps(where["position"]), file=relative)
params = dict(where, newName="state_q_x")
ms = tries(s, "textDocument/rename", params, ARGS.tries + 1)
_, message = s.request("textDocument/rename", params)
uris = edited_uris(message)
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
edit = edit_of(got.last)
uris = edited_uris(got.last)
tail = os.path.basename(sites.TAIL_TAIL_FILE)
record(phase="tailrename",
row="rename state_q (tail through u_entropy_src_main_sm)",
ms=ms, n=len(uris),
client=s.client_shape(), fingerprint=fingerprint(edit),
note="tail edited" if any(tail in u for u in uris) else "TAIL NOT EDITED",
titles=sorted(os.path.basename(u) for u in uris))
titles=sorted(os.path.basename(u) for u in uris),
**dict(got.row(), **counts(edit)))
def edited_uris(message):
"""The URIs a `WorkspaceEdit` touches, whichever shape it came in."""
@@ -112,19 +135,29 @@ def edited_uris(message):
def phase_didopen():
"""§46 — `didOpen` → the request behind it, workspace scope, warm store."""
for relative in sites.DIDOPEN_FILES:
runs, seconds = [], []
runs, seconds, statuses, last = [], [], [], {}
for _ in range(ARGS.tries):
with session("workspace") as s:
settled(s)
started = time.perf_counter()
s.did_open(sites.path(relative))
s.ms("textDocument/definition", at(relative, "module ", 1, 0))
first = samples(s, "textDocument/definition",
at(relative, "module ", 1, 0), 1)
runs.append((time.perf_counter() - started) * 1000.0)
seconds.append(s.ms("textDocument/definition", at(relative, "module ", 1, 0)))
second = samples(s, "textDocument/definition",
at(relative, "module ", 1, 0), 1)
seconds.append(second.ms[0])
statuses.extend([first.status, second.status])
last, shape = second.last, s.client_shape()
lines = sum(1 for _ in open(sites.path(relative), encoding="utf-8", errors="replace"))
status = schema.worst(statuses)
record(phase="didopen", row="didOpen %s -> definition" % os.path.basename(relative),
ms=runs, n=lines,
note="second definition " + " / ".join("%.2f" % v for v in seconds))
ms=runs, n=lines, lines=lines, fresh_process=True, status=status,
message=None if status == "ok" else "a definition did not answer ok",
result_count=schema.result_count(last), client=shape,
second_definition_ms=seconds,
note="each try is a fresh server; second definition " + " / ".join(
"%.2f" % v for v in seconds))
@phase("tailcompletion")
@@ -137,55 +170,94 @@ def phase_tailcompletion():
s.wait_quiet(0.8)
s.take_notifications()
where = at(relative, needle, occurrence, offset)
ms = tries(s, "textDocument/completion", where, ARGS.tries + 1)
_, message = s.request("textDocument/completion", where)
items = (message.get("result") or {})
got = samples(s, "textDocument/completion", where, ARGS.tries + 1)
items = (got.last.get("result") or {})
items = items.get("items", items) if isinstance(items, dict) else items
record(phase="tailcompletion",
row="completion after an instance head + '.' (%s)" % os.path.basename(
sites.path(relative)),
ms=ms, n=result_count(message),
titles=[i.get("label") for i in (items or [])[:8]])
client=s.client_shape(),
titles=[i.get("label") for i in (items or [])[:8]], **got.row())
@phase("hierarchy")
def phase_hierarchy():
with session("workspace") as s:
settled(s)
ms = tries(s, "lucisv/moduleHierarchy", {}, ARGS.tries + 1)
_, message = s.request("lucisv/moduleHierarchy", {})
result = message.get("result") or {}
payload = len(json.dumps(result))
record(phase="hierarchy", row="lucisv/moduleHierarchy", ms=ms, n=payload,
got = samples(s, "lucisv/moduleHierarchy", {}, ARGS.tries + 1)
result = got.last.get("result") or {}
record(phase="hierarchy", row="lucisv/moduleHierarchy",
client=s.client_shape(), payload_bytes=len(json.dumps(result)),
note="modules %d, files %d, schema %s" % (
len(result.get("modules") or []), len(result.get("files") or []),
result.get("schemaVersion")))
result.get("schemaVersion")), **got.row())
def rss_kib(pid):
"""One `ps -o rss=` reading in KiB, or 0 once the process is gone."""
out = subprocess.run(["ps", "-o", "rss=", "-p", str(pid)],
capture_output=True, text=True).stdout.strip()
return float(out) if out else 0.0
class Sampler(threading.Thread):
"""`ps -o rss=` every 50 ms, so a scan's *peak* is seen, not just its end.
`/usr/bin/time -l` would give a kernel-reported maximum, but it would have
to wrap the server, and the session's guard already owns that slot; a
50 ms poll is the honest approximation and the row says which it is.
"""
def __init__(self, pid, interval=0.05):
super().__init__(daemon=True)
self.pid, self.interval, self.peak = pid, interval, 0.0
self.stopping = threading.Event()
def run(self):
while not self.stopping.is_set():
self.peak = max(self.peak, rss_kib(self.pid))
self.stopping.wait(self.interval)
def stop(self):
self.stopping.set()
self.join(timeout=2.0)
return self.peak
@phase("rss")
def phase_rss():
"""Server peak RSS after the workspace scan, and the index store on disk.
"""Idle and peak server RSS after the workspace scan, and the store size.
RSS is read with `ps -o rss=` on the server's own pid a second after the
scan settles, so it is the resident set of a server that has finished
indexing and is idle — what an editor session actually holds.
Take 4 put idle RSS in a field called `ms`, where it was neither a latency
nor a peak (take 5 §P0). Here idle RSS is `rss_kib`, the sampled maximum
is `peak_rss_kib`, the store is `store_kib`, `units` says `KiB`, and there
is no `ms` field at all.
Idle is `ps -o rss=` on the server's own pid a second after the scan
settles — the resident set of a server that has finished indexing and is
doing nothing. Peak is the largest of the same reading taken every 50 ms
from `initialize` to that moment, so the scan's own high-water mark is in
the row rather than inferred.
"""
store = os.path.join(ARGS.storage, "rss")
for cache in ("cold", "warm"):
rss, size = [], "0"
idle, peaks, size = [], [], "0"
for _ in range(ARGS.tries):
s = Session(server=ARGS.server, root=sites.ROOT, storage=store,
scope=sites.SCOPES["workspace"], cold=(cache == "cold"))
with s:
sampler = Sampler(s.proc.pid)
sampler.start()
settled(s)
time.sleep(1.0)
rss.append(float(subprocess.run(
["ps", "-o", "rss=", "-p", str(s.proc.pid)],
capture_output=True, text=True).stdout.strip()))
idle.append(rss_kib(s.proc.pid))
peaks.append(sampler.stop())
size = subprocess.run(["du", "-sk", store], capture_output=True,
text=True).stdout.split()[0]
record(phase="rss", row="server RSS after workspace scan, %s cache" % cache,
ms=rss, n=int(size),
note="RSS KB above; index store %s KB" % size)
units="KiB", rss_kib=idle, peak_rss_kib=peaks, store_kib=int(size),
fresh_process=True, result_count=len(idle), client=s.client_shape(),
note="idle RSS a second after the scan settled; peak from "
"`ps -o rss=` sampled at 50 ms; no latency in this row")
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/env python3
"""The phases take 5 §P0 added: what a command actually costs, what a filtered
offer costs, and what a slow offer does to the request behind it.
Imported by `bench.py`, which owns the registry and the command line.
- `execute` — the rows take 4 never had. An extract or inline offer carries a
**command**, not an edit: `codeAction/resolve` on it reaches the ports
resolver, which rejects an offer without its data, so take 4's tiny
"extract resolve" rows measured a refusal, not an extraction. This phase
sends `workspace/executeCommand`, captures the `workspace/applyEdit` the
server pushes back, and declines it. The edit is counted and fingerprinted;
the corpus is never written.
- `offerkinds` — the owner's action-family attribution probe, promoted from a
scratch script: seven `context.only` shapes at five cursors, result counts
beside every time.
- `offerqueue` — the owner's pipelining probe: the pinmux no-offer comment as
the leader and an `aes` definition as the follower, leader and follower in
their own fields rather than a repeats array that means neither.
- [`first_useful_rows`] is not a phase: `bench.py::phase_scan` calls it so the
`scan` phase reports scan-settled time and first-useful-answer separately.
"""
import copy
import os
import time
import schema
from harness import (
ARGS, at, code_action_params, counts, doc, fingerprint, phase, pos,
record, samples, session, settled, sites,
)
#: The `context.only` families the attribution probe walks. `None` asks for
#: everything (no `only` key at all); `[]` asks for nothing, and should be the
#: cheapest answer the server can give.
ONLY_FAMILIES = [
None, [], ["quickfix"], ["refactor.extract"], ["refactor.inline"],
["refactor.rewrite.lucisv.ports"], ["source.organizeImports"],
]
#: (label, file, needle, cursor offset) — the five cursors of the owner's
#: size/attribution control, smallest file first.
OFFER_CURSORS = [
("tb-comment", sites.TB, "// ", 2),
("aes-reg-instance", sites.AES, "aes_reg_top u_reg (", 0),
("aes-core-comment", sites.AES_CORE, "// ", 2),
("spi-comment", sites.SPI_DEVICE, "// ", 2),
("pinmux-comment", sites.PINMUX_REG_TOP, "// ", 2),
]
def open_and_settle(s, relative, quiet=0.6):
"""Settle the scan, then open the file this row measures."""
settled(s)
s.did_open(sites.path(relative))
s.wait_quiet(quiet)
s.take_notifications()
def shape_of(action):
"""`edit`, `command` or `data` — how an offer delivers its work.
An offer that already carries an `edit` needs nothing more; one with only
a `command` is run by `workspace/executeCommand`; one with neither is the
lazy shape, completed by `codeAction/resolve`. Take 4 sent the second and
third kind to the same place, which is the §P0 bug.
"""
if not isinstance(action, dict):
return "command" # a bare `Command`, not a `CodeAction`
if action.get("edit"):
return "edit"
if action.get("command"):
return "command"
return "data"
def command_of(action):
"""`{command, arguments}` for `workspace/executeCommand`, or None."""
command = action.get("command") if isinstance(action, dict) else None
if isinstance(command, str): # a bare `Command` object
return {"command": command, "arguments": action.get("arguments") or []}
if isinstance(command, dict):
return {"command": command.get("command"),
"arguments": command.get("arguments") or []}
return None
def shown(s):
"""The `window/showMessage` texts the server has sent since last asked.
`extract` and `inline` report their scope warnings this way, and a warning
is part of a refactoring's answer — so it joins the fingerprint. A message
naming this client's own declined edit is dropped: that is our doing.
"""
found = [n.get("params", {}).get("message", "")
for n in s.take_notifications("window/showMessage")]
return [t for t in found if t and schema.CAPTURE_REASON not in t]
def execute_once(s, params):
"""One `workspace/executeCommand`, timed in its two halves.
Returns `(compute_ms, deliver_ms, total_ms, message, pushes)`.
`compute_ms` runs from the request going out to the server's
`workspace/applyEdit` arriving: that instant is the end of the edit
computation, which is what a menu click waits for. `deliver_ms` runs from
this client's `applied: false` to the command's own response, and is
recorded separately because it is bookkeeping, not work. A server that
pushed nothing (a refusal, or a client shape that gets the edit as the
result) leaves both halves `None` and only `total_ms` stands.
"""
s.take_applied()
rid = s.send("workspace/executeCommand", params)
sent = s.pending[rid][1]
total_ms, message = s.await_id(rid)
pushes = s.take_applied()
if not pushes:
return None, None, total_ms, message, pushes
compute_ms = (pushes[0]["arrived"] - sent) * 1000.0
deliver_ms = total_ms - (pushes[0]["replied"] - sent) * 1000.0
return compute_ms, deliver_ms, total_ms, message, pushes
def verdict(statuses, pushed):
"""The row's status: a capture is a success, a refusal is not a timing."""
failed = next(((s, m) for s, m in statuses if s != "ok"), None)
if failed:
return failed
if not pushed:
return "error", "the server pushed no workspace/applyEdit"
return "capture", schema.CAPTURE_REASON
def execute_row(s, label, action):
"""`--tries + 1` executions of one command-bearing offer, as one row."""
call = command_of(action)
if call is None or not call["command"]:
record(phase="execute", row="%s: no command" % label, ms=[0.0],
status="error", message="the offer carries no command",
result_count=0, client=s.client_shape())
return
s.take_notifications()
compute, deliver, total, statuses, pushed = [], [], [], [], []
for _ in range(ARGS.tries + 1):
one, two, three, message, pushes = execute_once(s, call)
if one is not None:
compute.append(one)
deliver.append(two)
total.append(three)
statuses.append(schema.status_of(message))
pushed = pushes or pushed
warnings = list(dict.fromkeys(shown(s))) # one per distinct text, in order
status, text = verdict(statuses, pushed)
edit = pushed[0]["edit"] if pushed else {}
note = ("ms is executeCommand -> applyEdit: the edit computation. "
"applyEdit label %r" % pushed[0]["label"] if pushed else
"no edit was pushed, so ms is the whole executeCommand round trip")
record(phase="execute", row="%s: %s" % (label, action.get("title")),
ms=compute or total, status=status, message=text,
result_count=len(pushed), client=s.client_shape(),
command=call["command"], arguments=len(call["arguments"]),
total_ms=total, deliver_ms=deliver or None,
fingerprint=fingerprint(edit, warnings) if pushed else None,
warnings=warnings, note=note, **counts(edit))
def execute_sites():
"""The two command-bearing sites: the extract selection, the inline point.
Both are `sites.py`'s own positions — the selection of `EXTRACT_SELECTION`
and the `inline-module` row of `REFACTOR_SITES` — so the cursor this phase
runs is the cursor `refactor` offers at.
"""
relative, first, first_n, last, last_n = sites.EXTRACT_SELECTION
start, end = pos(relative, first, first_n), pos(relative, last, last_n)
end = {"line": end["line"], "character": end["character"] + len(last)}
rows = [("extract-module", relative,
{"textDocument": doc(relative),
"range": {"start": start, "end": end},
"context": {"diagnostics": []}})]
for label, path, needle, occurrence, offset in sites.REFACTOR_SITES:
if label != "inline-module":
continue
rows.append((label, path,
code_action_params(path, needle, occurrence, offset)))
return rows
@phase("execute")
def phase_execute():
"""§P0 — the extract and inline commands actually run, and their edits.
The client says `workspace.applyEdit` and `resourceOperations: create`, so
the server takes the branch a real editor takes: the edit is pushed, not
returned. Every push is declined with `schema.CAPTURE_REASON`.
"""
for label, relative, params in execute_sites():
with session("workspace", resolve_support=True, apply_edit=True,
create_files=True) as s:
open_and_settle(s, relative)
offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
offered = offer.last.get("result") or []
record(phase="execute", row="%s offer" % label,
client=s.client_shape(), file=relative,
position=params["range"]["start"],
titles=[a.get("title") for a in offered],
shapes=[shape_of(a) for a in offered], **offer.row())
for action in offered:
if shape_of(action) == "command":
execute_row(s, label, action)
@phase("offerkinds")
def phase_offerkinds():
"""§P0 — the `context.only` families at five cursors, four requests each.
The owner's scratch attribution probe, promoted: which families a request
asks for changes what the server computes, and the result count beside
every time says whether a cheaper answer is also a smaller one.
"""
for label, relative, needle, offset in OFFER_CURSORS:
with session("workspace", resolve_support=True) as s:
open_and_settle(s, relative)
base = code_action_params(relative, needle, offset=offset)
for family in ONLY_FAMILIES:
params = copy.deepcopy(base)
if family is not None:
params["context"]["only"] = family
got = samples(s, "textDocument/codeAction", params, 4)
record(phase="offerkinds", row="%s %s" % (label, family),
client=s.client_shape(), file=relative,
position=base["range"]["start"],
only=family, load=os.getloadavg(), **got.row())
@phase("offerqueue")
def phase_offerqueue():
"""§P0 — what the pinmux no-offer comment does to the request behind it.
Leader and follower go out back to back and are recorded in *separate*
fields: take 4's `offer-queue` row put both in `ms`, where a reader could
not tell them from repeat trials.
"""
with session("workspace", resolve_support=True) as s:
open_and_settle(s, sites.PINMUX_REG_TOP)
leader_params = code_action_params(sites.PINMUX_REG_TOP, "// ", offset=2)
follower_params = at(sites.TB, " aes #(", 1, 2)
for pipeline in range(1, ARGS.tries + 1):
lead = s.send("textDocument/codeAction", leader_params)
follow = s.send("textDocument/definition", follower_params)
leader_ms, leader_message = s.await_id(lead)
follower_ms, follower_message = s.await_id(follow)
leader_status, leader_text = schema.status_of(leader_message)
follower_status, follower_text = schema.status_of(follower_message)
record(phase="offerqueue",
row="pinmux comment -> aes definition, pipeline %d" % pipeline,
ms=[leader_ms, follower_ms], leader_ms=leader_ms,
follower_ms=follower_ms,
status=schema.worst([leader_status, follower_status]),
message=leader_text or follower_text,
result_count=schema.result_count(leader_message),
follower_result_count=schema.result_count(follower_message),
client=s.client_shape(),
note="ms is [leader, follower], not repeats")
def first_useful_rows():
"""`scan`'s other half: when the first useful answer arrives.
A definition goes out immediately after the `didOpen`, while the scan is
still running; `first_answer_ms` is when it came back and `settled_ms` is
when that session's server went quiet. Each try is a fresh process. These
are separate rows from `scan`'s own, because a request served during the
scan perturbs the scan: keeping them apart leaves `scan`'s settled series
comparable with take 4's, which had nothing in flight.
"""
for cache in ("cold", "warm"):
first, settle, statuses, found = [], [], [], []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"),
storage_name="scan-workspace") as s:
s.initialize()
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
answer_ms, message = s.await_id(
s.send("textDocument/definition", at(sites.TB, " aes #(", 1, 2)))
first.append(answer_ms)
statuses.append(schema.status_of(message)[0])
found.append(schema.result_count(message))
s.wait_quiet(1.5)
settle.append((time.perf_counter() - started) * 1000.0 - 1500.0)
shape = s.client_shape()
status = schema.worst(statuses)
record(phase="scan", row="workspace, %s cache, first useful answer" % cache,
ms=first, first_answer_ms=first, settled_ms=settle,
fresh_process=True, status=status, client=shape,
message=None if status == "ok" else "a definition did not answer ok",
result_count=found[-1], result_counts=found,
note="ms is the definition sent during the scan; a 0 result "
"count means the answer arrived before the index could "
"give one. settled_ms is that session's own scan, "
"perturbed by serving the request")
+168
View File
@@ -0,0 +1,168 @@
"""Schema 2 for `results.jsonl`: what a row means, written into the row.
Take 4's rows (schema 1, and no `schema` key) said `phase`, `label`, `row`,
`ms`, `n`, `titles`, `note` and nothing else, so a reader had to know from
prose that `rss.ms` held KiB, that `offer-queue.ms` held a leader and a
follower rather than repeats, and that a request which *failed* was recorded
as a fast success. Take 5's §P0 makes each of those explicit:
- `schema` — 2 here. A row without the key is schema 1; read it with take 4's
prose. Nothing is rewritten, so both live in one file.
- `units` — what `ms` (or the row's own value fields) is counted in. Latency
is `ms` and only `ms`; memory and size get their own fields (`rss_kib`,
`peak_rss_kib`, `store_kib`) which are never `ms`.
- `status` — `ok`, `error`, `refused` or `capture`, plus `message` for
anything but `ok`. **No document may quote a row whose status is not `ok`,
`capture`, or exactly its own `expected_status`** — the last is for the one
row whose designed outcome *is* a rejection (the transport floor asks for a
method that does not exist). [`quotable`] is that rule in code.
- `result_count` — how many things the answer carried, so a timing that moved
because the *answer* moved is not read as a timing change.
- `client` — the capability shape that asked (`resolveSupport`, `applyEdit`,
`createFiles`), because the same cursor answers differently to each.
- `fresh_process` — whether each try was its own server, or repeats in one.
- `fingerprint` (edit-bearing rows) — sha256 over the sorted
`(uri, start, end, newText)` edits, the sorted created paths and the sorted
warnings, so two runs' edits are compared without quoting the corpus.
Python 3 standard library only, like the rest of `tools/perf`.
"""
import hashlib
import json
#: The version stamped into every row this harness writes.
SCHEMA = 2
#: `ok` answered; `error` failed; `refused` is the engine's own refusal
#: sentence (JSON-RPC `RequestFailed`); `capture` is *this client* declining
#: an edit it was pushed, which is a benchmark decision and not a server one.
STATUSES = ("ok", "error", "refused", "capture")
#: LSP's `RequestFailed`. The server returns a refusal sentence with this
#: code (a declined rename, an engine "cannot inline that"); any other code
#: is a real error.
REQUEST_FAILED = -32803
#: What this client tells the server when it declines a pushed edit. The
#: corpus is read-only: an edit is measured, never applied.
CAPTURE_REASON = "perf capture: the benchmark client never writes"
def status_of(message):
"""`(status, message_text)` for one JSON-RPC response."""
error = message.get("error") if isinstance(message, dict) else None
if not error:
return "ok", None
text = error.get("message") or json.dumps(error)
if error.get("code") == REQUEST_FAILED:
return "refused", text
return "error", "code %s: %s" % (error.get("code"), text)
def quotable(row):
"""Whether a document may quote this row's numbers.
`ok` answered and `capture` is this client declining an edit it asked to
be shown — both are measurements. An `error` or `refused` row measured a
rejection, and its time is not the operation's time; the sole exception is
a row whose `expected_status` names the rejection it was built to get.
"""
status = row.get("status", "ok")
return status in ("ok", "capture") or status == row.get("expected_status")
def worst(statuses):
"""The status a row of several tries reports: any failure outranks `ok`."""
for rank in ("error", "refused", "capture", "ok"):
if rank in statuses:
return rank
return "ok"
def result_count(message):
"""How many things an answer carried — a list, an item list, or one."""
result = message.get("result") if isinstance(message, dict) else None
if result is None:
return 0
if isinstance(result, list):
return len(result)
if isinstance(result, dict) and "items" in result:
return len(result["items"])
return 1
def _one(uri, edit):
"""One text edit as a comparable tuple."""
where = edit.get("range") or {}
start, end = where.get("start") or {}, where.get("end") or {}
return [
uri,
start.get("line"), start.get("character"),
end.get("line"), end.get("character"),
edit.get("newText"),
]
def normalized(edit):
"""`(edits, created)` from a `WorkspaceEdit`, both sorted.
Both shapes are read: the `changes` map every client understands, and the
`documentChanges` list a resource operation forces (an extraction that
creates a file cannot use the map).
"""
edits, created = [], []
if not isinstance(edit, dict):
return edits, created
for uri, ones in (edit.get("changes") or {}).items():
edits.extend(_one(uri, one) for one in ones or [])
for change in edit.get("documentChanges") or []:
if not isinstance(change, dict):
continue
kind = change.get("kind")
if kind in ("create", "rename", "delete"):
created.append("%s %s" % (kind, change.get("uri") or change.get("newUri") or ""))
continue
uri = (change.get("textDocument") or {}).get("uri", "")
edits.extend(_one(uri, one) for one in change.get("edits") or [])
edits.sort(key=json.dumps)
created.sort()
return edits, created
def counts(edit):
"""`{edits, files, created}` for a `WorkspaceEdit`."""
edits, created = normalized(edit)
return {
"edits": len(edits),
"files": len({one[0] for one in edits}),
"created": len(created),
}
def fingerprint(edit, warnings=()):
"""sha256 over the sorted edits, created paths and warnings.
Two runs that computed the same refactoring have the same fingerprint,
and no corpus text has to be copied out to say so.
"""
payload = json.dumps(
{"edits": normalized(edit)[0], "created": normalized(edit)[1],
"warnings": sorted(warnings)},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def edit_of(message):
"""The `WorkspaceEdit` in a response, whichever request produced it.
`textDocument/rename` answers with the edit itself; `codeAction/resolve`
answers with a code action carrying one.
"""
result = message.get("result") if isinstance(message, dict) else None
if not isinstance(result, dict):
return {}
if "edit" in result:
return result.get("edit") or {}
return result
+25 -3
View File
@@ -4,7 +4,11 @@
# trees, one binary at a time, three tries per cell, wall clock and peak RSS
# from `/usr/bin/time -l`.
#
# tools/perf/sweep.sh <lucisv-binary> <label> <opentitan-dir> <out-dir> [tries]
# tools/perf/sweep.sh <lucisv-binary> <label> <opentitan-dir> <out-dir> \
# [tries] [trees]
#
# `trees` is a space-separated list, defaulting to all five; pass one tree to
# check a single cell (`sweeptable.py` reads whatever is there).
#
# Each cell writes `<out-dir>/<label>__<tree>__<command>__<cache>.txt`, which
# holds the three runs' `/usr/bin/time -l` blocks; `sweeptable.py` reads them.
@@ -24,19 +28,37 @@ HERE=$(cd "$(dirname "$0")" && pwd)
GUARD="$HERE/../guard.sh"
CACHE="$OUT/fmtcache"
TREES="hw/ip hw/top_earlgrey/ip hw/top_darjeeling/ip hw/dv hw/vendor"
TREES=${6:-"hw/ip hw/top_earlgrey/ip hw/top_darjeeling/ip hw/dv hw/vendor"}
mkdir -p "$OUT"
# Cache warmth, per try, not per cell.
#
# Until take 5 §P0 this deleted `$CACHE` once before the *three* cold tries,
# so tries 2 and 3 read the store the first try had just written: two of every
# three "cold" numbers were warm. Now a cold try deletes the scratch cache
# immediately before itself, and a warm cell is primed by one explicit
# untimed run whose output is kept in the log but not counted. `sweeptable.py`
# prints the "N files from cache" each try reported, so a cold row that is not
# actually cold is visible rather than inferred.
#
# Only `$CACHE` — a scratch directory under `$OUT` — is ever removed. Nothing
# inside the corpus is touched.
run_cell() {
local tree=$1 name=$2 cache=$3
shift 3
local safe=${tree//\//_}
local log="$OUT/${LABEL}__${safe}__${name}__${cache}.txt"
: >"$log"
if [ "$cache" = cold ]; then rm -rf "$CACHE"; fi
if [ "$cache" = warm ]; then
echo "--- prime (untimed, not a try) ---" >>"$log"
rm -rf "$CACHE"
"$GUARD" -m 8 -t 1800 -- "$BIN" "$@" >>"$log" 2>>"$log"
echo "--- prime exit $? ---" >>"$log"
fi
local i
for i in $(seq 1 "$TRIES"); do
if [ "$cache" = cold ]; then rm -rf "$CACHE"; fi
echo "--- try $i ---" >>"$log"
# `-l` puts the resource block on stderr; both streams are kept.
"$GUARD" -m 8 -t 1800 -- /usr/bin/time -l "$BIN" "$@" >>"$log" 2>>"$log"
+35 -5
View File
@@ -11,6 +11,13 @@ per label — first try, then the range over the repeats, then peak RSS.
It also prints the summary line each run reported (`N files would be
reformatted`, the finding count), because a timing that moved because the work
moved is not a timing finding.
Since take 5 §P0 it prints the **cache hit count per try** — the `N files from
cache` the formatter reported, or 0 when it reported none. A "cold" row whose
tries report hits is not cold, which is exactly the bug §P0 fixed in
`sweep.sh`; printing the number per try makes the next one visible instead of
inferred. The untimed priming run a warm cell now starts with is excluded:
only the blocks after a `--- try N ---` marker are read.
"""
import argparse
@@ -20,6 +27,8 @@ import sys
REAL = re.compile(r"([0-9.]+)\s+real")
RSS = re.compile(r"(\d+)\s+maximum resident set size")
HITS = re.compile(r"(\d+) files? from cache")
TRY = re.compile(r"^--- try \d+ ---$", re.MULTILINE)
COMMANDS = [("format", "cold"), ("format", "warm"), ("check", "default"), ("check", "select")]
COMMAND_NAMES = {
("format", "cold"): "`format --check`, cold cache",
@@ -31,23 +40,28 @@ TREES = ["hw/ip", "hw/top_earlgrey/ip", "hw/top_darjeeling/ip", "hw/dv", "hw/ven
def cell(directory, label, tree, command, cache):
"""(reals, peak_rss_mb, summary_lines) for one cell, or None if absent."""
"""(reals, peak_rss_mb, summary_lines, hits) for a cell, or None."""
name = "%s__%s__%s__%s.txt" % (label, tree.replace("/", "_"), command, cache)
path = os.path.join(directory, name)
if not os.path.exists(path):
return None
text = open(path, encoding="utf-8", errors="replace").read()
reals = [float(v) for v in REAL.findall(text)]
rss = [int(v) for v in RSS.findall(text)]
# Everything before the first `--- try 1 ---` is a warm cell's untimed
# priming run: it is not a trial and is not counted anywhere.
tries = TRY.split(text)[1:]
timed = "".join(tries) if tries else text
reals = [float(v) for v in REAL.findall(timed)]
rss = [int(v) for v in RSS.findall(timed)]
# The run's own total line, not its per-file lines: a timing that moved
# because the *work* moved is not a timing finding.
summary = [
line.strip()
for line in text.splitlines()
for line in timed.splitlines()
if re.match(r"^(\d+ files? would be reformatted|found \d+ violations|"
r"no violations|All \d+)", line.strip())
]
return reals, (max(rss) / 1048576.0 if rss else 0.0), summary
hits = [int(HITS.search(one)[1]) if HITS.search(one) else 0 for one in tries]
return reals, (max(rss) / 1048576.0 if rss else 0.0), summary, hits
def render(reals):
@@ -89,6 +103,22 @@ def main():
continue
print(" %-22s %-8s %-8s %-8s %s" % (
tree, command, cache, label, found[2][0]))
print()
print("Format-cache hits per try (a cold row with a hit is not cold):")
for tree in TREES:
for command, cache in COMMANDS:
if command != "format":
continue
for label in labels:
found = cell(args.directory, label, tree, command, cache)
if not found:
continue
flag = " <-- COLD ROW WITH HITS" if (
cache == "cold" and any(found[3])) else ""
print(" %-22s %-8s %-8s %s%s" % (
tree, cache, label,
" / ".join(str(v) for v in found[3]) or "—", flag))
return 0