From ab19ac76f1f15b8de84b079df5e4a5af6cf83840 Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 23 Nov 2026 18:09:49 +0800 Subject: [PATCH 1/2] [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 e5bdc2405..360348613 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 @@ -26,6 +27,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.") @@ -215,6 +221,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 fac0fa4c2..dcd05498b 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -559,3 +559,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 From 3b04a6044086f010bf93509e2d63b6a485d740e6 Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 24 Nov 2026 15:42:55 +0800 Subject: [PATCH 2/2] [bugfix] agent: charge CLI start-up to the call that paid it Review of #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). --- docs/development/agent-timing.md | 6 +- docs/development/agent-timing.zh-CN.md | 6 +- .../src/opendirector/agent/cli_transport.py | 13 ++-- packages/core/src/opendirector/cli.py | 24 +++++-- scripts/bench_turn_timing.py | 65 ++++++++++++++++--- tests/test_agent_timing.py | 35 ++++++++++ tests/test_bench_turn_timing.py | 32 +++++++++ 7 files changed, 160 insertions(+), 21 deletions(-) diff --git a/docs/development/agent-timing.md b/docs/development/agent-timing.md index 050a4a07a..8b497de44 100644 --- a/docs/development/agent-timing.md +++ b/docs/development/agent-timing.md @@ -4,7 +4,7 @@ Each agent turn records where its time went. Optimizing the tool channel or the ## 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 business CLI takes its start timestamp before it imports anything, and reports it on its first request (`timing.startedAt`, `timing.firstCall`). This is the only way to see interpreter start-up and imports: the host only sees the request that arrives after them. A process's later requests report no start-up, so a command that waits in a loop is charged that cost once rather than once per poll. - 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. @@ -20,6 +20,8 @@ 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. +Call time is the union of the calls' wall-clock intervals, each stretched to include the start-up it paid for. Calls nest — a Bash call that runs the CLI contains the CLI call — so adding durations up would count the inner seconds twice and report more tool time than the turn had. `callSecondsSum` and `overlapSeconds` show that double count. + ## 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. @@ -32,4 +34,6 @@ Shares use the turn's wall clock, not the call count: batching already lowered t 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. +Choosing a band needs launch timing on every call. A call that never reached the transport, such as a `--help` probe, still started a process whose start-up nobody saw, so when `startupCoverage` is below 1 the report calls the decision inconclusive instead of naming a band. + 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 index 7c09aa37c..89ba061aa 100644 --- a/docs/development/agent-timing.zh-CN.md +++ b/docs/development/agent-timing.zh-CN.md @@ -4,7 +4,7 @@ ## 记录内容 -- 业务 CLI 在每次请求里自报启动时刻(`timing.startedAt`)。这是唯一能看见解释器启动与 import 的方式:宿主机只能看到在这些之后才到达的请求。 +- 业务 CLI 在任何 import 之前取一次启动时刻,并在自己的第一个请求里上报(`timing.startedAt`、`timing.firstCall`)。这是唯一能看见解释器启动与 import 的方式:宿主机只能看到在这些之后才到达的请求。同一进程后续的请求不再报启动,因此循环等待的命令只被计入一次启动,而不是每轮询一次就算一次。 - 传输层把它折算成工具事件上已有的 `spawn`(启动)与 `work`(命令本身)。工具调用不经过该传输的运行时两者都没有,此时账本只保留该次调用的墙钟时长。 - API 层按调用标识把工具事件折叠成一条,在本轮结束时写一次 `agent-runs/timing/.json`。 @@ -20,6 +20,8 @@ python3 scripts/bench_turn_timing.py --project <项目目录> [--json] 报告给出:整轮墙钟、调用总时长及其占比、启动时长及其占整轮与占调用的比例、未计入部分(模型思考与编排),以及单次调用的 P50 与 P90。 +调用总时长是各调用墙钟区间的并集,每个区间都补上它实际付出的启动时间。调用会嵌套——运行 CLI 的 Bash 调用包含 CLI 调用——所以把时长直接相加会把内层的时间算两遍,得出比整轮还多的工具时间。`callSecondsSum` 与 `overlapSeconds` 显示这部分重复计算。 + ## 判据 占比以整轮墙钟为分母,而不是调用次数:批量已经压低了次数,而"便宜但重复很多次"与"昂贵但重复很少次"是两个不同的问题。 @@ -32,4 +34,6 @@ python3 scripts/bench_turn_timing.py --project <项目目录> [--json] 当超过一半时间落在工具调用之外时,减少轮次与探测的收益先于任何传输层改动。根本不报告启动耗时的运行时是把问题留作未决,而不是已回答:未知不等于零。 +选档要求每次调用都有启动计时。没有经过传输的调用(例如 `--help` 探测)同样启动了进程,但它的启动没人看见,因此当 `startupCoverage` 小于 1 时,报告把结论写成未决,而不是给出某一档。 + 这些判据只作参考,不进入 CI。计时断言会继承网络、机器负载与服务商延迟的抖动;证据写进报告,不写进门槛。 diff --git a/packages/core/src/opendirector/agent/cli_transport.py b/packages/core/src/opendirector/agent/cli_transport.py index 4eb3d4e10..9e5e2f003 100644 --- a/packages/core/src/opendirector/agent/cli_transport.py +++ b/packages/core/src/opendirector/agent/cli_transport.py @@ -28,15 +28,20 @@ def environment(work, socket, bridge_env=None): def _spawn(timing): - """How long the CLI spent starting up before it asked for the command. + """How long the CLI spent starting up before it asked for this 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. + Only the CLI can see its own start, so this arrives in the request. The + process reports that start once: a command that polls in a loop sends + several requests from one process, and the second one onward are already + warm, so counting the time since the process began again would bill every + earlier poll as start-up. 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 + if not timing.get('firstCall', True): + return 0.0 spawn = round(time.monotonic() - started, 3) return spawn if 0 <= spawn < 600 else None diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 360348613..7957db4a5 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -1,4 +1,14 @@ """Command-line access to OpenDirector's shared project services.""" +import time + +# The agent measures how much of a tool call is interpreter start-up and import +# time, so the clock has to be anchored before the imports below: anchoring it +# after them would hide the very cost being measured. It stays anchored there +# for the whole process, and each request says whether it is the process's +# first, because a command that waits in a loop must not bill its earlier waits +# as start-up. +STARTED = time.monotonic() + from contextlib import redirect_stdout from enum import Enum from hashlib import sha256 @@ -11,7 +21,6 @@ import shlex import subprocess import sys -import time from typing import Annotated, Literal from urllib.parse import quote from uuid import UUID, uuid4, uuid5 @@ -27,10 +36,9 @@ 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() +# Set once this process has told the transport how it started, so later requests +# from the same process are not charged that start-up again. +_STARTUP_REPORTED = False 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. " @@ -210,6 +218,7 @@ def path(self, suffix=""): return f"/api/creation/projects/{self.project}{suffix}" def call(self, name, arguments, *, identity=None): + global _STARTUP_REPORTED if not self.live: raise ProjectError("This operation requires an active agent execution context.") endpoint = self.gateway.get("OPENDIRECTOR_AGENT_HOST") @@ -219,9 +228,11 @@ def call(self, name, arguments, *, identity=None): connection.settimeout(SOCKET_TIMEOUT) if not endpoint: connection.connect(self.gateway["OPENDIRECTOR_AGENT_SOCKET"]) + first = not _STARTUP_REPORTED + _STARTUP_REPORTED = True 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()}, + "timing": {"startedAt": STARTED, "sentAt": time.monotonic(), "firstCall": first}, }) + "\n").encode()) with connection.makefile("rb") as reader: response = json.loads(reader.readline(64 * 1024 * 1024)) @@ -766,7 +777,6 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg help="Generation job IDs. Omit them with --all.")] = None, all_jobs: Annotated[bool, typer.Option("--all", help="Wait for every unfinished job in this project.")] = False, timeout: Annotated[float, typer.Option(min=0, help="Maximum wait in seconds.")] = 300): - import time ctx.obj.command = ctx.command_path if not job_ids and not all_jobs: raise typer.BadParameter("Pass job IDs or --all.") diff --git a/scripts/bench_turn_timing.py b/scripts/bench_turn_timing.py index e0ba73c1a..8f58f273c 100644 --- a/scripts/bench_turn_timing.py +++ b/scripts/bench_turn_timing.py @@ -34,31 +34,76 @@ def percentile(values, fraction): return ordered[min(len(ordered) - 1, int(len(ordered) * fraction))] +def call_interval(call): + """The wall-clock interval one call occupied, start-up included. + + A CLI call's ledger entry starts when the host sees the request, which is + after the interpreter started. Counting its start-up means stretching the + interval back by that much, so the call is charged the seconds it really + took instead of only the part the host could see. + """ + started = call.get('startedAt') + ended = call.get('endedAt') + if not isinstance(started, (int, float)) or not isinstance(ended, (int, float)): + return None + spawn = call['spawn'] if isinstance(call.get('spawn'), (int, float)) else 0.0 + work = call['work'] if isinstance(call.get('work'), (int, float)) else 0.0 + seconds = max(ended - started, spawn + work) + return ended - seconds, ended + + +def union_seconds(intervals): + """Wall time covered by at least one call. + + Calls nest: a runtime Bash call that runs the CLI contains the CLI call, so + adding durations up would count the inner seconds twice, report more tool + time than the turn had and leave a negative remainder. + """ + total = 0.0 + current = None + for start, end in sorted(intervals): + if current is None or start > current[1]: + if current is not None: + total += current[1] - current[0] + current = [start, end] + else: + current[1] = max(current[1], end) + return total + current[1] - current[0] if current is not None else 0.0 + + 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] + intervals = [span for call in calls if (span := call_interval(call))] + durations = [end - start for start, end in intervals] + covered = union_seconds(intervals) 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) + summed = sum(durations) return { 'turns': len(turns), 'turnSeconds': round(turn_seconds, 2), 'calls': len(calls), - 'measurableCalls': len(durations), + 'measurableCalls': len(intervals), 'decomposedCalls': len(spawns), - 'callSeconds': round(measured, 2), - 'callShare': round(measured / turn_seconds, 3) if turn_seconds else None, + # Start-up timing for a call is only evidence about that call. A call + # that never reached the transport (a --help probe, say) still starts a + # process, so covering fewer calls leaves the answer unknown. + 'startupCoverage': round(len(spawns) / len(calls), 3) if calls else None, + 'callSeconds': round(covered, 2), + 'callSecondsSum': round(summed, 2), + 'overlapSeconds': round(summed - covered, 2), + 'callShare': round(covered / 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, + 'spawnShareOfCalls': round(sum(spawns) / summed, 3) if spawns and summed 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, + 'unaccountedSeconds': round(turn_seconds - covered, 2), + 'unaccountedShare': round((turn_seconds - covered) / turn_seconds, 3) if turn_seconds else None, } @@ -72,6 +117,10 @@ def verdict(numbers): 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 (numbers['startupCoverage'] or 0) < 1: + return (f'inconclusive: launch timing covers {numbers["decomposedCalls"]} of {numbers["calls"]} 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') if share > 0.4: decision = 'start-up dominates the turn: replace the CLI transport (R1)' elif share > 0.2: diff --git a/tests/test_agent_timing.py b/tests/test_agent_timing.py index 71e101e63..876687db6 100644 --- a/tests/test_agent_timing.py +++ b/tests/test_agent_timing.py @@ -153,3 +153,38 @@ async def scenario(): running, finished = asyncio.run(scenario()) assert 'timing' not in running assert finished['timing'] == {'spawn': None, 'work': finished['timing']['work']} + + +@requires_posix() +def test_start_up_is_counted_once_per_process(tmp_path): + async def scenario(): + queue = asyncio.Queue() + project = uuid4() + server, _ = await start_server(_Gateway(project), queue, str(tmp_path / 'cli.sock'), set()) + + async def send(first, identity): + reader, writer = await asyncio.open_unix_connection(str(tmp_path / 'cli.sock')) + writer.write((json.dumps({'id': identity, 'cliCommand': 'opendirector job wait', + 'projectId': str(project), 'name': 'job.wait', 'arguments': {}, + 'timing': {'startedAt': time.monotonic() - 1.5, + 'firstCall': first}}) + '\n').encode()) + await writer.drain() + await reader.readline() + writer.close() + await writer.wait_closed() + return [await asyncio.wait_for(queue.get(), 5) for _ in range(2)] + + try: + # A wait that polls sends one request per window from one process: + # only the first one paid for the interpreter. + first = await send(True, '1') + second = await send(False, '2') + return first, second + finally: + server.close() + await server.wait_closed() + + first, second = asyncio.run(scenario()) + assert 1.4 <= first[0]['timing']['spawn'] < 10 + assert second[0]['timing']['spawn'] == 0.0 + assert second[1]['timing']['spawn'] == 0.0 diff --git a/tests/test_bench_turn_timing.py b/tests/test_bench_turn_timing.py index 7c844b259..9bb9ecc2c 100644 --- a/tests/test_bench_turn_timing.py +++ b/tests/test_bench_turn_timing.py @@ -72,3 +72,35 @@ def test_the_report_reads_what_a_turn_writes(tmp_path): assert numbers['decomposedCalls'] == 1 assert numbers['spawnShareOfTurn'] == 0.22 assert json.loads(json.dumps(numbers))['turns'] == 1 + + +def test_nested_calls_do_not_report_more_tool_time_than_the_turn(): + numbers = bench.report([{'summary': {'turnSeconds': 10.0}, 'calls': [ + {'id': 'bash:1', 'name': 'bash', 'startedAt': 0.0, 'endedAt': 8.0}, + {'id': 'cli:1', 'name': 'opendirector job wait', 'startedAt': 1.0, 'endedAt': 7.0, + 'spawn': 0.0, 'work': 6.0}]}]) + assert numbers['callSeconds'] == 8.0 + assert numbers['callSecondsSum'] == 14.0 + assert numbers['overlapSeconds'] == 6.0 + assert numbers['callShare'] == 0.8 + assert numbers['unaccountedSeconds'] == 2.0 + + +def test_a_call_is_charged_the_start_up_it_paid_for(): + numbers = bench.report([{'summary': {'turnSeconds': 10.0}, 'calls': [ + {'id': 'cli:1', 'name': 'opendirector project show', 'startedAt': 5.0, 'endedAt': 5.1, + 'spawn': 1.2, 'work': 0.1}]}]) + assert numbers['callSeconds'] == 1.3 + assert numbers['callShare'] == 0.13 + assert numbers['spawnShareOfCalls'] == 0.923 + + +def test_calls_without_launch_timing_make_the_transport_decision_inconclusive(): + numbers = bench.report([{'summary': {'turnSeconds': 100.0}, 'calls': [ + {'id': f'cli:{index}', 'name': 'opendirector project show', 'startedAt': 0.0, + 'endedAt': 1.3, 'spawn': 1.2, 'work': 0.1} for index in range(40)] + [ + {'id': 'bash:help', 'name': 'bash', 'startedAt': 0.0, 'endedAt': 0.4}]}]) + assert numbers['startupCoverage'] == round(40 / 41, 3) + decision = bench.verdict(numbers) + assert 'inconclusive' in decision + assert 'replace the CLI transport' not in decision