From f3d03bb95cca7716480e43fd4ebec201db863c4c Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 23 Nov 2026 18:09:49 +0800 Subject: [PATCH] [perf] agent: record where a turn spends its time (#449) ## 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/.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 #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. --- apps/api/src/opendirector_api/agent.py | 12 +- docs/README.md | 1 + docs/development/agent-timing.md | 35 ++++ docs/development/agent-timing.zh-CN.md | 35 ++++ .../src/opendirector/agent/cli_transport.py | 23 ++- .../core/src/opendirector/agent/timing.py | 76 +++++++++ packages/core/src/opendirector/cli.py | 7 + scripts/bench_turn_timing.py | 105 ++++++++++++ tests/test_agent_timing.py | 155 ++++++++++++++++++ tests/test_assistant_conversations.py | 28 ++++ tests/test_bench_turn_timing.py | 74 +++++++++ 11 files changed, 548 insertions(+), 3 deletions(-) create mode 100644 docs/development/agent-timing.md create mode 100644 docs/development/agent-timing.zh-CN.md create mode 100644 packages/core/src/opendirector/agent/timing.py create mode 100644 scripts/bench_turn_timing.py create mode 100644 tests/test_agent_timing.py create mode 100644 tests/test_bench_turn_timing.py diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index b6181b108..f024ea7cf 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -5,6 +5,7 @@ import json import logging from pathlib import Path +import time from typing import Annotated, Literal from uuid import UUID, uuid5 @@ -19,6 +20,7 @@ from opendirector.agent.citations import referenced_sources, with_trace_sources from opendirector.agent.runtime import AgentRuntimes, runtime_available, configured_runtimes, runtime_spec, runtime_catalog, runtime_status from opendirector.agent.skills import skills +from opendirector.agent import timing as agent_timing from opendirector.domain.projects import ProjectError from opendirector.application.model_availability import requests_for from opendirector.domain.rule_facts import MAX_REFERENCES, PROMPT_MAX_LENGTH @@ -473,6 +475,8 @@ def validate_connection(): async def produce() -> None: text, status, error, accepted = '', 'complete', None, False activities = [] + timing = {} + turn_started = time.monotonic() sources = {} previous_sources = {} plan = None @@ -527,8 +531,11 @@ async def produce() -> None: if event['type'] == 'plan': plan = event['entries'] if event['type'] == 'tool': + agent_timing.note(timing, event) previous = next((item for item in activities if item['id'] == event['id']), None) - activity = {**{key: item for key, item in event.items() if key != 'type'}, + # `timing` is measurement, not history: keeping it out of the + # activity list keeps the persisted turn the same shape it was. + activity = {**{key: item for key, item in event.items() if key not in {'type', 'timing'}}, 'textOffset': previous['textOffset'] if previous else len(text)} if previous is None: activities.append(activity) @@ -553,7 +560,10 @@ async def produce() -> None: status=500, code='operation_rejected') logger.exception(f'agent.turn.failed project_id={project_id} turn_id={value.id}') finally: + # Measurement is best effort: losing the ledger is acceptable, + # losing the turn's reply is not. if accepted: + agent_timing.write(directory, value.id, timing, round(time.monotonic() - turn_started, 3)) for activity in activities: if activity['status'] == 'running': activity['status'] = 'interrupted' diff --git a/docs/README.md b/docs/README.md index 3c224ce6a..bbe67662c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ This directory is the entry point for the repository's shared documentation. The | [Capability mapping contract](architecture/capability-contract.md) | Evidenced upstream vocabulary, the `(operation, profile) → capability` table, the untranslatable declarations, and how it feeds discovery | Upstream vocabulary, capability ids, or discovery matching change | | [Roadmap](development/roadmap.md) | Capability dependencies and delivery criteria | Scope, dependencies, or acceptance criteria change | | [Validation guide](development/validation.md) | Reproducible checks and evidence requirements | Tools, runtime requirements, or validation entry points change | +| [Agent turn timing](development/agent-timing.md) ([中文](development/agent-timing.zh-CN.md)) | Where one agent turn spends its time, and the pre-registered bands that decide the next optimization | The ledger, its reader, or a decision band changes | | [CI layer assessment](development/ci-layer-assessment.md) | Timing evidence, critical PR representatives and staged Python classification | Measured evidence or classification decisions change | | [Issue #87 Windows handoff](development/issue-87-windows-handoff.md) ([中文](development/issue-87-windows-handoff.zh-CN.md)) | Native ACL repair and final text acceptance | The shared checkpoint or native validation scope changes | | [Development lessons](development/lessons.md) | Risks identified from recent fixes | New evidence emerges or a lesson no longer applies | diff --git a/docs/development/agent-timing.md b/docs/development/agent-timing.md new file mode 100644 index 000000000..050a4a07a --- /dev/null +++ b/docs/development/agent-timing.md @@ -0,0 +1,35 @@ +# Agent turn timing + +Each agent turn records where its time went. Optimizing the tool channel or the model loop without that split is guesswork, and the split did not exist: the trace carried events but no timestamps. + +## What is recorded + +- The business CLI reports its own start on every request (`timing.startedAt`). This is the only way to see interpreter start-up and imports: the host only sees the request that arrives after them. +- The transport turns that into `spawn` (start-up) and `work` (the command itself) on the tool events it already emits. A runtime whose tool calls never reach that transport reports neither, and the ledger then keeps one call's wall time alone. +- The API layer folds tool events into one entry per call, keyed by call identity, and writes `agent-runs/timing/.json` once when the turn ends. + +The ledger keeps the per-call numbers and one aggregate per turn. Shares across turns stay offline, so a broken measurement can at worst lose one file; it can never fail a turn. + +Raw numbers deliberately do not go into conversation history: a turn with hundreds of tool events already fills the 64 KB the CLI reads back, and two timestamps per event would make that worse. + +## Reading it + +```sh +python3 scripts/bench_turn_timing.py --project [--json] +``` + +The report prints, per project: the turn's wall clock, call time and its share, start-up and its share of the turn and of calls, the unaccounted remainder (model thinking plus orchestration), and the P50 and P90 of one call. + +## 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; 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 at all leaves the question open rather than answered: unknown is not zero. + +These bands are advisory and stay out of CI. Timing assertions would inherit the flakiness of network, machine load and provider latency; recorded evidence belongs in reports, not in gates. diff --git a/docs/development/agent-timing.zh-CN.md b/docs/development/agent-timing.zh-CN.md new file mode 100644 index 000000000..7c09aa37c --- /dev/null +++ b/docs/development/agent-timing.zh-CN.md @@ -0,0 +1,35 @@ +# Agent 单轮耗时 + +每个 Agent 单轮都会记录时间去向。没有这个分布,优化工具通道或模型循环都只能靠猜;而这个分布此前并不存在——trace 里有事件,但没有时间戳。 + +## 记录内容 + +- 业务 CLI 在每次请求里自报启动时刻(`timing.startedAt`)。这是唯一能看见解释器启动与 import 的方式:宿主机只能看到在这些之后才到达的请求。 +- 传输层把它折算成工具事件上已有的 `spawn`(启动)与 `work`(命令本身)。工具调用不经过该传输的运行时两者都没有,此时账本只保留该次调用的墙钟时长。 +- API 层按调用标识把工具事件折叠成一条,在本轮结束时写一次 `agent-runs/timing/.json`。 + +账本保存逐次调用的数字,外加每轮一份汇总。跨轮的占比留给离线分析,因此测量损坏最多丢一个文件,绝不会让一轮失败。 + +原始数字刻意不写进对话历史:数百个工具事件的单轮已经占满 CLI 回读的 64 KB,每个事件再加两个时间戳只会更糟。 + +## 读取方式 + +```sh +python3 scripts/bench_turn_timing.py --project <项目目录> [--json] +``` + +报告给出:整轮墙钟、调用总时长及其占比、启动时长及其占整轮与占调用的比例、未计入部分(模型思考与编排),以及单次调用的 P50 与 P90。 + +## 判据 + +占比以整轮墙钟为分母,而不是调用次数:批量已经压低了次数,而"便宜但重复很多次"与"昂贵但重复很少次"是两个不同的问题。 + +| 启动占整轮比例 | 决定 | +| --- | --- | +| > 40% | 用原生通道替换 CLI 传输。 | +| 20–40% | 原生通道与 CLI 并行。 | +| < 20% | 保留传输通道,转而减少调用与探测。 | + +当超过一半时间落在工具调用之外时,减少轮次与探测的收益先于任何传输层改动。根本不报告启动耗时的运行时是把问题留作未决,而不是已回答:未知不等于零。 + +这些判据只作参考,不进入 CI。计时断言会继承网络、机器负载与服务商延迟的抖动;证据写进报告,不写进门槛。 diff --git a/packages/core/src/opendirector/agent/cli_transport.py b/packages/core/src/opendirector/agent/cli_transport.py index 20e949390..4eb3d4e10 100644 --- a/packages/core/src/opendirector/agent/cli_transport.py +++ b/packages/core/src/opendirector/agent/cli_transport.py @@ -6,6 +6,7 @@ from pathlib import Path import shlex import sys +import time from opendirector.domain.projects import ProjectError @@ -26,6 +27,20 @@ def environment(work, socket, bridge_env=None): return env +def _spawn(timing): + """How long the CLI spent starting up before it asked for the command. + + Only the CLI can see its own start, so this arrives in the request. An + impossible value means the two clocks disagree and is dropped rather than + poisoning the turn's totals. + """ + started = timing.get('startedAt') if isinstance(timing, dict) else None + if not isinstance(started, (int, float)): + return None + spawn = round(time.monotonic() - started, 3) + return spawn if 0 <= spawn < 600 else None + + async def start_server(gateway, queue, endpoint, pending): async def connection(reader, writer): task = asyncio.current_task() @@ -33,14 +48,17 @@ async def connection(reader, writer): try: try: request = json.loads(await asyncio.wait_for(reader.readline(), 15)) + received = time.monotonic() if gateway.closed: raise ProjectError('Agent run is closed', 409) if request.get('projectId') and request['projectId'] != str(gateway.run.project_id): raise ProjectError('CLI project does not match the active agent project.', 403) key, name, arguments = str(request['id']), request['name'], request.get('arguments', {}) display_name = request['cliCommand'] + spawn = _spawn(request.get('timing')) await queue.put({'type': 'tool', 'id': 'cli:' + key, 'name': display_name, - 'status': 'running', 'arguments': arguments}) + 'status': 'running', 'arguments': arguments, + **({'timing': {'spawn': spawn}} if spawn is not None else {})}) outcome = await gateway.call('cli:' + key, name, arguments) response = {'value': outcome.value, 'error': outcome.error} if outcome.error and isinstance(outcome.value, dict) and isinstance(outcome.value.get('code'), str): @@ -48,7 +66,8 @@ async def connection(reader, writer): detail = json.dumps(outcome.value, ensure_ascii=False, indent=2) await queue.put({**outcome.event(display_name), 'id': 'cli:' + key, 'arguments': arguments, 'result': detail[:65536], - 'resultTruncated': len(detail) > 65536}) + 'resultTruncated': len(detail) > 65536, + 'timing': {'spawn': spawn, 'work': round(time.monotonic() - received, 3)}}) except (ProjectError, ValueError, KeyError, OSError, TimeoutError) as failure: response = {'error': str(failure)} writer.write(json.dumps(response, ensure_ascii=False).encode() + b'\n') diff --git a/packages/core/src/opendirector/agent/timing.py b/packages/core/src/opendirector/agent/timing.py new file mode 100644 index 000000000..4a6baf5a6 --- /dev/null +++ b/packages/core/src/opendirector/agent/timing.py @@ -0,0 +1,76 @@ +"""Turn-scoped measurement of one agent run. + +The turn's time goes into native model thinking, tool calls, and the project +synchronization each tool call triggers. Optimizing any of them needs their +share of the turn, which nothing currently records. + +The ledger is written once per turn under `agent-runs/`, beside the other +runtime state, rather than into conversation history: a turn with ~950 tool +events already fills the 64 KB the CLI reads back, and adding two timestamps +per event would make that worse. The ledger keeps the per-call numbers and one +aggregate per turn; shares across turns belong to offline analysis, so a broken +measurement can at most lose one file and never a turn. +""" +from __future__ import annotations + +import json +from pathlib import Path +import time + +TERMINAL = frozenset({'complete', 'failed', 'interrupted'}) + + +def note(ledger, event): + """Fold one tool event into the turn's ledger. + + The transport reports how much of a call was CLI start-up (`spawn`) and how + much was the command itself (`work`); a runtime that only sees tool events + reports neither, and the ledger then keeps the call's wall time alone. + """ + key = event.get('id') + if not isinstance(key, str): + return + now = time.monotonic() + entry = ledger.get(key) + if entry is None: + entry = ledger[key] = {'id': key, 'name': event.get('name'), 'startedAt': now} + entry['status'] = event.get('status') or entry.get('status', 'running') + timing = event.get('timing') + if isinstance(timing, dict): + entry.update({name: timing[name] for name in ('spawn', 'work') + if isinstance(timing.get(name), (int, float))}) + if entry['status'] in TERMINAL: + entry['endedAt'] = now + + +def _percentile(values, fraction): + if not values: + return None + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(len(ordered) * fraction))] + + +def summary(ledger, turn_seconds=None): + """Aggregate the ledger into the numbers a comparison needs.""" + durations = [entry['endedAt'] - entry['startedAt'] for entry in ledger.values() if 'endedAt' in entry] + spawns = [entry['spawn'] for entry in ledger.values() if 'spawn' in entry] + works = [entry['work'] for entry in ledger.values() if 'work' in entry] + return {'calls': len(ledger), 'measured': len(durations), + 'turnSeconds': turn_seconds, 'callSeconds': round(sum(durations), 3), + 'spawnSeconds': round(sum(spawns), 3), 'workSeconds': round(sum(works), 3), + 'decomposed': len(spawns), + 'p50Seconds': _percentile(durations, 0.5), 'p90Seconds': _percentile(durations, 0.9)} + + +def write(directory, turn_id, ledger, turn_seconds): + """Persist the turn's raw numbers, never at the cost of the turn itself.""" + if not ledger: + return None + path = Path(directory) / 'agent-runs' / 'timing' / f'{turn_id}.json' + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({'summary': summary(ledger, turn_seconds), + 'calls': list(ledger.values())}, ensure_ascii=False), encoding='utf-8') + return path + except OSError: + return None diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 5824189b1..b572c523f 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -11,6 +11,7 @@ import shlex import subprocess import sys +import time from typing import Annotated, Literal from urllib.parse import quote from uuid import UUID, uuid4, uuid5 @@ -25,6 +26,11 @@ from opendirector.domain.projects import ProjectError from opendirector.domain.timeline_errors import timeline_error, timeline_error_message +# The agent measures how much of a tool call is interpreter start-up and import +# time. Anchoring the clock at import lets it separate that from the command's +# own work; the process cannot measure its own start any other way. +STARTED = time.monotonic() + app = typer.Typer(no_args_is_help=True, help="Start OpenDirector and create or edit projects.", epilog="Run opendirector COMMAND --help for subcommands and usage. " "Place --project, --url and other global options before the command.") @@ -181,6 +187,7 @@ def call(self, name, arguments, *, identity=None): 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()}, }) + "\n").encode()) with connection.makefile("rb") as reader: response = json.loads(reader.readline(64 * 1024 * 1024)) diff --git a/scripts/bench_turn_timing.py b/scripts/bench_turn_timing.py new file mode 100644 index 000000000..e0ba73c1a --- /dev/null +++ b/scripts/bench_turn_timing.py @@ -0,0 +1,105 @@ +"""Report where one agent run spends its time. + +Every turn writes `agent-runs/timing/.json` with raw numbers only, so the +percentages below never live in the hot path. Run this after a task to decide +which cost dominates: start-up of the business CLI, the command itself, or the +part of a tool call that the runtime reports but cannot decompose. + + python3 scripts/bench_turn_timing.py --project ~/path/to/project [--json] +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import statistics +import sys + + +def load(project): + directory = Path(project).expanduser() / 'agent-runs' / 'timing' + turns = [] + for path in sorted(directory.glob('*.json')) if directory.is_dir() else []: + try: + turns.append(json.loads(path.read_text(encoding='utf-8'))) + except (OSError, ValueError): + continue + return turns + + +def percentile(values, fraction): + if not values: + return None + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(len(ordered) * fraction))] + + +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] + spawns = [call['spawn'] for call in calls if isinstance(call.get('spawn'), (int, float))] + works = [call['work'] for call in calls if isinstance(call.get('work'), (int, float))] + turn_seconds = sum(turn['summary'].get('turnSeconds') or 0 for turn in turns) + measured = sum(durations) + return { + 'turns': len(turns), + 'turnSeconds': round(turn_seconds, 2), + 'calls': len(calls), + 'measurableCalls': len(durations), + 'decomposedCalls': len(spawns), + 'callSeconds': round(measured, 2), + 'callShare': round(measured / turn_seconds, 3) if turn_seconds else None, + 'spawnSeconds': round(sum(spawns), 2), + # A runtime that cannot see start-up is unknown, not zero: reporting 0 + # would read as "start-up is free" and settle the decision wrongly. + 'spawnShareOfCalls': round(sum(spawns) / measured, 3) if spawns and measured else None, + 'spawnShareOfTurn': round(sum(spawns) / turn_seconds, 3) if spawns and turn_seconds else None, + 'workSeconds': round(sum(works), 2), + 'p50Seconds': percentile(durations, 0.5), + 'p90Seconds': percentile(durations, 0.9), + 'unaccountedSeconds': round(turn_seconds - measured, 2), + 'unaccountedShare': round((turn_seconds - measured) / turn_seconds, 3) if turn_seconds else None, + } + + +def verdict(numbers): + """Name the dominant cost, so the next change has one target. + + The bands were pre-registered from the turn's wall clock, not from the call + count: batching already lowered the count, and a cheap call repeated many + 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']: + return 'no turn recorded launch timing yet, so start-up cannot be ruled in or out' + if share > 0.4: + decision = 'start-up dominates the turn: replace the CLI transport (R1)' + elif share > 0.2: + decision = 'start-up matters but does not dominate: run a native channel alongside the CLI' + else: + decision = 'start-up is not the problem: keep the CLI transport and cut calls instead' + if (numbers['unaccountedShare'] or 0) > 0.5: + decision += '; most of the turn is outside tool calls, so fewer turns and probes pay first' + elif (numbers['spawnShareOfCalls'] or 0) > 0.4: + decision += '; start-up still dominates each call, so batching pays inside the channel too' + return decision + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--project', required=True, help='Project directory holding agent-runs/timing.') + parser.add_argument('--json', action='store_true', help='Print the numbers as JSON.') + options = parser.parse_args(argv) + turns = load(options.project) + numbers = report(turns) + numbers['verdict'] = verdict(numbers) + if options.json: + print(json.dumps(numbers, ensure_ascii=False, indent=2)) + else: + for name, value in numbers.items(): + print(f'{name:24} {value}') + return 0 if turns else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/test_agent_timing.py b/tests/test_agent_timing.py new file mode 100644 index 000000000..71e101e63 --- /dev/null +++ b/tests/test_agent_timing.py @@ -0,0 +1,155 @@ +import asyncio +import json +from types import SimpleNamespace +import time +from uuid import uuid4 + +import pytest + +from capabilities import requires_posix + +from opendirector.agent import timing +from opendirector.agent.cli_transport import start_server + + +def test_a_running_then_finished_call_becomes_one_ledger_entry(): + ledger = {} + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'generation.submit', 'status': 'running', + 'timing': {'spawn': 1.2}}) + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'generation.submit', 'status': 'complete', + 'timing': {'spawn': 1.2, 'work': 0.4}}) + assert list(ledger) == ['cli:1'] + entry = ledger['cli:1'] + assert entry['status'] == 'complete' + assert (entry['spawn'], entry['work']) == (1.2, 0.4) + assert entry['endedAt'] >= entry['startedAt'] + + +def test_a_runtime_without_transport_timing_still_records_call_time(): + ledger = {} + timing.note(ledger, {'type': 'tool', 'id': 'deepseek:a', 'name': 'bash', 'status': 'running'}) + timing.note(ledger, {'type': 'tool', 'id': 'deepseek:a', 'name': 'bash', 'status': 'complete'}) + summary = timing.summary(ledger, turn_seconds=3.0) + assert summary['calls'] == 1 and summary['measured'] == 1 + assert summary['decomposed'] == 0 + assert summary['spawnSeconds'] == 0 + + +def test_events_without_identity_are_ignored(): + ledger = {} + timing.note(ledger, {'type': 'tool', 'name': 'bash', 'status': 'complete'}) + assert ledger == {} + + +def test_summary_separates_call_time_from_start_up_and_work(): + ledger = {} + for index, spawn in enumerate([1.0, 1.2, 1.4]): + timing.note(ledger, {'type': 'tool', 'id': f'cli:{index}', 'name': 'read_project', + 'status': 'running', 'timing': {'spawn': spawn}}) + timing.note(ledger, {'type': 'tool', 'id': f'cli:{index}', 'name': 'read_project', + 'status': 'complete', 'timing': {'spawn': spawn, 'work': 0.1}}) + ledger[f'cli:{index}']['startedAt'] = 0.0 + ledger[f'cli:{index}']['endedAt'] = 0.5 + summary = timing.summary(ledger, turn_seconds=12.0) + assert summary['calls'] == 3 and summary['measured'] == 3 + assert round(summary['spawnSeconds'], 3) == 3.6 + assert round(summary['workSeconds'], 3) == 0.3 + assert summary['callSeconds'] == 1.5 + assert summary['p50Seconds'] == summary['p90Seconds'] == 0.5 + assert summary['turnSeconds'] == 12.0 + + +def test_an_empty_turn_writes_nothing(tmp_path): + assert timing.write(tmp_path, uuid4(), {}, 1.0) is None + assert not (tmp_path / 'agent-runs').exists() + + +def test_the_ledger_lands_beside_the_other_runtime_state(tmp_path): + ledger = {} + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'bash', 'status': 'complete'}) + turn = uuid4() + path = timing.write(tmp_path, turn, ledger, 2.5) + assert path == tmp_path / 'agent-runs' / 'timing' / f'{turn}.json' + stored = json.loads(path.read_text()) + assert stored['summary']['turnSeconds'] == 2.5 + assert [call['id'] for call in stored['calls']] == ['cli:1'] + + +def test_an_unwritable_ledger_never_raises(tmp_path): + (tmp_path / 'agent-runs').write_text('not a directory') + ledger = {} + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'bash', 'status': 'complete'}) + assert timing.write(tmp_path, uuid4(), ledger, 1.0) is None + + +class _Outcome: + value = {'ok': True} + error = None + + def event(self, name): + return {'type': 'tool', 'name': name, 'status': 'complete'} + + +class _Gateway: + closed = False + + def __init__(self, project_id): + self.run = SimpleNamespace(project_id=project_id) + + async def call(self, key, name, arguments): + return _Outcome() + + +@requires_posix() +def test_the_cli_reports_its_own_start_up_through_the_transport(tmp_path): + async def scenario(): + queue = asyncio.Queue() + project = uuid4() + server, _ = await start_server(_Gateway(project), queue, str(tmp_path / 'cli.sock'), set()) + try: + reader, writer = await asyncio.open_unix_connection(str(tmp_path / 'cli.sock')) + writer.write((json.dumps({'id': '1', 'cliCommand': 'opendirector', 'projectId': str(project), + 'name': 'read_project', 'arguments': {}, + 'timing': {'startedAt': time.monotonic() - 1.5}}) + '\n').encode()) + await writer.drain() + await reader.readline() + writer.close() + await writer.wait_closed() + running = await asyncio.wait_for(queue.get(), 5) + finished = await asyncio.wait_for(queue.get(), 5) + return running, finished + finally: + server.close() + await server.wait_closed() + + running, finished = asyncio.run(scenario()) + assert 1.4 <= running['timing']['spawn'] < 10 + assert finished['timing']['spawn'] == running['timing']['spawn'] + assert finished['timing']['work'] >= 0 + + +@requires_posix() +def test_a_clock_disagreement_is_dropped_instead_of_poisoning_the_turn(tmp_path): + async def scenario(): + queue = asyncio.Queue() + project = uuid4() + server, _ = await start_server(_Gateway(project), queue, str(tmp_path / 'cli.sock'), set()) + try: + reader, writer = await asyncio.open_unix_connection(str(tmp_path / 'cli.sock')) + writer.write((json.dumps({'id': '1', 'cliCommand': 'opendirector', 'projectId': str(project), + 'name': 'read_project', 'arguments': {}, + 'timing': {'startedAt': time.monotonic() + 60}}) + '\n').encode()) + await writer.drain() + await reader.readline() + writer.close() + await writer.wait_closed() + running = await asyncio.wait_for(queue.get(), 5) + finished = await asyncio.wait_for(queue.get(), 5) + return running, finished + finally: + server.close() + await server.wait_closed() + + running, finished = asyncio.run(scenario()) + assert 'timing' not in running + assert finished['timing'] == {'spawn': None, 'work': finished['timing']['work']} diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index daa54dba4..03cb2a8d7 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -556,3 +556,31 @@ def test_plain_request_reaches_each_runtime_without_delivery_instructions(assist saved = client.get(path).json()['messages'] assert saved[0]['text'] == text assert saved[-1]['status'] == 'complete' + + +def test_a_turn_writes_its_timing_beside_its_runtime_state(assistant, monkeypatch, tmp_path): + client, path, _ = assistant + async def stream(self, run): + yield {'type': 'tool', 'id': 'cli:1', 'name': 'opendirector', 'status': 'running', + 'timing': {'spawn': 1.1}} + yield {'type': 'tool', 'id': 'cli:1', 'name': 'opendirector', 'status': 'complete', + 'timing': {'spawn': 1.1, 'work': 0.2}} + yield {'type': 'delta', 'text': '已导出。'} + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + conversation = client.get(path).json()['conversationId'] + turn = str(uuid4()) + response = client.post(path + '/turns', json={'id': turn, 'runtime': 'default', + 'conversationId': conversation, 'text': '导出视频'}) + assert response.status_code == 200, response.text + assert frames(response)[-1]['error'] is None + + ledger = json.loads(next(tmp_path.glob(f'**/agent-runs/timing/{turn}.json')).read_text(encoding='utf-8')) + assert ledger['summary']['calls'] == 1 + assert ledger['summary']['decomposed'] == 1 + assert ledger['summary']['spawnSeconds'] == 1.1 + assert ledger['calls'][0]['work'] == 0.2 + + # Measurement stays out of the turn the user and the next run read back. + saved = client.get(path).json()['messages'][-1] + assert 'timing' not in json.dumps(saved['tools']) + assert json.loads(next(tmp_path.glob('**/agent-runs/conversation.json')).read_text(encoding='utf-8'))['messages'][-1] == saved diff --git a/tests/test_bench_turn_timing.py b/tests/test_bench_turn_timing.py new file mode 100644 index 000000000..7c844b259 --- /dev/null +++ b/tests/test_bench_turn_timing.py @@ -0,0 +1,74 @@ +"""The pre-registered bands decide the next optimization, so they need a test. + +A measurement nobody can act on is worse than none: these cases pin the three +start-up bands and the "most of the turn is outside tool calls" note to the +turn's wall clock, which is what the decision was made against. +""" +import importlib.util +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('bench_turn_timing', ROOT / 'scripts/bench_turn_timing.py') +bench = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bench) + + +def turn(turn_seconds, calls): + return {'summary': {'turnSeconds': turn_seconds}, 'calls': [ + {'id': f'cli:{index}', 'name': 'opendirector', 'status': 'complete', + 'startedAt': 0.0, 'endedAt': spawn + work, 'spawn': spawn, 'work': work} + for index, (spawn, work) in enumerate(calls)]} + + +def test_start_up_above_forty_percent_of_the_turn_replaces_the_transport(): + numbers = bench.report([turn(100.0, [(1.2, 0.1)] * 40)]) + assert numbers['spawnShareOfTurn'] == 0.48 + assert 'replace the CLI transport' in bench.verdict(numbers) + + +def test_start_up_between_twenty_and_forty_percent_runs_both_channels(): + numbers = bench.report([turn(100.0, [(1.2, 0.1)] * 25)]) + assert numbers['spawnShareOfTurn'] == 0.3 + assert 'alongside the CLI' in bench.verdict(numbers) + + +def test_start_up_below_twenty_percent_keeps_the_cli_transport(): + numbers = bench.report([turn(100.0, [(1.2, 0.1)] * 10)]) + assert numbers['spawnShareOfTurn'] == 0.12 + assert 'not the problem' in bench.verdict(numbers) + + +def test_a_turn_spent_outside_tool_calls_says_so(): + numbers = bench.report([turn(100.0, [(1.2, 0.1)] * 10)]) + assert numbers['unaccountedShare'] > 0.5 + assert 'outside tool calls' in bench.verdict(numbers) + + +def test_calls_without_transport_timing_are_counted_but_not_decomposed(): + numbers = bench.report([{'summary': {'turnSeconds': 10.0}, 'calls': [ + {'id': 'deepseek:a', 'startedAt': 0.0, 'endedAt': 2.0}]}]) + assert numbers['calls'] == 1 and numbers['measurableCalls'] == 1 + assert numbers['decomposedCalls'] == 0 + assert numbers['spawnShareOfCalls'] is None + + +def test_an_empty_or_missing_directory_is_not_an_error(tmp_path): + assert bench.load(tmp_path) == [] + assert bench.main(['--project', str(tmp_path)]) == 1 + + +def test_the_report_reads_what_a_turn_writes(tmp_path): + from opendirector.agent import timing + + ledger = {} + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'read_project', + 'status': 'running', 'timing': {'spawn': 1.1}}) + timing.note(ledger, {'type': 'tool', 'id': 'cli:1', 'name': 'read_project', + 'status': 'complete', 'timing': {'spawn': 1.1, 'work': 0.2}}) + timing.write(tmp_path, '00000000-0000-0000-0000-000000000001', ledger, 5.0) + numbers = bench.report(bench.load(tmp_path)) + assert numbers['calls'] == 1 + assert numbers['decomposedCalls'] == 1 + assert numbers['spawnShareOfTurn'] == 0.22 + assert json.loads(json.dumps(numbers))['turns'] == 1