Skip to content

refactor: H22.2 structural bundle — route table gate plus 28 cold-path fixes across eight crates - #46

Merged
lg2m merged 9 commits into
mainfrom
refactor/h22-2-structural-bundle
Sep 16, 2026
Merged

lg2m merged 9 commits into
mainfrom
refactor/h22-2-structural-bundle

Conversation

@lg2m

@lg2m lg2m commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

H22.2: structural bundle — route table gate plus 28 cold-path fixes across eight crates

Spec: docs/plans/speed-first-extensible-agent-harness.md § Bundled Fixes (H22) · Phase 6 acceptance: "the H22 route-table equality test passes between client and server"

First of a two-PR stack. The second (perf/h22-2-notify-cancellation) carries the one public-signature change in the H22 list and is based on this branch. Phase 6 closes when both merge.

No PROTOCOL_VERSION, store schema, or DESCRIPTOR_VERSION change. Wire and headless goldens are byte-identical.

What this is

Two audits of the 34 items under § Bundled Fixes: 1 already done (MCP permit ordering), 4 partial, 29 open. This PR lands 28 as one commit per crate, so each is reviewable on its own and any one can be reverted alone. Seven items are deferred with written reasons (below).

The acceptance gate

SessionCommandKind::route() / COMMAND_ROUTES in qq-protocol is the one source for the 13 command paths. The server registers handlers from the table and checks the decoded kind against the route's kind; the client posts to kind.route(). command_routes_match_the_protocol_table drives every kind through its own route (200) and its neighbour's (400) and asserts the handled sequence equals SessionCommandKind::ALL. A route added to one side without the other fails there, not in the field. Server: 13 near-identical handlers → 1.

Per-crate commits

Commit Crate What
9d8eb62 server Route table + gate test; decode_bounded replaces four copies of permit + body-limit + strict-decode
07e4ff7 protocol Box<SessionSummary> in 8 event variants: SessionEvent 536 → 328 bytes (size test pins it; goldens unchanged); one sha256_identity! macro for InstructionHash/ContentHash (−70 lines); client body limits into limits.rs so the server bounds by the same constants
4523bf2 cli PlanCache::load(&PlanKey): a hit clones nothing; SourceFingerprint::is_current re-stats without a PathBuf clone per source per lookup
272634a provider Request body encoded into a Vec sized from ModelRequest::wire_size_hint: heap peak 1.57→1.40x / 1.80→1.60x / 1.55→1.39x / 1.58→1.39x of payload, encode time flat (5 interleaved pairs); Arc<HeaderMap> (one clone per attempt, not two); RequestAuthorizer is an enum; attempts that add no secret share the static redaction list (normalized once in HttpExchange::new); Bedrock event size from payload bytes instead of Debug-formatting the SDK event
19befce runtime Correctness: the direct run path called every host's blocking catalog_blocking on the async task before spawn_blocking — now inside it. One pinned deadline timer per call in the embedded-host, shell, and MCP loops (was a fresh sleep_until per poll tick / output chunk). RetainedResult keeps text + flag + spill handle per tool call and moves file states, display, and spilled text into the event instead of cloning the whole output. workspace::read_bounded behind five identical size-take-check reads. AgentPlanDescriptor::encode: 3 → 1 serializations per compile. session_files eviction gated on count (regression test)
68318c5 config, auth Seven built-in presets built once behind LazyLock, cloned per load. Probes memoizes verified ancestor directories (test: a symlink below a verified prefix is still rejected). Auth reads take lock_shared; writers keep exclusive; every post-lock verification unchanged. Data-dir chmod only when the verified mode differs. resolve_with_epoch returns secret + epoch in one lock cycle
26625d0 client, tui SessionStore::body_mut leaves the tree index alone; all streaming reducers use it, so the sidebar order is not rebuilt every frame during a run (test pins the same allocation across deltas). Sidebar plan uses has_status_line (no alloc) for all sessions, builds text only for visible rows. Transcript caches the unsettled tail from refresh_live for live_lines. Default chords parsed once. tool_timing evicted with its calls; expanded_tool_calls bounded at 256

