Skip to content

[perf] agent: record where a turn spends its time (#449) - #469

Merged
kunkunblueberry merged 2 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:perf/turn-timing
Nov 24, 2026
Merged

kunkunblueberry merged 2 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:perf/turn-timing

Conversation

@Zhangbo-cn

Copy link
Copy Markdown
Contributor

Why

Issue #449 asks for TTFA/TTC measurement (T5) before any tool-overhead optimization. The existing trace carries the events but no timestamps: 609 JSON-RPC messages, 173 tool calls, 954 job wait polls, and a total duration that nothing records. The only thing known today is a floor — 1,224 tool calls × 1.16 s of CLI start-up ≈ 23.7 minutes — and a floor is not a share, so it cannot say whether the transport, the model loop, or project synchronization should be optimized first.

This PR makes a turn report where its time went, and pre-registers the bands that turn the numbers into a decision.

What changes

One call now yields three numbers instead of a guess:

Number Source Why it cannot be measured elsewhere
spawn the CLI reports its own import time in the request it already sends interpreter start-up and imports happen before any request reaches the host
work the transport, host side it is what the command itself spent
call wall time the API layer, keyed by call identity the only value that exists for a runtime whose tool calls never pass through the transport
  • cli.py anchors a monotonic clock at import and sends timing.startedAt with each request.
  • agent/cli_transport.py turns that into spawn and work on the tool events it already emits, and drops an impossible value instead of poisoning the turn's totals.
  • agent/timing.py folds tool events into one entry per call and writes agent-runs/timing/<turn>.json when the turn ends. Raw numbers only: percentiles and shares stay offline, so a broken measurement can at worst lose one file and never a turn.
  • scripts/bench_turn_timing.py reads those files and prints the turn's wall clock, call time and share, start-up and its share of the turn and of calls, the unaccounted remainder (model thinking plus orchestration), and P50/P90 of one call.
  • docs/development/agent-timing.md (+ zh-CN) records what is measured, how to read it, and the bands below.

Decision bands

Shares use the turn's wall clock, not the call count: batching already lowered the count, and a cheap call repeated many times is a different problem from an expensive one repeated a few times.

Start-up share of the turn Decision
> 40% replace the CLI transport with a native channel
20–40% run a native channel alongside the CLI
< 20% keep the transport and cut calls and probes instead

When more than half the turn is outside tool calls, fewer turns and fewer discovery probes pay before any transport change does. A runtime that reports no start-up leaves the question open rather than answered: unknown is not zero, and the report says so instead of printing 0.

The bands are advisory and stay out of CI. Timing assertions inherit the flakiness of network, machine load and provider latency; evidence belongs in a report, not in a gate. The repository already has this convention for tests/browser/reference_drag_performance.mjs ("Diagnostic CPU profiles to /tmp; no pass/fail thresholds").

What does not change

  • conversation.json keeps the shape it had: timing is stripped before it reaches the activity list, so the 64 KB the CLI reads back does not grow. A turn with ~950 tool events is already at that edge.
  • No user-visible behaviour, no new command, no new query type, no ceremony in the reply.
  • Nothing is cached, batched, or skipped: this PR only observes.

Validation

  • tests/test_agent_timing.py — a running then finished call folds into one entry; a runtime without transport timing keeps call time but reports start-up as unknown; events without identity are ignored; the ledger lands beside the other runtime state; an unwritable ledger never raises; the transport reports start-up through a real unix socket and drops a clock disagreement.
  • tests/test_bench_turn_timing.py — pins the three bands and the "most of the turn is outside tool calls" note to the turn's wall clock, and reads back what a turn actually wrote.
  • tests/test_assistant_conversations.py::test_a_turn_writes_its_timing_beside_its_runtime_state — a real turn through the API writes the ledger, and the persisted turn contains no timing.

Not in this PR

  • Commit-anchored per-commit TTFA and per-job TTC samples (they need head() before and after each tool event, plus the visibility and decode anchors).
  • The synchronization segment (R4): 954 full /canvas refreshes per task is currently invisible to the server.
  • A real-model baseline: codex returns no model list and jiuwenswarm exceeds 900 s in this environment, so the first numbers will come from replay rather than a live provider. The report states the model time as unaccounted rather than pretending it is measured.

@github-actions github-actions Bot added area:agent Agent runtime, assistant chat and tools area:performance Performance and responsiveness / 性能与响应速度 type:feat New capability or behaviour labels Nov 23, 2026
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

全量 Python 套件在本机 worktree 的结果,附基线对照,避免把环境问题读成回归:

  • pytest tests -q(base dfe61c67 + 本 PR):2882 passed, 118 skipped, 11 failed, 3654 s。
  • 11 个失败里 10 个是 tests/test_native_runtime.py 需要真实 _bundled CLI/运行时的用例。在未改动的 base commit 上同样失败(test_cli_bridge_preserves_utf8_with_legacy_stdio_encoding 在干净 worktree 里也是 subprocess.TimeoutExpired after 10 seconds)⇒ 环境缺件,与本改动无关。
  • 剩下 1 个 tests/test_creation_node_versions.py::test_active_job_blocks_version_application_and_pin_subject_expansion_keeps_roles 在全量顺序下失败,单独跑 1 passed;本 PR 未触碰 job/version 逻辑。
  • 直接相关的套件:test_agent_timing.py + test_bench_turn_timing.py 16 passed;test_cli.py / test_agent_gateway.py / test_agent_metadata.py / test_agent_citations.py / test_agent_artifacts.py 77 passed;test_assistant_conversations.py + test_assistant_conversation_trace.py 35 passed(含新增的 timing 落盘用例)。

Comment thread packages/core/src/opendirector/cli.py Outdated
connection.connect(self.gateway["OPENDIRECTOR_AGENT_SOCKET"])
connection.sendall((json.dumps({
"id": str(identity or uuid4()), "cliCommand": self.command, "projectId": str(self.project) if self.project else None, "name": name, "arguments": arguments,
"timing": {"startedAt": STARTED, "sentAt": time.monotonic()},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

job wait reuses the process start timestamp on every poll, so later polls count earlier waits as CLI startup. Please start timing before the CLI imports and count startup once per process.

@Zhangbo-cn Zhangbo-cn Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3b04a604. STARTED now sits above the CLI's imports, and each request carries timing.firstCall. _spawn() charges start-up only for the process's first request and reports spawn: 0.0 for the warm ones after it, so one job wait is billed once no matter how many windows it polls.

Checked end to end against a real CLI subprocess and a fake gateway: job wait --timeout 2.5 sent 4 polls with spawns [0.734, 0.0, 0.0, 0.0]. Before the change those read 0.7, 1.7, 2.7, 3.7 — the whole poll loop billed as start-up.

Comment thread scripts/bench_turn_timing.py Outdated

def report(turns):
calls = [call for turn in turns for call in turn.get('calls', [])]
durations = [call['endedAt'] - call['startedAt'] for call in calls if 'endedAt' in call]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a 10 s replay, an 8 s Bash call containing a 6 s CLI call reports 140% tool time and −4 s unaccounted. Please use the union of call intervals for wall-clock shares and include CLI startup in the call duration used to calculate its share.

@Zhangbo-cn Zhangbo-cn Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3b04a604. call_interval() stretches each call back by the start-up it paid for, and union_seconds() merges nested intervals, so wall-clock shares now count covered time once. callSeconds is the union; callSecondsSum and overlapSeconds keep the double count visible instead of hiding it inside one number.

Your replay now reads, in a 10 s turn: callSeconds 8.0 (was 14.0), callShare 0.8 (was 1.4), unaccountedSeconds 2.0 (was −4.0). Pinned in tests/test_bench_turn_timing.py::test_nested_calls_do_not_report_more_tool_time_than_the_turn and ::test_a_call_is_charged_the_start_up_it_paid_for.

times is not the same problem as an expensive one repeated a few times.
"""
share = numbers['spawnShareOfTurn']
if share is None or not numbers['turnSeconds']:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a manual project show turn, the --help invocations bypassed the gateway, leaving their startup time unmeasured. Please report the transport recommendation as inconclusive when startup coverage is unknown.

@Zhangbo-cn Zhangbo-cn Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3b04a604. The report now prints startupCoverage (decomposed calls ÷ calls), and verdict() returns inconclusive while it is below 1: a call that never reached the transport still started a process, so the uncovered start-up could move the band in either direction.

A project show turn with one --help probe now reports inconclusive: launch timing covers 1 of 2 calls, so start-up cannot be ruled in or out; a call that never reaches the transport still starts a process, and its start-up went unmeasured instead of picking a transport. Turns where every call goes through the transport still land in the pre-registered bands, which is what the existing band tests pin. Both docs say this: docs/development/agent-timing{,.zh-CN}.md.

@kunkunblueberry

Copy link
Copy Markdown
Collaborator

PASS f3d03bb Refs #449

T5's first step: one turn reports where its time went, and the bands that turn the numbers into a decision are pre-registered rather than chosen after seeing results. I reviewed the code, not the description.

  • agent/timing.py keeps raw numbers only. note() folds the running and terminal events of one call into one entry; a runtime without transport timing keeps call time and reports decomposed: 0 rather than a fabricated zero, and bench_turn_timing.py returns None for every share it cannot compute, so unknown stays unknown instead of reading as "start-up is free".
  • cli_transport._spawn drops a clock disagreement (0 <= spawn < 600) instead of poisoning the turn's totals, and the final event carries work measured host-side from request receipt.
  • The ledger never enters turn history: agent.py strips timing from the activity list before events.put, and test_a_turn_writes_its_timing_beside_its_runtime_state asserts 'timing' not in json.dumps(saved['tools']) on a real turn through the API. The 64 KB CLI readback does not grow.
  • write() is called in finally under if accepted: and returns None on OSError, so an unwritable ledger cannot cost a reply.
  • Bilingual docs ship together: agent-timing.md and agent-timing.zh-CN.md, with the index entry in docs/README.md. No user-visible string changed, so no demo applies here; I accepted that instead of asking for N/A text.
  • The bands use the turn's wall clock (spawnShareOfTurn) rather than the call count, which is the right denominator now that [perf] agent: answer a wait group with one query #455 lowered the count.

Two non-blocking items:

One precision note for the docs, not a defect: STARTED = time.monotonic() is anchored at cli.py import, which excludes the few milliseconds of interpreter start before that module is imported. The code comment says so honestly ("the process cannot measure its own start any other way"); the body's table says "interpreter start-up and imports", which is slightly wider than what spawn measures.

Ran: gh pr checks 469 on f3d03bb (13/13 pass: checks / python 16m5s, static, frontend, browser (assistant|isolated|voice), checks, tests, route, CodeQL); read the full diff of 11 files; verified _spawn, note, summary, write, the transport wiring, the activity-list strip, the bench script's band logic, the bilingual docs and the test assertions against the code.

Not run: the Python suite or the bench script locally. The turn-timing report has only been exercised with replayed/fake turns here; no real-model baseline exists yet, as the body states.

Coordinator: ping after this Reviewer PASS and green CI on f3d03bb. This skill does not merge.

Zhangbo-cn pushed a commit to Zhangbo-cn/OpenDirector that referenced this pull request Nov 24, 2026
Review of ThinkFlowLab#469 found three ways the timing report disagreed with itself.

- `job wait` polls in one process and sent the process start on every
  request, so poll two billed poll one's wait as start-up. The clock is
  now anchored before the CLI imports, and each request says whether it
  is the process's first; the transport charges start-up once and reports
  none for the already-warm requests that follow.
- The bench added call durations up, so a Bash call containing a CLI call
  counted the inner seconds twice: 8 s + 6 s in a 10 s turn read as 140%
  tool time with -4 s unaccounted. Wall-clock shares now use the union of
  the calls' intervals, each stretched by the start-up it paid for, and
  the sum plus overlap stay visible as `callSecondsSum` and
  `overlapSeconds`.
- A `--help` probe starts a process but never reaches the transport, so
  its start-up is unmeasured. The verdict now reports `startupCoverage`
  and calls the transport decision inconclusive instead of naming a band
  when it is below 1.

Tests pin each case; the full Python suite passes (2897 passed, 118
skipped).
dev added 2 commits November 24, 2026 15:50
## summary

- `cli.py` anchors a monotonic clock at import and reports it as
  `timing.startedAt` on every request, because interpreter start-up and
  imports finish before any request reaches the host and cannot be
  observed from there.
- `agent/cli_transport.py` converts that into `spawn` and `work` on the
  tool events it already emits, and drops an implausible value instead of
  poisoning the turn's totals.
- `agent/timing.py` folds tool events into one entry per call and writes
  `agent-runs/timing/<turn>.json` at turn end. The ledger keeps per-call
  numbers plus one aggregate; shares across turns stay offline, and a
  failed write loses a file rather than a turn.
- `apps/api` keeps `timing` out of the activity list so the persisted
  conversation keeps the shape it had: a turn with hundreds of tool events
  already sits at the 64 KB the CLI reads back.
- `scripts/bench_turn_timing.py` reads the ledgers and reports the turn's
  wall clock, call time and its share, start-up and its share of the turn
  and of calls, the unaccounted remainder, and P50/P90 of one call.
- `docs/development/agent-timing{,.zh-CN}.md` record what is measured, how
  to read it, and the pre-registered bands: start-up above 40% of the turn
  replaces the CLI transport, 20-40% runs a native channel alongside it,
  below 20% keeps the transport and cuts calls and probes instead. The
  bands stay out of CI; timing assertions inherit machine and provider
  jitter.

Measured at `dfe61c67`: `opendirector --help` costs 1.16 s of which 0.85 s
is imports, and the ThinkFlowLab#449 trace's 1,224 tool calls put the start-up floor at
23.7 minutes without saying what share of the turn that is. This change
turns the floor into a share before any transport work starts.
Review of ThinkFlowLab#469 found three ways the timing report disagreed with itself.

- `job wait` polls in one process and sent the process start on every
  request, so poll two billed poll one's wait as start-up. The clock is
  now anchored before the CLI imports, and each request says whether it
  is the process's first; the transport charges start-up once and reports
  none for the already-warm requests that follow.
- The bench added call durations up, so a Bash call containing a CLI call
  counted the inner seconds twice: 8 s + 6 s in a 10 s turn read as 140%
  tool time with -4 s unaccounted. Wall-clock shares now use the union of
  the calls' intervals, each stretched by the start-up it paid for, and
  the sum plus overlap stay visible as `callSecondsSum` and
  `overlapSeconds`.
- A `--help` probe starts a process but never reaches the transport, so
  its start-up is unmeasured. The verdict now reports `startupCoverage`
  and calls the transport decision inconclusive instead of naming a band
  when it is below 1.

Tests pin each case; the full Python suite passes (2897 passed, 118
skipped).
@kunkunblueberry

Copy link
Copy Markdown
Collaborator

PASS 3b04a60 Refs #449

Supersedes my PASS at f3d03bb: the tip moved to a rebase plus [bugfix] agent: charge CLI start-up to the call that paid it, so I re-read the new commit instead of carrying the old verdict over. All three fixes are correct and each is pinned by a test:

  • cli.py now anchors STARTED before the first import and sets timing.firstCall, so spawn finally includes import time and a polling command is billed start-up once. _spawn returns 0.0 for firstCall: false. test_start_up_is_counted_once_per_process drives two requests through a real unix socket and asserts 1.4 <= spawn < 10 then 0.0.
  • The bench sums the union of call intervals instead of raw durations, so a nested Bash → CLI call no longer double counts. test_nested_calls_do_not_report_more_tool_time_than_the_turn pins 8 s covered, 14 s summed, 6 s overlap and a positive remainder — that is exactly the 140% / −4 s contradiction the old reader produced.
  • startupCoverage keeps the band decision honest: a --help probe starts a process nobody timed, so the verdict says "inconclusive" instead of naming a band. test_calls_without_launch_timing_make_the_transport_decision_inconclusive asserts replace the CLI transport is absent.

Two follow-ups, both in the advisory report path only — nothing here changes turn behaviour, and I am not holding the merge for them:

  1. bench_turn_timing.report() unions intervals across every turn it loads, but startedAt/endedAt are time.monotonic() in the API process, and that base resets when the host restarts. Ledgers written before and after a restart are not comparable, so a union across them can merge unrelated intervals and push unaccountedSeconds negative again — the case this commit just fixed. Union per turn and then sum, or record a process/monotonic epoch in the ledger.
  2. cli.py sets _STARTUP_REPORTED = True before sendall, so if a process's first request fails to send, the later requests report firstCall: false and spawn: 0.0. That understates start-up and still counts the call as decomposed in startupCoverage. Setting the flag after the send succeeds would be closer to what the field means.

Ran: gh pr checks 469 on 3b04a60 (13/13 pass: checks / python 15m47s, static, frontend, browser (assistant|isolated|voice), checks, tests, route, CodeQL); read the full diff of the new commit (cli_transport.py, cli.py, scripts/bench_turn_timing.py, both agent-timing docs, two test files) and checked the arithmetic of call_interval/union_seconds against the pinned expectations.

Not run: the Python suite or the bench script locally; the numbers in the body come from replay, not a live provider, as the body states.

Coordinator: this is the PASS for the current tip; merging is handled separately.

@kunkunblueberry
kunkunblueberry merged commit 2edf77d into ThinkFlowLab:main Nov 24, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent runtime, assistant chat and tools area:performance Performance and responsiveness / 性能与响应速度 type:feat New capability or behaviour

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants