Skip to content

perf(runtime)!: cancel tool and host calls by wake, not by a 50 ms poll (H22.2, stacked on #46) - #47

Merged
lg2m merged 4 commits into
refactor/h22-2-structural-bundlefrom
perf/h22-2-notify-cancellation
Sep 16, 2026
Merged

lg2m merged 4 commits into
refactor/h22-2-structural-bundlefrom
perf/h22-2-notify-cancellation

Conversation

@lg2m

@lg2m lg2m commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

H22.2 (2 of 2): cancel tool and host calls by wake, not by a 50 ms poll

Stacked on #46 (refactor/h22-2-structural-bundle) — review and merge that first; this PR's diff is only the cancellation change on top. Phase 6 closes when both merge.

Spec: docs/plans/speed-first-extensible-agent-harness.md § D8 "Remaining acceptance" (deferred from H20 to H22 because it changes ExternalToolHost::call) · ADR: docs/adr/0026-run-cancellation-token.md

No PROTOCOL_VERSION, store schema, or descriptor change.

The problem

A run's cancellation was an Arc<AtomicBool>. Three sites — the embedded tool host, the shell tool, and the MCP manager — can't await a flag, so each ran a 50 ms interval and checked it per tick. Two costs:

  • Latency. Measured cancel → Cancelled for an in-flight host call: 48.0 ms median, 49.0 ms p95. The tick lands at a fixed phase relative to the call's start, so it waited out nearly a full period, every time.
  • Wake-ups. Every in-flight host call registered a timer every 50 ms for its whole life. An idle MCP call or a long shell command was a steady stream of scheduler work that did nothing.

What changed

qq_core::RunCancellation — the run's token: Arc<{ AtomicBool, Notify }>, Clone, one per run, cloned into every tool call, host call, context fetch, and blocking helper.

  • cancel() sets the flag and wakes every waiter; idempotent.
  • cancelled().await registers the Notified before reading the flag, so a cancel between the check and the await is never lost; a cancel before the first wait resolves immediately (the flag is the truth, not a one-shot permit).
  • is_cancelled() for work that can't await (a blocking read, a directory walk).

The three pollers now select! on the token. The interval and its MissedTickBehavior are gone from all three. The 14 .store(true, Release) sites in sessions/execution.rs became .cancel() — there is no longer a way to set the flag without waking waiters.

qq-mcp stays free of core's type: McpManager::call takes CancellationSignal = Pin<Box<dyn Future<Output = ()> + Send>> and the root adapter builds it as Box::pin(cancelled.cancelled()). One box per MCP call; keeps the crate direction.

Breaking (public API)

Before After
ExternalToolHost::call(&self, name, arguments, cancelled: Arc<AtomicBool>) … cancelled: RunCancellation)
ContextSource::fetch(&self, request, cancelled: Arc<AtomicBool>) … cancelled: RunCancellation)
Runtime::run_*_with_cancellation(…, Arc<AtomicBool>) and the run loop RunCancellation
McpManager::call(&self, name, arguments, Arc<AtomicBool>) … CancellationSignal)

Every in-tree implementor (root MCP adapter, four test/bench hosts, one test source) is updated here. An out-of-tree host replaces cancelled.load(Acquire) on a tick with () = cancelled.cancelled() => Err(HostCallError::Cancelled) in its select!.

The guard

hosts::conformance::check now requires an in-flight call to settle as Cancelled within 40 ms of cancel() — comfortably under the old period, so a host that reverted to polling fails the suite — and a pre-cancelled token to settle a call at once, twice (it's a flag, not a permit). The MCP cancellation test asserts the same bound. Three unit tests on the token: wake without polling; cancel-before-wait resolves and repeats; no lost wake between check and await.

Measurements

host_cancel_latency (new bench), cancel → Cancelled for an in-flight embedded host call, 200 iterations, same host and delay:

median p95 max
polled flag (main) 48.0 ms 49.0 ms 49.0 ms
token (this PR) 251 ns 941 ns 1.8 µs

Evidence: target/qq-perf/h22-2026-09-15/host_cancel_latency-{before,after}.txt.

How verified

Docs

  • ADR-0026 (Accepted); docs/adr/README.md; root.md (0025 → merged, 0026 reserved, next free 0027)
  • architecture.md § Runtime (the cancellation contract) and the ExternalToolHost seam paragraph
  • Plan: D8 remaining-acceptance note closed, § Bundled Fixes item marked shipped; ledger receipt

Compatibility note for the plan

The 50 ms executable output-service budget in D8 is unrelated to these polls and still awaits a quiet-host p95 recording (H20). This PR closes the other D8 remainder.

…ll (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
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
@lg2m
lg2m added this pull request to stack #48 September 16, 2026 17:50
@lg2m
lg2m merged commit c7fd5c4 into main Sep 16, 2026
4 checks passed
@lg2m
lg2m deleted the perf/h22-2-notify-cancellation branch September 16, 2026 18:29
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