Deferred (in the plan, with reasons)

  • StaticHttpAuth — HttpAuth is public and re-exported; the four build_headers differ in per-protocol header-safety checks. Own slice + ADR.
  • Headless output off the Tokio worker — changes headless::run/output::render signatures and exit-code-on-write-failure semantics; 1,300 lines of tests use Vec<u8> writers. Needs a contract test first.
  • Config parse-once-per-load — three Document::parse per source with trust-gating between them; correctness risk on a cold path.
  • Reviewer via PlanCache — a behavior fix (it ignores config changes until a credential rotates), not structure.
  • TurnMode/StreamEnd, parse-args-once, Arc<[RuntimeToolCall]> — in the 1,600-line run loop; do when it's next opened for a behavioral change.
  • Approval-wait sleep_until — not done by measurement: that loop iterates once per reviewer verdict.

How verified

  • cargo test --workspace — 1,425 passed / 4 ignored (main: 1,401; +24 new); fmt; clippy --workspace --all-targets --all-features -D warnings; cargo build --workspace
  • cargo test -p qq-provider --no-default-features --features test-support — 169 passed; minimal-profile clippy clean
  • One flake seen once under full-workspace load: schedules_ready_sessions_fairly hit its 2 s timeout; 3/3 isolated, 1/1 on rerun, and it passes on main under the same load. Pre-existing timing test, not touched here.

Measurements

  • provider_encode, 5 interleaved pairs vs main (evidence target/qq-perf/h22-2026-09-15/):

    Case Encode µs Heap, shared Arc
    openai_responses 195 → 212 1.57x → 1.40x
    openai_chat 223 → 228 1.80x → 1.60x
    anthropic_messages 204 → 198 1.55x → 1.39x
    google_generate_content 440 → 409 1.58x → 1.39x
  • SessionEvent 536 → 328 bytes (measured on main and here; test asserts ≤ 336).

  • Everything else is structural or cold-path and shipped on inspection.

Compatibility

  • qq-protocol: 8 SessionEvent variants now carry Box<SessionSummary> (serde-transparent; wire unchanged). New pub: COMMAND_ROUTES, SessionCommandKind::route, 5 limit consts.
  • qq-auth: new pub resolve_with_epoch (additive).
  • qq-client: new pub SessionStore::body_mut; retain_recent_tool_calls now returns evicted ids.
  • Root: PlanCache::load takes &PlanKey (root-only callers).
  • qq-provider: RequestAuthorizer is crate-private; no public change.

Follow-ups

  • Stacked PR: Notify cancellation (next in the stack).
  • The seven deferrals above.

SessionCommandKind::route() and COMMAND_ROUTES in qq-protocol are the one
source for the thirteen command paths. The server registers its handlers
from the table and checks the decoded kind against the route's; the client
posts to kind.route(). command_routes_match_the_protocol_table drives every
kind through its own route and its neighbour's, so a route added to one
side without the other fails in the test. decode_bounded replaces the four
copies of the permit + body-limit + strict-decode preamble.

Slice: H22.2
…ed body limits (H22.2)

The eight SessionEvent variants that carry a SessionSummary box it: the
enum drops 536 -> 328 bytes with no wire change (Box is serde-transparent;
the wire and headless goldens are unchanged). A size test pins both facts.
InstructionHash and ContentHash come from one sha256_identity! macro
instead of two identical 70-line impl blocks. The client's per-route
response bounds move to qq_protocol::limits so the server bounds what it
emits by the same constants instead of a private copy.

Slice: H22.2
… allocating (H22.2)

PlanCache::load takes &PlanKey: a hit clones nothing, and the key (two
PathBufs and an optional inline config document) is copied only into the
in-flight guard list and a new slot. SourceFingerprint::is_current observes
the path in place instead of building a whole fingerprint with a cloned
PathBuf per source per lookup.

Slice: H22.2
…horizer (H22.2)

sse_exchange encodes into a Vec sized from ModelRequest::wire_size_hint (the
payload bytes the codecs embed verbatim plus fixed framing) instead of
letting reqwest's .json() double from empty: request heap peak drops from
1.55-1.80x to 1.39-1.60x the payload on provider_encode (five interleaved
pairs, encode time flat). Adapters hold Arc<HeaderMap> so an attempt clones
the map once, not twice. RequestAuthorizer is an enum of the one mechanism
that applies; an attempt whose authorizer adds no secret shares the static
redaction list, which HttpExchange::new now normalizes once. The Bedrock
event size check counts the text, tool-input, id, and name bytes it will
keep instead of Debug-formatting the SDK event.

Slice: H22.2
…unded read; slim tool-result retention (H22.2)

- The direct run path captured every host's blocking catalog on the async
  task before spawn_blocking; the capture now runs inside it.
- The embedded-host, shell, and MCP call loops pin one deadline timer for
  the whole call instead of registering a fresh sleep_until on every poll
  tick or output chunk.
- The run loop retains a RetainedResult (bounded text, error flag, spill
  handle) per tool call and moves file states, display payload, and the
  spilled text into the finished event instead of cloning the whole output.
- workspace::read_bounded is the one size-then-take-then-check read behind
  instructions, guidance, personas, input attachments, and editable files.
- AgentPlanDescriptor::encode serializes once for both the digest and the
  persisted JSON (previously three serializations per compile).
- session_files eviction runs only when a new path pushes a session over
  MAX_SESSION_FILES; updates and under-bound sessions skip the ordered
  sub-select. Regression test pins the bound and the update case.

Slice: H22.2
…or checks, shared read locks (H22.2)

qq-config: the seven built-in provider presets (each a filtered copy of the
model table) are built once behind a LazyLock and cloned per load instead
of rebuilt on every load. Probes memoizes the directories whose ancestors
it has already checked for symlinks, so candidates under one tree do not
re-stat their common prefix; a test shows a symlink below a verified prefix
is still rejected.

qq-auth: reads (resolve, epoch, status, list) take the lock file shared so
concurrent compiles do not serialize on each other; writers keep the
exclusive lock and every verification after the lock is unchanged. The data
directory chmod runs only when the verified mode differs from 0700.
resolve_with_epoch returns the secret and the epoch of the index it was
read from in one lock cycle, for callers that record both.

Slice: H22.2
…k only for visible rows (H22.2)

qq-client: SessionStore::body_mut is mutable access that leaves the derived
tree index alone; every streaming reducer (text, reasoning, tool output,
activity, run stats, message lookup) uses it, so the sidebar order is not
rebuilt on every frame while a run streams. get_mut still drops the index
for summary changes. Tool-call timings are evicted with the calls they
describe. Regression test pins that deltas keep the same index allocation
and a summary change still rebuilds it.

qq-tui: the sidebar plan asks has_status_line (no allocation) for every
session and builds the status text only for rows inside the window. The
transcript keeps the unsettled tail collected by refresh_live so live_lines
in the same frame lays it out instead of collecting it again. Default
command chords are parsed once behind a LazyLock instead of per keypress.
expanded_tool_calls is bounded at 256, dropping expansions for calls no
session retains first.

Slice: H22.2
@lg2m
lg2m added this pull request to stack #48 September 16, 2026 17:50
@lg2m
lg2m merged commit 486926b into main Sep 16, 2026
4 checks passed
@lg2m
lg2m deleted the refactor/h22-2-structural-bundle branch September 16, 2026 18:29
lg2m added a commit that referenced this pull request Sep 16, 2026
…ll (H22.2, stacked on #46) (#47)

* perf(runtime)!: cancel tool and host calls by wake, not by a 50 ms poll (H22.2)

RunCancellation is the run's cancellation token: a flag plus a Notify, one
per run, cloned into every tool call, host call, context fetch, and
blocking helper. cancel() sets the flag and wakes every waiter; cancelled()
registers before it reads the flag so a cancel between the check and the
await is never lost. It replaces the Arc<AtomicBool> that the embedded
host, the shell tool, and the MCP manager each polled every 50 ms.

The three loops now select on the token: cancellation is observed when it
happens, not up to 50 ms later, and an idle call registers no timer per
tick. ToolCancellation (run + dropped-caller) keeps its shape with the run
half as the token. qq-mcp takes a plain CancellationSignal future so it
stays free of core's type; the root adapter builds it from the token.

Breaking: ExternalToolHost::call and ContextSource::fetch take
RunCancellation; Runtime::run*_with_cancellation and the run loop take it;
McpManager::call takes CancellationSignal. Implementors replace
`cancelled.load(Acquire)` polls with `cancelled.cancelled().await` in a
select, or `is_cancelled()` between blocking steps.

The host conformance suite now requires cancellation to settle within
40 ms of cancel() (well under the old poll period) and a pre-cancelled
token to settle a call at once, twice. The MCP cancellation test asserts
the same bound.

Slice: H22.2

* perf(runtime): host_cancel_latency bench (H22.2)

Measures cancel() -> Cancelled for an in-flight embedded host call. On the
polled hosts this was 48.0 ms median / 49.0 ms p95 (the poll landed at a
fixed phase and waited out almost a full period); with the token it is
251 ns median / 941 ns p95 / 1.8 us max over 200 iterations.

Slice: H22.2

* docs(h22.2): ADR-0026 run cancellation token; architecture, plan, ledger

Slice: H22.2

* docs(ledger): link H22.2 Notify PR #47
lg2m added a commit that referenced this pull request Sep 16, 2026
#46 was cut before v0.1.0 (#42) and merged after it without a rebase, so
its Cargo.toml carried 0.0.0 back onto main: `qq --version` reported 0.0.0
and the next `cargo xtask release` would have compared against the wrong
base. A test now fails whenever the manifest version is below the newest
v* tag, so a stale branch cannot do this silently again.
lg2m added a commit that referenced this pull request Sep 16, 2026
* docs: close Phase 6 and reconcile every plan with what shipped

Phase 6 closed with #46/#47 but the docs still said "in review" in
fourteen places, the tool-layer plan still said "proposed" with eight of
fourteen slices shipped, three ADRs said Proposed for merged work, and the
priority table listed only shipped items. This pass makes the docs match
main at 7956e8e:

- speed-first plan: status block closed; Phases 5b and 6 collapsed to
  Completed Phases rows per the plan's own rule; D5/D8/D9/D10 as-built
  blocks reduced to ADR pointers; § Bundled Fixes keeps only the seven
  deferrals; version row points at protocol.md. 865 -> 742 lines.
  Gate files g-phase-5b.md and g-phase-6.md written.
- tool-layer plan: status block added (T1-T8, T12 shipped); D1-D5 and D8
  replaced by pointers to tools.md plus the recorded departures (rule
  count, PolicyDecision::Forbidden shape, runtime/spill.rs, Launch in
  shell.rs, LineRange, qq-tui -> qq-core edge); dependency table and
  owned paths corrected; § Docs marked done. 601 -> 317 lines.
- ADR-0019/0020/0022 -> Accepted; adr/README.md and root.md agree with the
  files; root.md requests table resolved; ADR-0027 records that qq-core
  is a public embedding API (the audit's "unused exports" are the
  contract).
- plans/README.md priority table rewritten to open work only; readiness
  plan's Phase 6 candidates replaced by pointers to T2/T5/T10 and its
  delivery table annotated; R6-search/patch ledger rows Superseded;
  supervised-delegation status and its applied Amendments collapsed;
  multi-surface status, shipped gaps, and W2 ledger row.
- Design docs: tools.md forward references to plan slices removed
  (list_dir, T6/T7 capture cap, T11); architecture.md records the
  qq-tui -> qq-core edge, the built-in tool set, and tool_spills/schema
  28; product.md and architecture.md point web/mobile at the approved
  multi-surface plan; headless-contract.md musl row and v21 note;
  release.md example numbers; README approval modes describe the
  classifier tiers, supervised, and full.
- decisions-needed #2 stays dropped, #3 carried to Phase 7, #4 and #6
  resolution text updated.

Every relative link and anchor under docs/** resolves (checked with
GitHub's slug rule); the as-built ADRs now point at design docs, not at
the plan sections that were collapsed.

* docs(ledger): link the cleanup stack (#51, #52)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant