diff --git a/docs/README.md b/docs/README.md index 86cc0fe69..3741cbad8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ This directory is the entry point for the repository's shared documentation. The | [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 | +| [Motion path benchmark](development/motion-path-benchmark.md) ([中文](development/motion-path-benchmark.zh-CN.md)) | Controlled 3x2 timing comparison and stage decomposition between Main Chat and Motion Director for 30s Web Motion generation | The benchmark runner, stage rules, or controlled baseline 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/motion-path-benchmark.md b/docs/development/motion-path-benchmark.md new file mode 100644 index 000000000..248b82435 --- /dev/null +++ b/docs/development/motion-path-benchmark.md @@ -0,0 +1,114 @@ +# Motion path benchmark + +Issue [#654](https://github.com/ThinkFlowLab/OpenDirector/issues/654) observed that generating a 30-second OpenDirector intro animation from Main Chat took roughly 17 minutes during manual acceptance of [#609](https://github.com/ThinkFlowLab/OpenDirector/pull/609), whereas the built-in Motion Director finished a comparable request much faster under uncontrolled conditions. This record establishes a controlled, reproducible comparison on a pinned commit and decomposes end-to-end wall time into comparable stages before selecting follow-up optimizations. + +## Controlled setup + +All trials ran sequentially against an isolated local API server (`OPENDIRECTOR_ROOT`) provisioned from the same commit and model configuration, with no pre-installed user skills and no concurrent workloads: + +- **Commit:** `9f24de145389dab2186944d6fcc79acee5492dad` (`origin/main` when the 3x2 live trials ran; automated checks re-verified after rebasing onto `728b40774628307f315a2b29c466237a8c434a11`) +- **Environment:** Apple Silicon macOS (`Darwin 27.2.0 arm64`), Python `3.12.9`, Node.js `v24.22.2`, FFmpeg `8.0.1`, local headless Chrome/Chromium Web Motion renderer +- **Model & reasoning:** `deepseek-flash` (`api.deepseek.com`, `inputModalities: ["text", "image"]`), `thinking="low"` on both paths so both send identical upstream wire reasoning settings (`thinking: {"type": "enabled"}`, `reasoning_effort: "low"`) +- **Prompt:** `做个OpenDirector 30s的动效动画` +- **Initial project & inputs:** Fresh empty project per trial (`assets=[]`, `canvasItems=[]`, `editorDocuments=[]`), `1920x1080` at `30fps` +- **Harnesses & versions:** + - `motion_director`: Built-in `stream_motion_director_chat` (`MAX_AGENT_STEPS=12`), preceded by `creation.batch` (`editor.create` + `canvas.show`) and followed by `editor.save` plus `/api/creation/motion/publish-prepare` -> `/render-jobs` -> `/render-jobs/{id}/publish` + - `main_chat`: `default` runtime backed by bundled `opencode-ai` `1.19.5` (`NativeRuntime` + `ModelGateway` + `cli_transport`) +- **Shared completion condition:** Both an editable `motion` `editorDocument` (`duration` within `30.0 ± 0.5s`, non-empty `web.html`, bound to a visible `motion` `canvasItem`) and a published `video` `canvasItem` backed by a decodable `1920x1080` `30fps` H.264 MP4 asset (`30.0 ± 0.5s`) are committed to disk and verified through a fresh `CreationProjects` store plus `ffprobe`. + +## Reproducing the benchmark + +```sh +.venv/bin/python scripts/bench_motion_paths.py run \ + --source-root . \ + --output-dir /tmp/motion-bench-654 \ + --archive-path /tmp/motion-bench-654/motion-benchmark-654-traces.zip \ + --runs 3 \ + --paths motion_director,main_chat \ + --model deepseek-flash \ + --thinking low \ + --runtime default +``` + +To recompute per-trial stage metrics from saved raw traces or re-export a sanitized trace archive (redacting credentials, local paths, usernames, temporary directories, inline data URLs, and raw model prompt/reasoning text while preserving request timings, payload sizes, and wire settings) from an existing run directory: + +```sh +.venv/bin/python scripts/bench_motion_paths.py reanalyze \ + --output-dir /tmp/motion-bench-654 +.venv/bin/python scripts/bench_motion_paths.py archive \ + --source-root . \ + --output-dir /tmp/motion-bench-654 \ + --zip-path /tmp/motion-bench-654/motion-benchmark-654-traces.zip +``` + +## Stage accounting rules + +Each trial partitions `[wall_started_at, wall_ended_at]` into five mutually exclusive, collectively exhaustive wall-clock buckets (`sum(stages) == endToEndSeconds`): + +1. **`model`:** Upstream LLM request-to-completion intervals (`model.request` to `model.completed` in `.model.jsonl` on `main_chat`; SSE LLM generation windows prior to tool execution on `motion_director`, keeping streamed `tool_call_delta` argument generation inside `model`). +2. **`cliDiscoveryAndExec`:** Non-inspect, non-render tool and CLI execution (`opendirector --help` / `--help-field` probes, skill/schema file discovery, Python helper scripts, `editor.create`, `editor.save`, `canvas.show`, and in-memory Motion Director composition mutations). +3. **`inspectFrames`:** `opendirector motion inspect`, frame image inspection reads, and Motion Director `inspect_frames` executions. +4. **`renderAndPublish`:** `opendirector motion render` (including `--publish-item-id`) and Motion Director `publish-prepare` + `render-jobs` + `publish`. +5. **`unattributed`:** Wall-clock remainder outside all four attributed stages (such as harness startup, client-side SSE/SQLite delta persistence, and inter-step orchestration). When nested intervals overlap (for example, an outer `bash` call wrapping `opendirector motion render`), intervals are unioned with inner stage precedence (`renderAndPublish` > `inspectFrames` > `cliDiscoveryAndExec` > `model`) so nested seconds are never counted twice. + +## Controlled 3x2 results + +All 6 runs (including failed `main_chat` trial 1) are retained: + +| Path | Trial | Result | End-to-End (s) | TTFA (s) | TTC (s) | `model` (s) | `cliDiscoveryAndExec` (s) | `inspectFrames` (s) | `renderAndPublish` (s) | `unattributed` (s) | Model Reqs | Tool Calls | `--help` Probes | Inspect Calls | Render Calls | +| --- | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `motion_director` | 1 | Succeeded | 185.117 | 125.548 | 185.117 | 122.733 | 0.172 | 2.643 | 59.569 | 0.000 | 13 | 21 | 0 | 4 | 1 | +| `motion_director` | 2 | Succeeded | 195.069 | 133.858 | 195.069 | 130.762 | 0.404 | 2.691 | 61.211 | 0.001 | 12 | 29 | 0 | 4 | 1 | +| `motion_director` | 3 | Succeeded | 206.254 | 142.030 | 206.254 | 140.701 | 0.231 | 1.098 | 64.223 | 0.001 | 8 | 14 | 0 | 2 | 1 | +| `main_chat` | 1 | Failed (`reason=length`) | 117.388 | — | — | 99.334 | 13.525 | 0.000 | 0.000 | 4.529 | 23 | 27 | 5 | 0 | 0 | +| `main_chat` | 2 | Succeeded | 371.621 | 186.438 | 342.249 | 182.460 | 31.755 | 4.052 | 96.755 | 56.599 | 50 | 72 | 18 | 3 | 2 | +| `main_chat` | 3 | Succeeded | 616.762 | 310.204 | 597.411 | 323.187 | 137.369 | 9.810 | 134.589 | 11.807 | 75 | 90 | 4 | 6 | 3 | + +### Aggregate comparison (succeeded trials) + +| Metric | `motion_director` (3/3 succeeded) | `main_chat` (2/3 succeeded, 1 failed) | Ratio (`main_chat` / `motion_director`) | +| --- | ---: | ---: | ---: | +| Mean end-to-end (s) | 195.480 | 494.191 | 2.53x | +| Median end-to-end (s) | 195.069 | 494.191 | 2.53x | +| Mean `model` (s) | 131.399 (67.2%) | 252.824 (51.2%) | 1.92x | +| Mean `cliDiscoveryAndExec` (s) | 0.269 (0.1%) | 84.562 (17.1%) | 314.4x | +| Mean `inspectFrames` (s) | 2.144 (1.1%) | 6.931 (1.4%) | 3.23x | +| Mean `renderAndPublish` (s) | 61.668 (31.5%) | 115.672 (23.4%) | 1.88x | +| Mean `unattributed` (s) | 0.001 (0.0%) | 34.203 (6.9%) | — | + +### Persisted project verification + +Reopening each isolated repository through a fresh `CreationProjects` store and probing published media with `ffprobe` confirmed: + +- `motion_director` trials 1–3: `eventCursor=5`, editable `motion` document (`revision=2`, `duration=30.0s`, `20–23` `data-clip-id` clips) plus frozen render snapshot (`revision=1`), and published `video` asset (`provenance.source="rendered"`, `1920x1080`, `30.0fps`, `h264`, `30.0s`, `0.74–1.59 MB`). +- `main_chat` trial 1 (failed): `eventCursor=1`, `0` `editorDocuments`, `0` `assets`, `0` `canvasItems`; terminated on `step_finish.reason="length"` before creating project objects. +- `main_chat` trials 2–3: `eventCursor=7` and `9`, editable `motion` documents (`revision=2` and `5`, `duration=30.0s`, `39` and `23` clips) plus frozen render snapshot, and published `video` assets (`provenance.source="rendered"`, `1920x1080`, `30.0fps`, `h264`, `30.0s`, `1.28 MB` and `0.79 MB`). + +## Bottleneck diagnosis and candidate follow-ups + +The traces isolate four concrete causes behind both the `2.53x` controlled slowdown (`494.2s` vs `195.5s` mean at `thinking="low"`) and the larger ~17-minute uncontrolled gap under default UI settings: + +1. **Multi-turn orchestration & `max_tokens=8192` ceiling (`model`: `+121.4s` mean; caused `main_chat` trial 1 failure):** + - `ModelGateway` uses `CHAT_MAX_TOKENS = 8192` without `reserve_reasoning=True`, whereas `MotionGeneration` grants `deepseek-flash` `32768` (`off`/`auto`), `65536` (`low`/`medium`), and `131072` (`high`) output tokens. + - In `main_chat` trial 1, request `40be830322c67e1d` streamed for `52.07s` (`2.57 MB` SSE) attempting to write the full 30s `MotionDocument` payload in one `bash` call, hit `finish_reason="length"` at `8192` tokens, and exited with zero deliverables. Successful `main_chat` runs decomposed the task into `50–75` sequential model requests (`11.0–19.0 MB` total SSE bytes) versus `8–13` requests in `motion_director`. + - Under default UI `thinking="auto"` (not pinned to `"low"`), `chat_payload` maps `api.deepseek.com` `"auto"` to `thinking={"type": "enabled"}, reasoning_effort="high"` (`max_tokens=8192`), while `_motion_thinking` maps `deepseek-flash` `"auto"` to `"off"` (`thinking={"type": "disabled"}, max_tokens=32768`), further amplifying latency and token truncation when `"auto"` is left selected. +2. **Inaccessible built-in `motion-director` skill and non-existent `skillsDir` hint (`cliDiscoveryAndExec`: `+84.3s` mean; `137.4s` in trial 3):** + - `builtin_skills()` exposes `packages/agent/skills` and omits `packages/agent/motion-skills/motion-director`. Meanwhile, `opendirector motion skills` lists `motion-director` alongside `skillsDir: "/.opendirector/motion-skills"` (the empty user-override path) with no CLI subcommand to read built-in motion skill files. + - All three `main_chat` runs failed `ls -R .../.opendirector/motion-skills` and launched filesystem searches (`mdfind` `4.69s` in trial 1; `find -maxdepth 6` `13.67s` plus `18` `--help`/`--help-field` probes in trial 2; `find / -type d -name "motion-skills"` hitting a `120.10s` shell timeout in trial 3) and Python source greps to reconstruct `MotionDocument` and `MotionWebDoc` schemas. +3. **Repeated full 900-frame MP4 renders during self-review (`renderAndPublish`: `+54.0s` mean; `2–3` full renders vs `1`):** + - `motion_director` verifies layout and motion exclusively with warm-Chrome `inspect_frames` (`1.1–2.7s` across `2–4` calls) and renders the 900-frame MP4 once (`59.6–64.2s`) when publishing. + - `main_chat` executed `2` full `opendirector motion render` passes in trial 2 (`48.39s` draft + `48.13s` publish = `96.8s`) and `3` full passes in trial 3 (`44.82s` + `44.32s` + `45.17s` = `134.6s`), rendering intermediate MP4 drafts before final publication. +4. **Harness SSE/SQLite delta-persistence overhead on large reasoning streams (`unattributed`: `56.6s` in trial 2, `11.8s` in trial 3):** + - In `main_chat` trial 2, after request `f74f69d9bec41a58` streamed `7846` reasoning tokens across `7844` SSE chunks (`2.46 MB` of SSE frames), `48.1s` elapsed inside OpenCode's local event/SQLite persistence and snapshot bookkeeping outside both `ModelGateway` upstream HTTP time and child `bash` execution. + +### Candidate optimization hypotheses (to be validated individually against this baseline) + +1. Expose `motion-director` (or a CLI `opendirector motion skill-read` command and accurate built-in path) plus compact `MotionDocument` / `canvas.show` templates to Main Chat so zero filesystem searches or `--help-field` walks are needed. +2. Align `ModelGateway` output token headroom and `thinking="auto"` defaults for `deepseek-flash` with `MotionGeneration` so single-pass composition writes do not hit the `8192`-token truncation cliff. +3. Instruct Main Chat's motion workflow to iterate with `opendirector motion inspect` and run `opendirector motion render --publish-item-id` once at final delivery. + +## Limitations + +- Measurements used real `deepseek-flash` calls over `https://api.deepseek.com/v1` from a single Apple Silicon macOS host; absolute network latency (`medianTtfbMs` `495–723 ms`) and token throughput vary with provider load. +- Neither path generated bespoke audio in these 6 runs because the isolated `OPENDIRECTOR_ROOT` intentionally omitted audio/video generation providers to keep the comparison strictly on identical `deepseek-flash` + Web Motion conditions. Runs that also synthesize and mux local BGM or invoke external media models add stage time outside this baseline. +- Backend `ttfaSeconds` and `ttcSeconds` measure authoritative server commit/publication timestamps rather than browser first-paint decode latency (see [Agent turn timing](agent-timing.md) and [Assistant turn timing](turn-timing.md)). diff --git a/docs/development/motion-path-benchmark.zh-CN.md b/docs/development/motion-path-benchmark.zh-CN.md new file mode 100644 index 000000000..6c959e011 --- /dev/null +++ b/docs/development/motion-path-benchmark.zh-CN.md @@ -0,0 +1,114 @@ +# Motion 路径对照基准测量 + +Issue [#654](https://github.com/ThinkFlowLab/OpenDirector/issues/654) 记录了 [#609](https://github.com/ThinkFlowLab/OpenDirector/pull/609) 手动验收时的现象:主聊天生成一条 30 秒 OpenDirector 介绍动效约耗时 17 分钟,而内置 Motion Director 完成类似请求明显更快。由于当时两次运行未控制相同条件,本文在固定提交、同一模型与推理档位、同一提示词和干净初始工程下完成可复现对照测量,按阶段拆解端到端耗时并定位主要瓶颈,作为后续逐项验证优化假设的基线。 + +## 受控实验条件 + +所有轮次均在独立隔离的本地 API 服务目录(`OPENDIRECTOR_ROOT`)中顺序执行,仅保留单一目标 Agent 模型配置,不包含用户自定义技能或并发任务干扰: + +- **代码提交:** `9f24de145389dab2186944d6fcc79acee5492dad`(实测启动时的 `origin/main`;变基对齐至 `728b40774628307f315a2b29c466237a8c434a11` 后重新通过自动化检查) +- **运行环境:** Apple Silicon macOS(`Darwin 27.2.0 arm64`)、Python `3.12.9`、Node.js `v24.22.2`、FFmpeg `8.0.1`、本机无头 Chrome/Chromium Web Motion 渲染器 +- **模型与推理设置:** `deepseek-flash`(`api.deepseek.com`,`inputModalities: ["text", "image"]`);两条路径均显式固定 `thinking="low"`,确保发送到上游模型服务的推理参数一致(`thinking: {"type": "enabled"}`、`reasoning_effort: "low"`) +- **统一提示词:** `做个OpenDirector 30s的动效动画` +- **初始工程与输入素材:** 每轮新建空白工程(`assets=[]`、`canvasItems=[]`、`editorDocuments=[]`),画幅 `1920x1080`、`30fps` +- **Harness 与版本:** + - `motion_director`:内置 `stream_motion_director_chat`(`MAX_AGENT_STEPS=12`),前置 `creation.batch`(`editor.create` + `canvas.show`)创建空白动效节点,对话结束后执行 `editor.save` 及 `/api/creation/motion/publish-prepare` -> `/render-jobs` -> `/render-jobs/{id}/publish` + - `main_chat`:`default` 运行时,使用仓库内置 `opencode-ai` `1.19.5`(`NativeRuntime` + `ModelGateway` + `cli_transport`) +- **共同完成条件:** 工程落盘同时包含可编辑的 `motion` `editorDocument`(`duration` 在 `30.0 ± 0.5s` 内、`web.html` 非空,且绑定可见 `motion` 画布节点)以及已发布的 `video` 画布节点与可解码 `1920x1080` `30fps` H.264 MP4 资产(`30.0 ± 0.5s`),并通过全新 `CreationProjects` 实例重读与 `ffprobe` 校验。 + +## 复现命令 + +```sh +.venv/bin/python scripts/bench_motion_paths.py run \ + --source-root . \ + --output-dir /tmp/motion-bench-654 \ + --archive-path /tmp/motion-bench-654/motion-benchmark-654-traces.zip \ + --runs 3 \ + --paths motion_director,main_chat \ + --model deepseek-flash \ + --thinking low \ + --runtime default +``` + +基于已有运行目录重新统计阶段指标或导出脱敏轨迹归档(自动脱敏密钥、本机目录、用户名、临时目录、内联图片 Base64 与模型原始提示词/思考正文,完整保留请求耗时、字节量与线上参数): + +```sh +.venv/bin/python scripts/bench_motion_paths.py reanalyze \ + --output-dir /tmp/motion-bench-654 +.venv/bin/python scripts/bench_motion_paths.py archive \ + --source-root . \ + --output-dir /tmp/motion-bench-654 \ + --zip-path /tmp/motion-bench-654/motion-benchmark-654-traces.zip +``` + +## 阶段计时口径 + +每轮将 `[wall_started_at, wall_ended_at]` 划分为五个互斥且完备的墙钟阶段(各阶段之和严格等于 `endToEndSeconds`): + +1. **`model`(模型):** 上游大模型请求至响应流结束的时间区间(`main_chat` 取 `.model.jsonl` 的 `model.request` 至 `model.completed`;`motion_director` 取每步工具实际执行前的流式生成窗口,流式输出 `tool_call_delta` 参数计入 `model`)。 +2. **`cliDiscoveryAndExec`(CLI 探索与执行):** 除检查帧与渲染发布外的工具和 CLI 执行(`opendirector --help` / `--help-field` 探测、技能与 Schema 查找、Python 辅助脚本、`editor.create`、`editor.save`、`canvas.show`,以及 Motion Director 内存态合成编辑工具)。 +3. **`inspectFrames`(检查帧):** `opendirector motion inspect`、抽帧图片检查读取,以及 Motion Director 的 `inspect_frames` 调用。 +4. **`renderAndPublish`(渲染发布):** `opendirector motion render`(含 `--publish-item-id`)以及 Motion Director 的 `publish-prepare` + `render-jobs` + `publish`。 +5. **`unattributed`(无法归属的时间):** 上述四类阶段并集之外的墙钟余量(如 Harness 进程启动、客户端 SSE/SQLite 分片落库及步骤间调度开销)。当外层 `bash` 与内层 CLI 调用嵌套重叠时,按内层阶段优先级(`renderAndPublish` > `inspectFrames` > `cliDiscoveryAndExec` > `model`)去重切分,避免重复计入。 + +## 3x2 对照实测结果 + +全部 6 轮运行(含失败的 `main_chat` 第 1 轮样本)完整保留如下: + +| 路径 | 轮次 | 结果 | 端到端 (s) | TTFA (s) | TTC (s) | `model` (s) | `cliDiscoveryAndExec` (s) | `inspectFrames` (s) | `renderAndPublish` (s) | `unattributed` (s) | 模型请求数 | 工具调用数 | `--help` 探测 | 检查帧次数 | 渲染次数 | +| --- | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `motion_director` | 1 | 成功 | 185.117 | 125.548 | 185.117 | 122.733 | 0.172 | 2.643 | 59.569 | 0.000 | 13 | 21 | 0 | 4 | 1 | +| `motion_director` | 2 | 成功 | 195.069 | 133.858 | 195.069 | 130.762 | 0.404 | 2.691 | 61.211 | 0.001 | 12 | 29 | 0 | 4 | 1 | +| `motion_director` | 3 | 成功 | 206.254 | 142.030 | 206.254 | 140.701 | 0.231 | 1.098 | 64.223 | 0.001 | 8 | 14 | 0 | 2 | 1 | +| `main_chat` | 1 | 失败(`reason=length`) | 117.388 | — | — | 99.334 | 13.525 | 0.000 | 0.000 | 4.529 | 23 | 27 | 5 | 0 | 0 | +| `main_chat` | 2 | 成功 | 371.621 | 186.438 | 342.249 | 182.460 | 31.755 | 4.052 | 96.755 | 56.599 | 50 | 72 | 18 | 3 | 2 | +| `main_chat` | 3 | 成功 | 616.762 | 310.204 | 597.411 | 323.187 | 137.369 | 9.810 | 134.589 | 11.807 | 75 | 90 | 4 | 6 | 3 | + +### 成功样本汇总对比 + +| 指标 | `motion_director`(3/3 成功) | `main_chat`(2/3 成功,1 失败) | 比值(`main_chat` / `motion_director`) | +| --- | ---: | ---: | ---: | +| 端到端均值 (s) | 195.480 | 494.191 | 2.53x | +| 端到端中位数 (s) | 195.069 | 494.191 | 2.53x | +| `model` 均值 (s) | 131.399 (67.2%) | 252.824 (51.2%) | 1.92x | +| `cliDiscoveryAndExec` 均值 (s) | 0.269 (0.1%) | 84.562 (17.1%) | 314.4x | +| `inspectFrames` 均值 (s) | 2.144 (1.1%) | 6.931 (1.4%) | 3.23x | +| `renderAndPublish` 均值 (s) | 61.668 (31.5%) | 115.672 (23.4%) | 1.88x | +| `unattributed` 均值 (s) | 0.001 (0.0%) | 34.203 (6.9%) | — | + +### 工程落盘产物核验 + +通过全新 `CreationProjects` 存储实例重读各轮隔离工程并用 `ffprobe` 校验落盘视频确认: + +- `motion_director` 第 1–3 轮:`eventCursor=5`,同时落盘可编辑 `motion` 文档(`revision=2`,`duration=30.0s`,`20–23` 个 `data-clip-id` 片段)与冻结渲染快照(`revision=1`),以及已发布 `video` 资产(`provenance.source="rendered"`,`1920x1080`、`30.0fps`、`h264`、`30.0s`,`0.74–1.59 MB`)。 +- `main_chat` 第 1 轮(失败样本):`eventCursor=1`,`0` 个 `editorDocuments`、`0` 个 `assets`、`0` 个 `canvasItems`;因 `step_finish.reason="length"` 提前终止,未创建工程对象。 +- `main_chat` 第 2–3 轮:`eventCursor=7` 与 `9`,同时落盘可编辑 `motion` 文档(`revision=2` 与 `5`,`duration=30.0s`,`39` 与 `23` 个片段)与冻结渲染快照,以及已发布 `video` 资产(`provenance.source="rendered"`,`1920x1080`、`30.0fps`、`h264`、`30.0s`,`1.28 MB` 与 `0.79 MB`)。 + +## 主要耗时阶段与根因定位 + +结合轨迹证据,固定 `thinking="low"` 条件下主聊天仍慢 `2.53x`(`494.2s` 对 `195.5s`)以及默认 UI 设置下耗时进一步放大至约 17 分钟,主要由以下四项原因共同造成: + +1. **多轮拆解与 `max_tokens=8192` 截断上限(`model` 均值多 `+121.4s`,并直接导致 `main_chat` 第 1 轮失败):** + - `ModelGateway` 固定使用 `CHAT_MAX_TOKENS = 8192` 且未启用 `reserve_reasoning=True`;而 `MotionGeneration` 为 `deepseek-flash` 分配 `32768`(`off`/`auto`)、`65536`(`low`/`medium`)及 `131072`(`high`)输出上限。 + - `main_chat` 第 1 轮在最后一次请求(`40be830322c67e1d`)耗时 `52.07s`(转发 `2.57 MB` SSE)试图单次输出完整 30 秒 `MotionDocument` JSON 时触发 `8192` token 上限(`finish_reason="length"`),导致该轮直接中断且无产物落盘。成功的第 2、3 轮被迫拆分为 `50–75` 次串行模型调用(累计转发 `11.0–19.0 MB` SSE),远高于 `motion_director` 的 `8–13` 次。 + - 此外,若界面保持默认 `thinking="auto"`(未显式固定为 `"low"`),`chat_payload` 会将 `api.deepseek.com` 的 `"auto"` 映射为 `thinking={"type": "enabled"}, reasoning_effort="high"`(`max_tokens=8192`),而 `_motion_thinking` 会将 `deepseek-flash` 的 `"auto"` 映射为 `"off"`(`thinking={"type": "disabled"}, max_tokens=32768`),默认档位不一致会进一步拉大模型耗时与截断概率。 +2. **主聊天未挂载内置 `motion-director` 技能且 `opendirector motion skills` 返回不存在的 `skillsDir`(`cliDiscoveryAndExec` 均值多 `+84.3s`,第 3 轮达 `137.4s`):** + - `builtin_skills()` 仅暴露 `packages/agent/skills`,未包含 `packages/agent/motion-skills/motion-director`;同时 `opendirector motion skills` 返回了 `motion-director` 名称及 `skillsDir: "/.opendirector/motion-skills"`(并不存在的用户覆盖目录),且缺少读取内置动效技能正文的 CLI 子命令。 + - 全部 3 轮 `main_chat` 在执行 `ls -R .../.opendirector/motion-skills` 失败后均触发了全盘搜索(第 1 轮 `mdfind` `4.69s`;第 2 轮 `find -maxdepth 6` `13.67s` 加 `18` 次 `--help`/`--help-field` 探测;第 3 轮执行 `find / -type d -name "motion-skills"` 触发 `120.10s` 命令超时),并反复 `grep` Python 源码拼凑 `MotionDocument` 与 `MotionWebDoc` 结构。 +3. **审片循环中重复执行完整 900 帧 MP4 渲染(`renderAndPublish` 均值多 `+54.0s`,全量渲染 `2–3` 次对 `1` 次):** + - `motion_director` 在编辑阶段仅通过常驻热启动 Chrome 的 `inspect_frames`(`2–4` 次共 `1.1–2.7s`)检查关键帧,仅在最终发布画布时执行 `1` 次 900 帧 MP4 导出(`59.6–64.2s`)。 + - `main_chat` 在第 2 轮执行了 `2` 次完整 `opendirector motion render`(`48.39s` 草稿 + `48.13s` 发布,共 `96.8s`),第 3 轮执行了 `3` 次完整 `opendirector motion render`(`44.82s` + `44.32s` + `45.17s`,共 `134.6s`),用全片渲染代替轻量抽帧复查。 +4. **大体量推理流在 Harness 侧的 SSE/SQLite 分片落库开销(`unattributed` 第 2 轮 `56.6s`,第 3 轮 `11.8s`):** + - `main_chat` 第 2 轮在单次请求(`f74f69d9bec41a58`)流式输出 `7846` 个推理 token(共 `7844` 条 `model.reasoning` SSE 分片,`2.46 MB`)后,OpenCode 进程在 `ModelGateway` 响应结束与下一条子命令启动之间耗费了 `48.1s` 进行本地事件落库与工作区快照整理。 + +### 待测优化项建议(后续基于本基线逐项验证) + +1. 向主聊天暴露内置 `motion-director` 技能(或提供 `opendirector motion skill-read` 命令并修正 `skillsDir` 提示)及精简的 `MotionDocument` / `canvas.show` 示例契约,消除全盘 `find` 与反复 `--help-field` 探测。 +2. 对齐 `ModelGateway` 与 `MotionGeneration` 在 `deepseek-flash` 上的 `max_tokens` 输出余量及 `thinking="auto"` 默认映射,避免生成完整 30 秒动效文档时触碰 `8192` 截断上限。 +3. 在动效创作指引中明确使用 `opendirector motion inspect` 完成迭代审片,仅在定稿发布时调用一次 `opendirector motion render --publish-item-id`。 + +## 范围与局限说明 + +- 实测基于单台 Apple Silicon macOS 主机访问真实 `https://api.deepseek.com/v1`(`deepseek-flash`),绝对网络首包延迟(`medianTtfbMs` `495–723 ms`)与流式吞吐受服务商实时负载影响。 +- 为严格隔离同一 `deepseek-flash` 与 Web Motion 创作条件,隔离环境中未配置额外音频/视频生成模型,本组 6 轮样本均未额外合成配乐;若叠加本地音频合成或外部媒体模型调用,相应耗时将在此基线之上增加。 +- 表中 `ttfaSeconds` 与 `ttcSeconds` 为服务端权威提交与发布完成时间戳,不包含浏览器端首帧加载与解码渲染延迟(参见[Agent 轮次计时](agent-timing.zh-CN.md)与[助手轮次计时](turn-timing.zh-CN.md))。 diff --git a/scripts/bench_motion_paths.py b/scripts/bench_motion_paths.py new file mode 100644 index 000000000..c61810734 --- /dev/null +++ b/scripts/bench_motion_paths.py @@ -0,0 +1,1904 @@ +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import platform +import re +import shutil +import socket +import statistics +import subprocess +import sys +import time +from typing import Any +from urllib.parse import urlsplit +from uuid import uuid4, uuid5 +import zipfile + +import httpx + + +_SCRIPT_DIR = Path(__file__).resolve().parent +_REPO_ROOT = _SCRIPT_DIR.parent +sys.path[:] = [entry for entry in sys.path if Path(entry or ".").resolve() != _SCRIPT_DIR] +_CORE_SRC = str(_REPO_ROOT / "packages" / "core" / "src") +if _CORE_SRC not in sys.path: + sys.path.insert(0, _CORE_SRC) + + +DEFAULT_PROMPT = "做个OpenDirector 30s的动效动画" +STAGE_KEYS = ( + "model", + "cliDiscoveryAndExec", + "inspectFrames", + "renderAndPublish", + "unattributed", +) +STAGE_PRECEDENCE = ( + "renderAndPublish", + "inspectFrames", + "cliDiscoveryAndExec", + "model", +) + +_CMD_RENDER_RE = re.compile( + r"(?:^|[;&|\n]\s*)(?:\S*/)?opendirector(?:\s+(?:--project|--operation-id)\s+\S+)*\s+motion\s+render\b" +) +_CMD_INSPECT_RE = re.compile( + r"(?:^|[;&|\n]\s*)(?:\S*/)?opendirector(?:\s+(?:--project|--operation-id)\s+\S+)*\s+motion\s+inspect\b" +) +_HELP_FLAG_RE = re.compile(r"(?:^|\s)(?:--help|--help-field|-h)(?:\s|$)") +_DATA_URL_RE = re.compile(r"data:image/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+") +_BEARER_RE = re.compile(r"Bearer\s+[A-Za-z0-9._\-+/=]+", re.I) +_SK_TOKEN_RE = re.compile(r"\bsk-[A-Za-z0-9_\-]{12,}\b") +_TMP_AGENT_RE = re.compile(r"(?:/private)?/tmp/od-agent-[A-Za-z0-9_\-]+") +_VAR_FOLDERS_RE = re.compile(r"(?:/private)?/var/folders/[A-Za-z0-9_/.\-]+") +_CLIP_ID_RE = re.compile(r"""data-clip-id\s*=\s*(?:"([^"]+)"|'([^']+)')""") + + +def default_empty_web_doc(width: int = 1920, height: int = 1080) -> dict[str, Any]: + return { + "version": 1, + "baseWidth": width, + "baseHeight": height, + "theme": { + "background": "#0B1120", + "backgroundGradientTo": "#131C33", + "accentColor": "#D6A85A", + "textColor": "#F2F5FA", + "surfaceColor": "#151E35", + "borderColor": "#263352", + }, + "html": "", + "css": "", + "script": "", + "overrides": {}, + } + + +def merge_intervals(intervals: list[tuple[float, float]]) -> list[tuple[float, float]]: + cleaned = [(float(a), float(b)) for a, b in intervals if b > a] + if not cleaned: + return [] + ordered = sorted(cleaned) + merged: list[list[float]] = [[ordered[0][0], ordered[0][1]]] + for start, end in ordered[1:]: + if start <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], end) + else: + merged.append([start, end]) + return [(item[0], item[1]) for item in merged] + + +def sum_intervals(intervals: list[tuple[float, float]]) -> float: + return sum(end - start for start, end in merge_intervals(intervals)) + + +def clip_intervals( + intervals: list[tuple[float, float]], + lower: float, + upper: float, +) -> list[tuple[float, float]]: + if upper <= lower: + return [] + out: list[tuple[float, float]] = [] + for start, end in intervals: + clipped_start = max(lower, float(start)) + clipped_end = min(upper, float(end)) + if clipped_end > clipped_start: + out.append((clipped_start, clipped_end)) + return merge_intervals(out) + + +def partition_stage_intervals( + total_start: float, + total_end: float, + stage_intervals: dict[str, list[tuple[float, float]]], +) -> dict[str, Any]: + duration = max(0.0, float(total_end) - float(total_start)) + clipped = { + stage: clip_intervals(stage_intervals.get(stage, []), float(total_start), float(total_end)) + for stage in STAGE_PRECEDENCE + } + raw_sums = { + stage: round(sum(end - start for start, end in stage_intervals.get(stage, []) if end > start), 3) + for stage in STAGE_PRECEDENCE + } + boundaries = {float(total_start), float(total_end)} + for spans in clipped.values(): + for start, end in spans: + boundaries.add(start) + boundaries.add(end) + points = sorted(boundaries) + totals = {key: 0.0 for key in STAGE_KEYS} + for left, right in zip(points, points[1:]): + if right <= left: + continue + midpoint = (left + right) * 0.5 + assigned = "unattributed" + for stage in STAGE_PRECEDENCE: + if any(start <= midpoint <= end for start, end in clipped[stage]): + assigned = stage + break + totals[assigned] += right - left + rounded = {key: round(totals[key], 3) for key in STAGE_KEYS} + drift = round(duration - sum(rounded.values()), 3) + if drift != 0.0: + rounded["unattributed"] = round(max(0.0, rounded["unattributed"] + drift), 3) + shares = { + key: round(totals[key] / duration, 4) if duration > 0 else 0.0 + for key in STAGE_KEYS + } + return { + "endToEndSeconds": round(duration, 3), + "stages": rounded, + "stageShares": shares, + "rawStageSums": raw_sums, + } + + +def classify_cli_command(tool_name: str, command_text: str = "") -> str: + clean_tool = (tool_name or "").strip() + clean_cmd = (command_text or "").strip() + if clean_tool == "opendirector motion render": + return "renderAndPublish" + if clean_tool == "opendirector motion inspect": + return "inspectFrames" + if clean_tool.startswith("opendirector "): + return "cliDiscoveryAndExec" + if clean_tool == "bash" and clean_cmd: + has_help = bool(_HELP_FLAG_RE.search(clean_cmd)) + if not has_help and _CMD_RENDER_RE.search(clean_cmd): + return "renderAndPublish" + if not has_help and _CMD_INSPECT_RE.search(clean_cmd): + return "inspectFrames" + if clean_tool == "read" and clean_cmd: + lower_path = clean_cmd.lower() + if lower_path.endswith((".png", ".jpg", ".jpeg", ".webp")) and "frame" in lower_path: + return "inspectFrames" + return "cliDiscoveryAndExec" + + +def is_help_probe(tool_name: str, command_text: str = "") -> bool: + if (tool_name or "").strip() != "bash": + return False + clean_cmd = (command_text or "").strip() + return "opendirector" in clean_cmd and bool(_HELP_FLAG_RE.search(clean_cmd)) + + +def is_followup_enrichment_rpc(tool_name: str, arguments: Any) -> bool: + clean_tool = (tool_name or "").strip() + if not isinstance(arguments, dict): + return False + if clean_tool in {"opendirector motion render", "opendirector motion inspect"}: + return arguments.get("type") == "object.get" + return False + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + if not path.is_file(): + return [] + records: list[dict[str, Any]] = [] + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + text = line.strip() + if not text: + continue + try: + parsed = json.loads(text) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict): + records.append(parsed) + return records + + +def extract_model_gateway_intervals( + model_events: list[dict[str, Any]], +) -> tuple[list[tuple[float, float]], list[tuple[float, float]], dict[str, Any]]: + requests_by_id: dict[str, dict[str, Any]] = {} + foreground_intervals: list[tuple[float, float]] = [] + background_intervals: list[tuple[float, float]] = [] + ttfb_ms_values: list[float] = [] + completed_count = 0 + error_count = 0 + forwarded_bytes = 0 + effective_payload_meta: dict[str, Any] = {} + + for event in model_events: + kind = event.get("event") + req_id = str(event.get("requestId") or "") + if not req_id: + continue + if kind == "model.request": + payload = event.get("payload") if isinstance(event.get("payload"), dict) else {} + has_tools = bool(payload.get("tools")) + requests_by_id[req_id] = { + "timestamp": event.get("timestamp"), + "hasTools": has_tools, + } + if has_tools and not effective_payload_meta: + effective_payload_meta = { + "model": payload.get("model"), + "thinking": payload.get("thinking"), + "reasoningEffort": payload.get("reasoning_effort"), + "maxTokens": payload.get("max_tokens") or payload.get("max_completion_tokens"), + } + elif kind == "model.response": + elapsed_ms = event.get("elapsedMs") + if isinstance(elapsed_ms, (int, float)): + ttfb_ms_values.append(float(elapsed_ms)) + elif kind in {"model.completed", "model.error", "model.cancelled"}: + if kind == "model.completed": + completed_count += 1 + else: + error_count += 1 + fb = event.get("forwardedBytes") + if isinstance(fb, int): + forwarded_bytes += fb + end_ts = event.get("timestamp") + req_meta = requests_by_id.get(req_id, {}) + start_ts = req_meta.get("timestamp") + elapsed_ms = event.get("elapsedMs") + span: tuple[float, float] | None = None + if isinstance(end_ts, (int, float)) and isinstance(elapsed_ms, (int, float)) and elapsed_ms > 0: + span = (float(end_ts) - float(elapsed_ms) / 1000.0, float(end_ts)) + elif isinstance(start_ts, (int, float)) and isinstance(end_ts, (int, float)) and end_ts > start_ts: + span = (float(start_ts), float(end_ts)) + if span is not None: + if req_meta.get("hasTools", True): + foreground_intervals.append(span) + else: + background_intervals.append(span) + + meta = { + "requestCount": len(requests_by_id), + "foregroundRequestCount": sum(1 for item in requests_by_id.values() if item.get("hasTools")), + "backgroundRequestCount": sum(1 for item in requests_by_id.values() if not item.get("hasTools")), + "completedCount": completed_count, + "errorCount": error_count, + "forwardedBytes": forwarded_bytes, + "medianTtfbMs": round(statistics.median(ttfb_ms_values), 1) if ttfb_ms_values else None, + "effectiveWireConfig": effective_payload_meta, + } + return foreground_intervals, background_intervals, meta + + +def analyze_main_chat_traces( + *, + wall_started_at: float, + wall_ended_at: float, + sse_records: list[dict[str, Any]], + opencode_records: list[dict[str, Any]], + model_records: list[dict[str, Any]], + timing_ledger: dict[str, Any] | None, +) -> dict[str, Any]: + fg_model, bg_model, model_meta = extract_model_gateway_intervals(model_records) + timing_by_id: dict[str, dict[str, Any]] = {} + if isinstance(timing_ledger, dict): + for entry in timing_ledger.get("calls", []): + if isinstance(entry, dict) and isinstance(entry.get("id"), str): + timing_by_id[entry["id"]] = entry + + sse_tool_starts: dict[str, float] = {} + sse_tool_ends: dict[str, tuple[float, str, str, Any]] = {} + ttfa_epoch: float | None = None + ttc_epoch: float | None = None + turn_error: str | None = None + + for row in sse_records: + ts = row.get("epoch") + payload = row.get("event") + if not isinstance(ts, (int, float)) or not isinstance(payload, dict): + continue + etype = payload.get("type") + if etype == "tool": + call_id = str(payload.get("id") or "") + name = str(payload.get("name") or "") + status = str(payload.get("status") or "") + args = payload.get("arguments") + if call_id and call_id not in sse_tool_starts: + sse_tool_starts[call_id] = float(ts) + if call_id and status in {"complete", "failed", "interrupted"}: + sse_tool_ends[call_id] = (float(ts), name, status, args) + if status == "complete": + if ttfa_epoch is None and name in { + "opendirector canvas show", + "opendirector editor create", + "opendirector editor save", + "opendirector creation batch", + }: + ttfa_epoch = float(ts) + if name == "opendirector motion render" and not is_followup_enrichment_rpc(name, args): + if not isinstance(args, dict) or "publishItemId" in args or ttc_epoch is None: + ttc_epoch = float(ts) + elif etype == "end" and payload.get("error"): + err_obj = payload["error"] + turn_error = err_obj.get("message") if isinstance(err_obj, dict) else str(err_obj) + + stage_intervals: dict[str, list[tuple[float, float]]] = {key: [] for key in STAGE_PRECEDENCE} + stage_intervals["model"].extend(fg_model) + stage_intervals["model"].extend(bg_model) + + cli_call_count = 0 + inspect_call_count = 0 + render_call_count = 0 + failed_tool_count = 0 + help_probe_count = 0 + native_tool_count = 0 + + for call_id, (end_ts, name, status, args) in sse_tool_ends.items(): + cli_call_count += 1 + if status != "complete": + failed_tool_count += 1 + ledger_entry = timing_by_id.get(call_id, {}) + spawn = ledger_entry.get("spawn") if isinstance(ledger_entry.get("spawn"), (int, float)) else 0.0 + work = ledger_entry.get("work") if isinstance(ledger_entry.get("work"), (int, float)) else 0.0 + observed_start = sse_tool_starts.get(call_id, end_ts) + duration = max(end_ts - observed_start, float(spawn) + float(work)) + span = (end_ts - duration, end_ts) + stage = classify_cli_command(name) + if not is_followup_enrichment_rpc(name, args): + if stage == "inspectFrames": + inspect_call_count += 1 + elif stage == "renderAndPublish": + render_call_count += 1 + stage_intervals[stage].append(span) + + for row in opencode_records: + native = row.get("native") + if not isinstance(native, dict) or native.get("type") != "tool_use": + continue + part = native.get("part") + if not isinstance(part, dict): + continue + native_tool_count += 1 + tool_name = str(part.get("tool") or "") + state = part.get("state") if isinstance(part.get("state"), dict) else {} + status = str(state.get("status") or "") + if status == "error": + failed_tool_count += 1 + inp = state.get("input") if isinstance(state.get("input"), dict) else {} + cmd_text = str(inp.get("command") or inp.get("filePath") or inp.get("pattern") or "") + if is_help_probe(tool_name, cmd_text): + help_probe_count += 1 + time_info = state.get("time") if isinstance(state.get("time"), dict) else {} + start_ms = time_info.get("start") + end_ms = time_info.get("end") + if isinstance(start_ms, (int, float)) and isinstance(end_ms, (int, float)) and end_ms > start_ms: + span = (float(start_ms) / 1000.0, float(end_ms) / 1000.0) + stage = classify_cli_command(tool_name, cmd_text) + stage_intervals[stage].append(span) + + partition = partition_stage_intervals(wall_started_at, wall_ended_at, stage_intervals) + return { + **partition, + "ttfaSeconds": round(ttfa_epoch - wall_started_at, 3) if ttfa_epoch is not None else None, + "ttcSeconds": round(ttc_epoch - wall_started_at, 3) if ttc_epoch is not None else None, + "counts": { + "modelRequests": model_meta["requestCount"], + "foregroundModelRequests": model_meta["foregroundRequestCount"], + "backgroundModelRequests": model_meta["backgroundRequestCount"], + "nativeToolCalls": native_tool_count, + "cliTransportCalls": cli_call_count, + "helpProbes": help_probe_count, + "inspectCalls": inspect_call_count, + "renderCalls": render_call_count, + "failedToolCalls": failed_tool_count, + }, + "modelMeta": model_meta, + "turnError": turn_error, + } + + +def analyze_motion_director_traces( + *, + wall_started_at: float, + wall_ended_at: float, + setup_span: tuple[float, float] | None, + chat_started_at: float, + chat_ended_at: float, + sse_records: list[dict[str, Any]], + save_span: tuple[float, float] | None, + publish_span: tuple[float, float] | None, +) -> dict[str, Any]: + stage_intervals: dict[str, list[tuple[float, float]]] = {key: [] for key in STAGE_PRECEDENCE} + if setup_span is not None: + stage_intervals["cliDiscoveryAndExec"].append(setup_span) + if save_span is not None: + stage_intervals["cliDiscoveryAndExec"].append(save_span) + if publish_span is not None: + stage_intervals["renderAndPublish"].append(publish_span) + + phase = "model" + cursor = float(chat_started_at) + active_tool_name: str | None = None + active_tool_start: float | None = None + model_step_count = 0 + tool_call_count = 0 + inspect_call_count = 0 + failed_tool_count = 0 + stream_error: str | None = None + + for row in sse_records: + ts = row.get("epoch") + event = row.get("event") + if not isinstance(ts, (int, float)) or not isinstance(event, dict): + continue + now = float(ts) + etype = event.get("type") + + if etype == "tool_start": + args = event.get("arguments") + has_real_args = isinstance(args, dict) and len(args) > 0 + if has_real_args: + if phase == "model": + if now > cursor: + stage_intervals["model"].append((cursor, now)) + model_step_count += 1 + elif phase == "post_tool" and now > cursor: + stage_intervals["cliDiscoveryAndExec"].append((cursor, now)) + if phase != "tool": + active_tool_start = now + phase = "tool" + active_tool_name = str(event.get("name") or "") + elif phase == "post_tool": + phase = "model" + elif etype == "tool_progress": + if "arguments" in event: + if phase == "model": + if now > cursor: + stage_intervals["model"].append((cursor, now)) + model_step_count += 1 + elif phase == "post_tool" and now > cursor: + stage_intervals["cliDiscoveryAndExec"].append((cursor, now)) + if phase != "tool": + active_tool_start = now + phase = "tool" + active_tool_name = str(event.get("name") or "") + elif phase == "post_tool": + phase = "model" + elif etype == "tool_end": + t_name = str(event.get("name") or active_tool_name or "") + status = str(event.get("status") or "complete") + tool_call_count += 1 + if status != "complete": + failed_tool_count += 1 + if phase == "model": + if now > cursor: + stage_intervals["model"].append((cursor, now)) + model_step_count += 1 + t_start = now + else: + t_start = active_tool_start if active_tool_start is not None else cursor + if now > t_start: + target_stage = "inspectFrames" if t_name == "inspect_frames" else "cliDiscoveryAndExec" + stage_intervals[target_stage].append((t_start, now)) + if t_name == "inspect_frames": + inspect_call_count += 1 + active_tool_name = None + active_tool_start = None + phase = "post_tool" + cursor = now + elif etype == "web_update": + if phase == "post_tool" and now > cursor: + stage_intervals["cliDiscoveryAndExec"].append((cursor, now)) + cursor = now + elif etype in {"thinking", "delta", "tool_call_delta"}: + if phase == "post_tool": + phase = "model" + elif etype == "done": + if phase == "model": + if now > cursor: + stage_intervals["model"].append((cursor, now)) + model_step_count += 1 + elif phase == "post_tool" and now > cursor: + stage_intervals["cliDiscoveryAndExec"].append((cursor, now)) + phase = "done" + cursor = now + elif etype == "error": + stream_error = str(event.get("message") or "motion_chat_error") + if phase == "model": + if now > cursor: + stage_intervals["model"].append((cursor, now)) + model_step_count += 1 + elif phase == "post_tool" and now > cursor: + stage_intervals["cliDiscoveryAndExec"].append((cursor, now)) + phase = "done" + cursor = now + + if chat_ended_at > cursor: + if phase == "model": + stage_intervals["model"].append((cursor, float(chat_ended_at))) + model_step_count += 1 + elif phase == "post_tool": + stage_intervals["cliDiscoveryAndExec"].append((cursor, float(chat_ended_at))) + + partition = partition_stage_intervals(wall_started_at, wall_ended_at, stage_intervals) + ttfa_seconds = round(save_span[1] - wall_started_at, 3) if save_span is not None else None + ttc_seconds = round(publish_span[1] - wall_started_at, 3) if publish_span is not None else None + return { + **partition, + "ttfaSeconds": ttfa_seconds, + "ttcSeconds": ttc_seconds, + "counts": { + "modelRequests": model_step_count, + "foregroundModelRequests": model_step_count, + "backgroundModelRequests": 0, + "nativeToolCalls": tool_call_count, + "cliTransportCalls": (1 if setup_span else 0) + (1 if save_span else 0) + (1 if publish_span else 0), + "helpProbes": 0, + "inspectCalls": inspect_call_count, + "renderCalls": 1 if publish_span is not None else 0, + "failedToolCalls": failed_tool_count, + }, + "streamError": stream_error, + } + + +def probe_video_file(video_path: Path) -> dict[str, Any]: + if not video_path.is_file() or video_path.stat().st_size == 0: + return {"ok": False, "reason": "missing_or_empty_file"} + ffprobe_bin = shutil.which("ffprobe") + if not ffprobe_bin: + return {"ok": False, "reason": "ffprobe_not_found"} + proc = subprocess.run( + [ + ffprobe_bin, + "-v", + "error", + "-show_entries", + "format=duration,size:stream=index,codec_type,codec_name,width,height,r_frame_rate", + "-of", + "json", + str(video_path), + ], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if proc.returncode != 0: + return {"ok": False, "reason": f"ffprobe_exit_{proc.returncode}"} + try: + info = json.loads(proc.stdout) + except json.JSONDecodeError: + return {"ok": False, "reason": "ffprobe_invalid_json"} + streams = info.get("streams") or [] + video_stream = next((s for s in streams if s.get("codec_type") == "video"), None) + audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), None) + if video_stream is None: + return {"ok": False, "reason": "missing_video_stream"} + fmt = info.get("format") or {} + duration_raw = fmt.get("duration") + duration_sec = float(duration_raw) if duration_raw is not None else None + fps_raw = str(video_stream.get("r_frame_rate") or "0/1") + num, _, den = fps_raw.partition("/") + fps_val = round(float(num) / float(den), 3) if den and float(den) != 0 else None + return { + "ok": True, + "probed": True, + "bytes": video_path.stat().st_size, + "codec": video_stream.get("codec_name"), + "width": video_stream.get("width"), + "height": video_stream.get("height"), + "fps": fps_val, + "durationSeconds": round(duration_sec, 3) if duration_sec is not None else None, + "hasAudio": audio_stream is not None, + } + + +def load_reopened_disk_snapshot(project_dir: Path, project_id: str | None) -> dict[str, Any] | None: + if not project_id: + return None + if project_dir.parent.name != "projects": + return None + repo_root = project_dir.parent.parent + if not (repo_root / ".opendirector").is_dir(): + return None + from uuid import UUID + + from opendirector.infrastructure.creation_projects import CreationProjects + from opendirector.infrastructure.local_projects import LocalProjects + + reopened = CreationProjects(LocalProjects(repo_root)).snapshot(UUID(str(project_id))) + return reopened.model_dump(mode="json") + + +def verify_project_deliverables( + snapshot: dict[str, Any], + project_dir: Path, + *, + expected_duration: float = 30.0, + duration_tolerance: float = 0.5, + expected_width: int = 1920, + expected_height: int = 1080, + expected_fps: float = 30.0, + expected_codec: str = "h264", +) -> dict[str, Any]: + failures: list[str] = [] + project_meta = snapshot.get("project") if isinstance(snapshot.get("project"), dict) else {} + reopened = load_reopened_disk_snapshot(project_dir, project_meta.get("id")) + effective_snapshot = reopened if reopened is not None else snapshot + canvas_items = effective_snapshot.get("canvasItems") or [] + editor_docs = effective_snapshot.get("editorDocuments") or [] + assets = effective_snapshot.get("assets") or [] + + editors_by_id = {str(doc.get("id")): doc for doc in editor_docs if isinstance(doc, dict)} + assets_by_id = {str(asset.get("id")): asset for asset in assets if isinstance(asset, dict)} + + motion_items = [ + item + for item in canvas_items + if isinstance(item, dict) + and item.get("kind") == "motion" + and item.get("visible", True) + and isinstance(item.get("binding"), dict) + and item["binding"].get("role") == "editor" + ] + selected_motion_item: dict[str, Any] | None = None + selected_motion_doc: dict[str, Any] | None = None + for item in motion_items: + obj_ref = item["binding"].get("objectRef") or {} + doc = editors_by_id.get(str(obj_ref.get("id") or "")) + if doc and doc.get("kind") == "motion": + selected_motion_item = item + selected_motion_doc = doc + break + + motion_facts: dict[str, Any] = {} + if selected_motion_item is None or selected_motion_doc is None: + failures.append("missing_editable_motion_node_or_document") + else: + data = selected_motion_doc.get("data") or {} + web = data.get("web") or {} + html = str(web.get("html") or "") + css = str(web.get("css") or "") + script = str(web.get("script") or "") + duration = float(data.get("duration") or 0.0) + clip_ids = [m[0] or m[1] for m in _CLIP_ID_RE.findall(html)] + motion_facts = { + "itemId": selected_motion_item.get("id"), + "editorId": selected_motion_doc.get("id"), + "revision": selected_motion_doc.get("revision"), + "duration": duration, + "width": data.get("width"), + "height": data.get("height"), + "fps": data.get("fps"), + "clipCount": len(clip_ids), + "htmlChars": len(html), + "cssChars": len(css), + "scriptChars": len(script), + } + if not html.strip(): + failures.append("empty_motion_web_html") + if abs(duration - expected_duration) > duration_tolerance: + failures.append(f"motion_duration_mismatch:{duration}") + + video_items = [ + item + for item in canvas_items + if isinstance(item, dict) + and item.get("kind") == "video" + and item.get("visible", True) + and isinstance(item.get("binding"), dict) + and item["binding"].get("role") == "material" + ] + selected_video_item: dict[str, Any] | None = None + selected_video_asset: dict[str, Any] | None = None + for item in reversed(video_items): + obj_ref = item["binding"].get("objectRef") or {} + asset = assets_by_id.get(str(obj_ref.get("assetId") or "")) + if asset and asset.get("kind") == "video": + selected_video_item = item + selected_video_asset = asset + break + + video_facts: dict[str, Any] = {} + if selected_video_item is None or selected_video_asset is None: + failures.append("missing_published_video_node_or_asset") + else: + rel_path = str(selected_video_asset.get("path") or "") + file_path = (project_dir / rel_path).resolve() if rel_path else Path() + probe = probe_video_file(file_path) if rel_path else {"ok": False, "reason": "empty_asset_path"} + provenance = selected_video_asset.get("provenance") or {} + meta = selected_video_asset.get("metadata") or {} + video_facts = { + "itemId": selected_video_item.get("id"), + "assetId": selected_video_asset.get("id"), + "provenanceSource": provenance.get("source"), + "metadataDurationSeconds": meta.get("durationSeconds"), + "probe": probe, + } + if not probe.get("ok") or not probe.get("probed"): + failures.append(f"video_probe_failed:{probe.get('reason')}") + else: + if probe.get("codec") != expected_codec: + failures.append(f"video_codec_mismatch:{probe.get('codec')}") + if probe.get("width") != expected_width or probe.get("height") != expected_height: + failures.append(f"video_dimensions_mismatch:{probe.get('width')}x{probe.get('height')}") + probed_fps = probe.get("fps") + if not isinstance(probed_fps, (int, float)) or abs(float(probed_fps) - expected_fps) > 0.5: + failures.append(f"video_fps_mismatch:{probed_fps}") + probed_dur = probe.get("durationSeconds") + if not isinstance(probed_dur, (int, float)) or abs(float(probed_dur) - expected_duration) > duration_tolerance: + failures.append(f"video_duration_mismatch:{probed_dur}") + + disk_project_file = project_dir / "project.json" + if not disk_project_file.is_file(): + failures.append("missing_persisted_project_json") + + return { + "passed": len(failures) == 0, + "failures": failures, + "motion": motion_facts, + "video": video_facts, + } + + +def discover_parent_git_root(workspace_root: Path) -> Path | None: + dot_git = workspace_root.resolve() / ".git" + if not dot_git.is_file(): + return None + try: + raw = dot_git.read_text(encoding="utf-8", errors="replace").strip() + except OSError: + return None + if not raw.startswith("gitdir:"): + return None + gitdir = Path(raw.split(":", 1)[1].strip()) + if not gitdir.is_absolute(): + gitdir = Path(os.path.normpath(workspace_root.resolve() / gitdir)) + for ancestor in gitdir.parents: + if ancestor.name == ".git": + return ancestor.parent + return None + + +def scrub_root_variants(text: str, root: Path, placeholder: str, home_path: Path) -> str: + resolved = root.resolve() + text = text.replace(str(resolved), placeholder) + text = text.replace(str(root), placeholder) + try: + rel_home = resolved.relative_to(home_path).as_posix() + except ValueError: + rel_home = "" + if rel_home: + escaped_rel = re.escape(rel_home) + text = re.sub(rf"(?:\.\./)+{escaped_rel}\b", placeholder, text) + text = text.replace(f"/{rel_home}", placeholder) + text = text.replace(rel_home, placeholder) + for ancestor in resolved.parents: + if ancestor == home_path or home_path not in ancestor.parents: + break + anc_rel = ancestor.relative_to(home_path).as_posix() + text = text.replace(str(ancestor), "") + text = re.sub(rf"(?:\.\./)+{re.escape(anc_rel)}(?=[/\"'\s]|$)", "", text) + text = re.sub(rf"/{re.escape(anc_rel)}(?=[/\"'\s]|$)", "", text) + return text + + +def sanitize_text( + raw: str, + *, + secrets_to_scrub: tuple[str, ...] = (), + workspace_root: Path | None = None, + bench_root: Path | None = None, +) -> str: + text = raw + for secret in secrets_to_scrub: + if secret and len(secret) >= 6: + text = text.replace(secret, "[REDACTED]") + text = _BEARER_RE.sub("Bearer [REDACTED]", text) + text = _SK_TOKEN_RE.sub("[REDACTED_KEY]", text) + text = _DATA_URL_RE.sub("data:image/[omitted]", text) + text = _TMP_AGENT_RE.sub("", text) + text = _VAR_FOLDERS_RE.sub("", text) + home_path = Path.home().resolve() + if bench_root is not None: + text = scrub_root_variants(text, bench_root, "", home_path) + if workspace_root is not None: + text = scrub_root_variants(text, workspace_root, "", home_path) + parent_repo = discover_parent_git_root(workspace_root) + if parent_repo is not None: + text = scrub_root_variants(text, parent_repo, "", home_path) + home = str(home_path) + if home and home != "/": + text = text.replace(home, "") + raw_home = str(Path.home()) + if raw_home and raw_home != "/": + text = text.replace(raw_home, "") + user = os.environ.get("USER") or os.environ.get("USERNAME") or "" + if user and len(user) >= 2: + text = text.replace(f"/Users/{user}", "") + text = text.replace(f"/home/{user}", "") + text = re.sub(rf"\b{re.escape(user)}\b", "", text) + return text + + +def sanitize_model_jsonl_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]: + sanitized: list[dict[str, Any]] = [] + for item in records: + event = item.get("event") + if event == "model.reasoning": + continue + base: dict[str, Any] = { + "event": event, + "turnId": item.get("turnId"), + "requestId": item.get("requestId"), + "timestamp": item.get("timestamp"), + } + if event == "model.request": + payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} + messages = payload.get("messages") if isinstance(payload.get("messages"), list) else [] + base.update( + { + "model": payload.get("model"), + "thinking": payload.get("thinking"), + "reasoningEffort": payload.get("reasoning_effort"), + "maxTokens": payload.get("max_tokens") or payload.get("max_completion_tokens"), + "hasTools": bool(payload.get("tools")), + "messageCount": len(messages), + "payloadBytes": len(json.dumps(payload, ensure_ascii=False).encode("utf-8")), + } + ) + else: + for key in ("status", "elapsedMs", "forwardedBytes", "error"): + if key in item: + base[key] = item[key] + sanitized.append(base) + return sanitized + + +def build_sanitized_archive( + output_dir: Path, + zip_path: Path, + *, + secrets_to_scrub: tuple[str, ...] = (), + workspace_root: Path | None = None, +) -> Path: + summary_path = output_dir / "summary.json" + zip_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + if summary_path.is_file(): + raw_summary = summary_path.read_text(encoding="utf-8") + archive.writestr( + "summary.json", + sanitize_text( + raw_summary, + secrets_to_scrub=secrets_to_scrub, + workspace_root=workspace_root, + bench_root=output_dir, + ), + ) + runs_dir = output_dir / "runs" + if runs_dir.is_dir(): + for trial_dir in sorted(p for p in runs_dir.iterdir() if p.is_dir()): + prefix = f"runs/{trial_dir.name}" + for fname in ("trial_result.json", "assistant.sse.jsonl", "motion_director.sse.jsonl", "timing.json"): + fpath = trial_dir / fname + if fpath.is_file(): + cleaned = sanitize_text( + fpath.read_text(encoding="utf-8", errors="replace"), + secrets_to_scrub=secrets_to_scrub, + workspace_root=workspace_root, + bench_root=output_dir, + ) + archive.writestr(f"{prefix}/{fname}", cleaned) + model_path = trial_dir / "model.jsonl" + if model_path.is_file(): + redacted_lines = sanitize_model_jsonl_records(load_jsonl(model_path)) + archive.writestr( + f"{prefix}/model.redacted.jsonl", + "\n".join(json.dumps(r, ensure_ascii=False) for r in redacted_lines) + ("\n" if redacted_lines else ""), + ) + opencode_path = trial_dir / "opencode.jsonl" + if opencode_path.is_file(): + cleaned_oc = sanitize_text( + opencode_path.read_text(encoding="utf-8", errors="replace"), + secrets_to_scrub=secrets_to_scrub, + workspace_root=workspace_root, + bench_root=output_dir, + ) + archive.writestr(f"{prefix}/opencode.sanitized.jsonl", cleaned_oc) + return zip_path + + +def prepare_isolated_root( + source_root: Path, + isolated_root: Path, + model_selector: str | None, +) -> tuple[dict[str, Any], tuple[str, ...]]: + src_models_path = source_root.resolve() / ".opendirector" / "models.json" + raw = json.loads(src_models_path.read_text(encoding="utf-8")) + models = raw.get("models") or [] + services = raw.get("services") or {} + agent_models = [m for m in models if isinstance(m, dict) and m.get("kind") == "agent"] + selected: dict[str, Any] | None = None + if model_selector: + selected = next( + ( + m + for m in agent_models + if m.get("id") == model_selector or m.get("modelId") == model_selector + ), + None, + ) + else: + selected = agent_models[0] if agent_models else None + if selected is None: + raise RuntimeError(f"Agent model '{model_selector}' not found in {src_models_path}") + + kept_services: dict[str, Any] = {} + secrets_found: list[str] = [] + provider_id = selected.get("providerId") + if isinstance(provider_id, str) and provider_id in services: + kept_services[provider_id] = services[provider_id] + svc_key = services[provider_id].get("apiKey") + if isinstance(svc_key, str) and svc_key: + secrets_found.append(svc_key) + direct_key = selected.get("apiKey") + if isinstance(direct_key, str) and direct_key: + secrets_found.append(direct_key) + + cfg_dir = isolated_root / ".opendirector" + cfg_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + out_models = { + "version": 1, + "services": kept_services, + "models": [selected], + } + models_file = cfg_dir / "models.json" + models_file.write_text(json.dumps(out_models, ensure_ascii=False, indent=2), encoding="utf-8") + if os.name == "posix": + cfg_dir.chmod(0o700) + models_file.chmod(0o600) + + resolved_url = selected.get("url") or (kept_services.get(provider_id, {}).get("url") if provider_id else None) + public_meta = { + "id": selected["id"], + "modelId": selected["modelId"], + "host": urlsplit(str(resolved_url or "")).hostname, + "inputModalities": selected.get("inputModalities") or ["text"], + } + return public_meta, tuple(secrets_found) + + +def pick_free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def collect_environment_metadata(source_root: Path) -> dict[str, Any]: + git_sha = "unknown" + git_proc = subprocess.run( + ["git", "rev-parse", "HEAD"], + cwd=source_root, + capture_output=True, + text=True, + check=False, + ) + if git_proc.returncode == 0: + git_sha = git_proc.stdout.strip() + + opencode_pkg = source_root / "node_modules" / "opencode-ai" / "package.json" + opencode_version = None + if opencode_pkg.is_file(): + try: + opencode_version = json.loads(opencode_pkg.read_text(encoding="utf-8")).get("version") + except (OSError, ValueError): + opencode_version = None + + ffmpeg_version = None + ffmpeg_bin = shutil.which("ffmpeg") + if ffmpeg_bin: + ff_proc = subprocess.run([ffmpeg_bin, "-version"], capture_output=True, text=True, check=False) + if ff_proc.returncode == 0 and ff_proc.stdout: + ffmpeg_version = ff_proc.stdout.splitlines()[0].strip() + + node_version = None + node_bin = shutil.which("node") + if node_bin: + node_proc = subprocess.run([node_bin, "--version"], capture_output=True, text=True, check=False) + if node_proc.returncode == 0: + node_version = node_proc.stdout.strip() + + return { + "commitSha": git_sha, + "pythonVersion": platform.python_version(), + "nodeVersion": node_version, + "platform": f"{platform.system()} {platform.release()} ({platform.machine()})", + "bundledOpenCodeVersion": opencode_version, + "motionDirectorHarness": "built-in stream_motion_director_chat (MAX_AGENT_STEPS=12)", + "ffmpeg": ffmpeg_version, + } + + +def stream_sse_json_events(response: httpx.Response, log_path: Path) -> list[dict[str, Any]]: + records: list[dict[str, Any]] = [] + data_lines: list[str] = [] + with log_path.open("w", encoding="utf-8") as handle: + for raw_line in response.iter_lines(): + line = raw_line.rstrip("\r") + if line.startswith("data:"): + data_lines.append(line[5:].lstrip(" ")) + continue + if not line and data_lines: + joined = "\n".join(data_lines).strip() + data_lines.clear() + if not joined or joined == "[DONE]": + continue + try: + parsed = json.loads(joined) + except json.JSONDecodeError: + continue + entry = { + "epoch": time.time(), + "monotonic": time.monotonic(), + "event": parsed, + } + records.append(entry) + handle.write(json.dumps(entry, ensure_ascii=False) + "\n") + handle.flush() + return records + + +def resolve_project_dir(projects_root: Path, project_id: str, fallback_name: str = "") -> Path: + direct = projects_root / project_id + if (direct / "project.json").is_file(): + return direct + if fallback_name: + named = projects_root / fallback_name + if (named / "project.json").is_file(): + return named + if projects_root.is_dir(): + for entry in projects_root.iterdir(): + proj_file = entry / "project.json" + if entry.is_dir() and proj_file.is_file(): + try: + meta = json.loads(proj_file.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if str(meta.get("id") or "") == project_id: + return entry + return direct + + +def create_and_open_project( + client: httpx.Client, + name: str, + session_id: str, +) -> tuple[str, dict[str, str]]: + project_id = str(uuid4()) + headers = { + "X-OpenDirector-Request": "1", + "X-OpenDirector-Session": session_id, + } + execute_project_command( + client, + project_id, + headers, + "project.create", + {"name": name}, + ) + opened = client.post( + f"/api/creation/projects/{project_id}/open", + headers={**headers, "X-OpenDirector-Persistent": "true"}, + ) + opened.raise_for_status() + return project_id, headers + + +def execute_project_command( + client: httpx.Client, + project_id: str, + headers: dict[str, str], + command_type: str, + payload: dict[str, Any], + *, + expected_versions: list[dict[str, Any]] | None = None, + command_id: str | None = None, +) -> dict[str, Any]: + body = { + "commandId": command_id or str(uuid4()), + "projectId": project_id, + "type": command_type, + "expectedVersions": expected_versions or [], + "payload": payload, + } + resp = client.post(f"/api/creation/projects/{project_id}/commands", json=body, headers=headers) + resp.raise_for_status() + data = resp.json() + receipt = data.get("receipt") or data + if receipt.get("status") not in {None, "applied"}: + raise RuntimeError(f"Command {command_type} rejected: {receipt}") + return data + + +def run_main_chat_trial( + *, + base_url: str, + projects_root: Path, + trial_dir: Path, + trial_index: int, + model_config_id: str, + thinking: str, + prompt: str, + runtime: str = "default", + timeout_seconds: float = 1500.0, +) -> dict[str, Any]: + trial_dir.mkdir(parents=True, exist_ok=True) + session_id = str(uuid4()) + turn_id = str(uuid4()) + project_name = f"bench-main-chat-{trial_index}" + with httpx.Client(base_url=base_url, timeout=httpx.Timeout(timeout_seconds, connect=15.0)) as client: + project_id, headers = create_and_open_project(client, project_name, session_id) + sse_log = trial_dir / "assistant.sse.jsonl" + wall_started_at = time.time() + mono_started = time.monotonic() + http_error: str | None = None + sse_records: list[dict[str, Any]] = [] + try: + with client.stream( + "POST", + f"/api/creation/projects/{project_id}/assistant/turns", + headers={**headers, "Accept": "text/event-stream"}, + json={ + "id": turn_id, + "text": prompt, + "runtime": runtime, + "modelId": model_config_id, + "thinking": thinking, + "skills": [], + }, + ) as response: + response.raise_for_status() + sse_records = stream_sse_json_events(response, sse_log) + except Exception as exc: + http_error = f"{type(exc).__name__}: {exc}" + mono_ended = time.monotonic() + wall_ended_at = wall_started_at + (mono_ended - mono_started) + + snap_resp = client.get(f"/api/creation/projects/{project_id}", headers=headers) + snap_resp.raise_for_status() + snapshot = snap_resp.json() + + project_dir = resolve_project_dir(projects_root, project_id, project_name) + agent_runs_dir = project_dir / "agent-runs" + opencode_src = agent_runs_dir / f"{turn_id}.opencode.jsonl" + model_src = agent_runs_dir / f"{turn_id}.model.jsonl" + timing_src = agent_runs_dir / "timing" / f"{turn_id}.json" + + if opencode_src.is_file(): + shutil.copy2(opencode_src, trial_dir / "opencode.jsonl") + if model_src.is_file(): + shutil.copy2(model_src, trial_dir / "model.jsonl") + timing_ledger: dict[str, Any] | None = None + if timing_src.is_file(): + shutil.copy2(timing_src, trial_dir / "timing.json") + timing_ledger = json.loads(timing_src.read_text(encoding="utf-8")) + + analysis = analyze_main_chat_traces( + wall_started_at=wall_started_at, + wall_ended_at=wall_ended_at, + sse_records=sse_records, + opencode_records=load_jsonl(opencode_src), + model_records=load_jsonl(model_src), + timing_ledger=timing_ledger, + ) + deliverables = verify_project_deliverables(snapshot, project_dir) + if deliverables["passed"] and deliverables["video"].get("assetId"): + asset_id = deliverables["video"]["assetId"] + asset_entry = next((a for a in snapshot.get("assets", []) if a.get("id") == asset_id), None) + if asset_entry and asset_entry.get("path"): + src_mp4 = project_dir / asset_entry["path"] + if src_mp4.is_file(): + shutil.copy2(src_mp4, trial_dir / "published.mp4") + + succeeded = http_error is None and analysis.get("turnError") is None and deliverables["passed"] + result = { + "path": "main_chat", + "trial": trial_index, + "projectId": project_id, + "turnId": turn_id, + "runtime": runtime, + "thinking": thinking, + "prompt": prompt, + "succeeded": succeeded, + "httpError": http_error, + "rawSpans": { + "wallStartedAt": wall_started_at, + "wallEndedAt": wall_ended_at, + }, + "deliverables": deliverables, + "timing": analysis, + } + (trial_dir / "trial_result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") + return result + + +def run_motion_director_trial( + *, + base_url: str, + projects_root: Path, + trial_dir: Path, + trial_index: int, + model_config_id: str, + thinking: str, + prompt: str, + timeout_seconds: float = 900.0, +) -> dict[str, Any]: + trial_dir.mkdir(parents=True, exist_ok=True) + session_id = str(uuid4()) + editor_id = str(uuid4()) + item_id = str(uuid4()) + initial_web = default_empty_web_doc(1920, 1080) + + project_name = f"bench-motion-director-{trial_index}" + with httpx.Client(base_url=base_url, timeout=httpx.Timeout(timeout_seconds, connect=15.0)) as client: + project_id, headers = create_and_open_project(client, project_name, session_id) + wall_started_at = time.time() + mono_started = time.monotonic() + + def now_epoch() -> float: + return wall_started_at + (time.monotonic() - mono_started) + + setup_start = now_epoch() + http_error: str | None = None + sse_records: list[dict[str, Any]] = [] + setup_span: tuple[float, float] | None = None + save_span: tuple[float, float] | None = None + publish_span: tuple[float, float] | None = None + chat_started = setup_start + chat_ended = setup_start + latest_web = initial_web + latest_duration = 8.0 + + try: + execute_project_command( + client, + project_id, + headers, + "creation.batch", + { + "operations": [ + { + "type": "editor.create", + "payload": { + "document": { + "id": editor_id, + "projectId": project_id, + "kind": "motion", + "data": { + "width": 1920, + "height": 1080, + "fps": 30, + "duration": 8.0, + "web": initial_web, + }, + } + }, + }, + { + "type": "canvas.show", + "payload": { + "item": { + "id": item_id, + "projectId": project_id, + "kind": "motion", + "title": "OpenDirector 30s Motion", + "position": {"x": 120.0, "y": 120.0}, + "width": 352.0, + "height": 198.0, + "binding": { + "role": "editor", + "objectRef": { + "objectType": "editor_document", + "id": editor_id, + "kind": "motion", + }, + }, + } + }, + }, + ], + }, + ) + setup_span = (setup_start, now_epoch()) + + chat_started = now_epoch() + sse_log = trial_dir / "motion_director.sse.jsonl" + with client.stream( + "POST", + "/api/creation/motion/chat", + headers={**headers, "Accept": "text/event-stream"}, + json={ + "projectId": project_id, + "messages": [{"role": "user", "content": prompt}], + "modelId": model_config_id, + "thinking": thinking, + "language": "zh-CN", + "width": 1920, + "height": 1080, + "fps": 30, + "duration": 8.0, + "currentWeb": initial_web, + }, + ) as response: + response.raise_for_status() + sse_records = stream_sse_json_events(response, sse_log) + chat_ended = now_epoch() + + for rec in sse_records: + ev = rec.get("event") + if isinstance(ev, dict) and ev.get("type") == "web_update": + if isinstance(ev.get("web"), dict): + latest_web = ev["web"] + if isinstance(ev.get("duration"), (int, float)): + latest_duration = float(ev["duration"]) + + if str(latest_web.get("html") or "").strip(): + save_start = now_epoch() + execute_project_command( + client, + project_id, + headers, + "editor.save", + { + "document": { + "id": editor_id, + "projectId": project_id, + "kind": "motion", + "revision": 1, + "data": { + "width": 1920, + "height": 1080, + "fps": 30, + "duration": latest_duration, + "web": latest_web, + }, + } + }, + expected_versions=[ + { + "objectType": "editor_document", + "id": editor_id, + "revision": 1, + } + ], + ) + save_span = (save_start, now_epoch()) + + pub_start = now_epoch() + publish_cmd_id = str(uuid5(uuid4(), "motion-publish")) + prep_resp = client.post( + "/api/creation/motion/publish-prepare", + headers=headers, + json={ + "projectId": project_id, + "itemId": item_id, + "editorId": editor_id, + "commandId": publish_cmd_id, + "title": "OpenDirector 30s Motion.mp4", + }, + ) + prep_resp.raise_for_status() + + start_job = client.post( + "/api/creation/motion/render-jobs", + headers=headers, + json={ + "projectId": project_id, + "web": latest_web, + "width": 1920, + "height": 1080, + "fps": 30, + "duration": latest_duration, + "mediaBindings": [], + "audioVolume": 1.0, + "videoAudioVolume": 1.0, + }, + ) + start_job.raise_for_status() + job_id = str(start_job.json()["jobId"]) + + deadline = time.monotonic() + 360.0 + job_status = start_job.json() + while job_status.get("status") not in {"done", "failed", "cancelled"}: + if time.monotonic() >= deadline: + raise TimeoutError("Timed out polling motion render job") + time.sleep(0.25) + poll_resp = client.get(f"/api/creation/motion/render-jobs/{job_id}", headers=headers) + poll_resp.raise_for_status() + job_status = poll_resp.json() + + if job_status.get("status") != "done": + raise RuntimeError(f"Motion render job ended with status={job_status.get('status')}: {job_status}") + + pub_resp = client.post( + f"/api/creation/motion/render-jobs/{job_id}/publish", + headers=headers, + json={ + "projectId": project_id, + "itemId": item_id, + "editorId": editor_id, + "commandId": publish_cmd_id, + "title": "OpenDirector 30s Motion.mp4", + }, + ) + pub_resp.raise_for_status() + publish_span = (pub_start, now_epoch()) + except Exception as exc: + http_error = f"{type(exc).__name__}: {exc}" + + wall_ended_at = now_epoch() + snap_resp = client.get(f"/api/creation/projects/{project_id}", headers=headers) + snap_resp.raise_for_status() + snapshot = snap_resp.json() + + project_dir = resolve_project_dir(projects_root, project_id, project_name) + analysis = analyze_motion_director_traces( + wall_started_at=wall_started_at, + wall_ended_at=wall_ended_at, + setup_span=setup_span, + chat_started_at=chat_started, + chat_ended_at=chat_ended, + sse_records=sse_records, + save_span=save_span, + publish_span=publish_span, + ) + deliverables = verify_project_deliverables(snapshot, project_dir) + if deliverables["passed"] and deliverables["video"].get("assetId"): + asset_id = deliverables["video"]["assetId"] + asset_entry = next((a for a in snapshot.get("assets", []) if a.get("id") == asset_id), None) + if asset_entry and asset_entry.get("path"): + src_mp4 = project_dir / asset_entry["path"] + if src_mp4.is_file(): + shutil.copy2(src_mp4, trial_dir / "published.mp4") + + succeeded = http_error is None and analysis.get("streamError") is None and deliverables["passed"] + result = { + "path": "motion_director", + "trial": trial_index, + "projectId": project_id, + "editorId": editor_id, + "itemId": item_id, + "thinking": thinking, + "prompt": prompt, + "succeeded": succeeded, + "httpError": http_error, + "rawSpans": { + "wallStartedAt": wall_started_at, + "wallEndedAt": wall_ended_at, + "setupSpan": list(setup_span) if setup_span is not None else None, + "chatStartedAt": chat_started, + "chatEndedAt": chat_ended, + "saveSpan": list(save_span) if save_span is not None else None, + "publishSpan": list(publish_span) if publish_span is not None else None, + }, + "deliverables": deliverables, + "timing": analysis, + } + (trial_dir / "trial_result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") + return result + + +def summarize_path_results(trials: list[dict[str, Any]]) -> dict[str, Any]: + all_durations = [float(t["timing"]["endToEndSeconds"]) for t in trials] + passed = [t for t in trials if t.get("succeeded")] + passed_durations = [float(t["timing"]["endToEndSeconds"]) for t in passed] + stage_medians: dict[str, float | None] = {} + stage_means: dict[str, float | None] = {} + source_trials = passed if passed else trials + for key in STAGE_KEYS: + vals = [float(t["timing"]["stages"][key]) for t in source_trials] + stage_medians[key] = round(statistics.median(vals), 3) if vals else None + stage_means[key] = round(statistics.mean(vals), 3) if vals else None + dominant = None + if source_trials: + ranked = sorted( + ((stage_medians[k] or 0.0, k) for k in STAGE_KEYS), + reverse=True, + ) + dominant = ranked[0][1] + return { + "totalRuns": len(trials), + "succeededRuns": len(passed), + "failedRuns": len(trials) - len(passed), + "allEndToEndSeconds": all_durations, + "medianEndToEndSeconds": round(statistics.median(passed_durations), 3) if passed_durations else None, + "meanEndToEndSeconds": round(statistics.mean(passed_durations), 3) if passed_durations else None, + "minEndToEndSeconds": round(min(passed_durations), 3) if passed_durations else None, + "maxEndToEndSeconds": round(max(passed_durations), 3) if passed_durations else None, + "stageMedianSeconds": stage_medians, + "stageMeanSeconds": stage_means, + "dominantStage": dominant, + } + + +def wait_for_server(base_url: str, proc: subprocess.Popen[str], timeout_seconds: float = 30.0) -> None: + deadline = time.monotonic() + timeout_seconds + headers = {"X-OpenDirector-Request": "1"} + while time.monotonic() < deadline: + if proc.poll() is not None: + raise RuntimeError(f"Isolated API server exited early with code {proc.returncode}") + try: + resp = httpx.get(f"{base_url}/api/model-configs", headers=headers, timeout=2.0) + if resp.status_code == 200: + return + except httpx.HTTPError: + pass + time.sleep(0.25) + raise TimeoutError(f"Timed out waiting for isolated API server at {base_url}") + + +def command_run(options: argparse.Namespace) -> int: + source_root = Path(options.source_root).expanduser().resolve() + output_dir = Path(options.output_dir).expanduser().resolve() + output_dir.mkdir(parents=True, exist_ok=True) + isolated_root = output_dir / "isolated-root" + model_meta, secrets_found = prepare_isolated_root(source_root, isolated_root, options.model) + env_meta = collect_environment_metadata(source_root) + + selected_paths = [p.strip() for p in options.paths.split(",") if p.strip()] + for name in selected_paths: + if name not in {"main_chat", "motion_director"}: + raise ValueError(f"Unsupported benchmark path: {name}") + + server_proc: subprocess.Popen[str] | None = None + server_log_handle = None + base_url = options.base_url + projects_root = ( + Path(options.projects_root).expanduser().resolve() + if options.projects_root + else isolated_root / "projects" + ) + + try: + if not base_url: + port = pick_free_port() + base_url = f"http://127.0.0.1:{port}" + env = dict(os.environ) + env["OPENDIRECTOR_ROOT"] = str(isolated_root) + server_log_path = output_dir / "server.log" + server_log_handle = server_log_path.open("w", encoding="utf-8") + server_proc = subprocess.Popen( + [sys.executable, "-m", "opendirector_api.server", "--port", str(port), "--log-level", "info"], + cwd=source_root, + env=env, + stdout=server_log_handle, + stderr=subprocess.STDOUT, + text=True, + ) + wait_for_server(base_url, server_proc) + + all_trials: list[dict[str, Any]] = [] + runs_dir = output_dir / "runs" + for trial_idx in range(1, options.runs + 1): + for path_name in selected_paths: + trial_dir = runs_dir / f"{path_name}-run-{trial_idx:02d}" + existing_result = trial_dir / "trial_result.json" + if options.resume and existing_result.is_file(): + cached = json.loads(existing_result.read_text(encoding="utf-8")) + all_trials.append(cached) + print( + f"[bench] loaded cached {path_name} run {trial_idx}: " + f"succeeded={cached['succeeded']} e2e={cached['timing']['endToEndSeconds']}s", + flush=True, + ) + continue + print(f"[bench] starting {path_name} run {trial_idx}/{options.runs} ...", flush=True) + if path_name == "motion_director": + res = run_motion_director_trial( + base_url=base_url, + projects_root=projects_root, + trial_dir=trial_dir, + trial_index=trial_idx, + model_config_id=model_meta["id"], + thinking=options.thinking, + prompt=options.prompt, + ) + else: + res = run_main_chat_trial( + base_url=base_url, + projects_root=projects_root, + trial_dir=trial_dir, + trial_index=trial_idx, + model_config_id=model_meta["id"], + thinking=options.thinking, + prompt=options.prompt, + runtime=options.runtime, + ) + all_trials.append(res) + print( + f"[bench] finished {path_name} run {trial_idx}: " + f"succeeded={res['succeeded']} e2e={res['timing']['endToEndSeconds']}s " + f"stages={res['timing']['stages']}", + flush=True, + ) + + partial_summary = { + "environment": env_meta, + "model": model_meta, + "thinking": options.thinking, + "prompt": options.prompt, + "runtime": options.runtime, + "runsPerPath": options.runs, + "byPath": { + p: summarize_path_results([t for t in all_trials if t["path"] == p]) + for p in selected_paths + }, + "trials": all_trials, + } + (output_dir / "summary.json").write_text( + json.dumps(partial_summary, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + + if options.archive_path: + build_sanitized_archive( + output_dir, + Path(options.archive_path).expanduser().resolve(), + secrets_to_scrub=secrets_found, + workspace_root=source_root, + ) + finally: + if server_proc is not None and server_proc.poll() is None: + server_proc.terminate() + try: + server_proc.wait(timeout=10) + except subprocess.TimeoutExpired: + server_proc.kill() + server_proc.wait(timeout=5) + if server_log_handle is not None: + server_log_handle.close() + + return 0 + + +def reanalyze_trial_dir(trial_dir: Path, projects_root: Path) -> dict[str, Any]: + result_path = trial_dir / "trial_result.json" + trial = json.loads(result_path.read_text(encoding="utf-8")) + path_name = trial["path"] + trial_idx = int(trial["trial"]) + raw_spans = trial.get("rawSpans") if isinstance(trial.get("rawSpans"), dict) else {} + old_timing = trial.get("timing") if isinstance(trial.get("timing"), dict) else {} + + if path_name == "main_chat": + sse_records = load_jsonl(trial_dir / "assistant.sse.jsonl") + opencode_records = load_jsonl(trial_dir / "opencode.jsonl") + model_records = load_jsonl(trial_dir / "model.jsonl") + timing_path = trial_dir / "timing.json" + timing_ledger = json.loads(timing_path.read_text(encoding="utf-8")) if timing_path.is_file() else None + if isinstance(raw_spans.get("wallStartedAt"), (int, float)) and isinstance(raw_spans.get("wallEndedAt"), (int, float)): + wall_started_at = float(raw_spans["wallStartedAt"]) + wall_ended_at = float(raw_spans["wallEndedAt"]) + else: + ttfa_sec = old_timing.get("ttfaSeconds") + e2e_sec = float(old_timing.get("endToEndSeconds") or 0.0) + ttfa_anchor: float | None = None + if isinstance(ttfa_sec, (int, float)): + for row in sse_records: + ev = row.get("event") if isinstance(row.get("event"), dict) else {} + if ( + ev.get("type") == "tool" + and ev.get("status") == "complete" + and ev.get("name") in { + "opendirector canvas show", + "opendirector editor create", + "opendirector editor save", + "opendirector creation batch", + } + and isinstance(row.get("epoch"), (int, float)) + ): + ttfa_anchor = float(row["epoch"]) + break + if ttfa_anchor is not None and isinstance(ttfa_sec, (int, float)): + wall_started_at = ttfa_anchor - float(ttfa_sec) + elif sse_records and isinstance(sse_records[-1].get("epoch"), (int, float)): + wall_started_at = float(sse_records[-1]["epoch"]) - e2e_sec + else: + wall_started_at = 0.0 + wall_ended_at = wall_started_at + e2e_sec + trial["timing"] = analyze_main_chat_traces( + wall_started_at=wall_started_at, + wall_ended_at=wall_ended_at, + sse_records=sse_records, + opencode_records=opencode_records, + model_records=model_records, + timing_ledger=timing_ledger, + ) + project_dir = resolve_project_dir(projects_root, str(trial.get("projectId") or ""), f"bench-main-chat-{trial_idx}") + else: + sse_records = load_jsonl(trial_dir / "motion_director.sse.jsonl") + project_dir = resolve_project_dir(projects_root, str(trial.get("projectId") or ""), f"bench-motion-director-{trial_idx}") + if isinstance(raw_spans.get("wallStartedAt"), (int, float)) and isinstance(raw_spans.get("wallEndedAt"), (int, float)): + wall_started_at = float(raw_spans["wallStartedAt"]) + wall_ended_at = float(raw_spans["wallEndedAt"]) + s_raw = raw_spans.get("setupSpan") + setup_span = (float(s_raw[0]), float(s_raw[1])) if isinstance(s_raw, list) and len(s_raw) == 2 else None + chat_started = float(raw_spans.get("chatStartedAt") or wall_started_at) + chat_ended = float(raw_spans.get("chatEndedAt") or wall_ended_at) + sv_raw = raw_spans.get("saveSpan") + save_span = (float(sv_raw[0]), float(sv_raw[1])) if isinstance(sv_raw, list) and len(sv_raw) == 2 else None + pb_raw = raw_spans.get("publishSpan") + publish_span = (float(pb_raw[0]), float(pb_raw[1])) if isinstance(pb_raw, list) and len(pb_raw) == 2 else None + else: + commit_mtimes: dict[str, float] = {} + commits_dir = project_dir / "commits" + if commits_dir.is_dir(): + for cfile in commits_dir.iterdir(): + if cfile.is_file() and cfile.suffix == ".json": + try: + cdata = json.loads(cfile.read_text(encoding="utf-8")) + ctype = str((cdata.get("command") or {}).get("type") or "") + if ctype: + commit_mtimes[ctype] = cfile.stat().st_mtime + except (OSError, ValueError): + continue + e2e_sec = float(old_timing.get("endToEndSeconds") or 0.0) + ttfa_sec = old_timing.get("ttfaSeconds") + first_sse = float(sse_records[0]["epoch"]) if sse_records else 0.0 + last_sse = float(sse_records[-1]["epoch"]) if sse_records else first_sse + t_save = commit_mtimes.get("editor.save") + if t_save is not None and isinstance(ttfa_sec, (int, float)): + wall_started_at = t_save - float(ttfa_sec) + else: + wall_started_at = first_sse + wall_ended_at = wall_started_at + e2e_sec + t_batch = commit_mtimes.get("creation.batch", first_sse) + setup_span = (wall_started_at, t_batch) if t_batch > wall_started_at else None + chat_started = t_batch + chat_ended = last_sse + if t_save is not None: + save_span = (last_sse, t_save) if t_save > last_sse else (t_save, t_save) + old_render = float((old_timing.get("stages") or {}).get("renderAndPublish") or 0.0) + pub_start = max(t_save, wall_ended_at - old_render) if old_render > 0 else t_save + publish_span = (pub_start, wall_ended_at) if wall_ended_at > pub_start else None + else: + save_span = None + publish_span = None + trial["timing"] = analyze_motion_director_traces( + wall_started_at=wall_started_at, + wall_ended_at=wall_ended_at, + setup_span=setup_span, + chat_started_at=chat_started, + chat_ended_at=chat_ended, + sse_records=sse_records, + save_span=save_span, + publish_span=publish_span, + ) + + if (project_dir / "project.json").is_file(): + reopened = load_reopened_disk_snapshot(project_dir, str(trial.get("projectId") or "")) + if reopened is not None: + trial["deliverables"] = verify_project_deliverables(reopened, project_dir) + err_field = trial["timing"].get("turnError") if path_name == "main_chat" else trial["timing"].get("streamError") + trial["succeeded"] = trial.get("httpError") is None and err_field is None and bool(trial["deliverables"].get("passed")) + result_path.write_text(json.dumps(trial, ensure_ascii=False, indent=2), encoding="utf-8") + return trial + + +def command_reanalyze(options: argparse.Namespace) -> int: + output_dir = Path(options.output_dir).expanduser().resolve() + projects_root = ( + Path(options.projects_root).expanduser().resolve() + if options.projects_root + else output_dir / "isolated-root" / "projects" + ) + runs_dir = output_dir / "runs" + trials: list[dict[str, Any]] = [] + if runs_dir.is_dir(): + for trial_dir in sorted(p for p in runs_dir.iterdir() if p.is_dir() and (p / "trial_result.json").is_file()): + trials.append(reanalyze_trial_dir(trial_dir, projects_root)) + trials.sort(key=lambda item: (int(item.get("trial") or 0), 0 if item.get("path") == "motion_director" else 1)) + summary_path = output_dir / "summary.json" + existing_summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.is_file() else {} + seen_paths: list[str] = [] + for item in trials: + pname = str(item.get("path") or "") + if pname and pname not in seen_paths: + seen_paths.append(pname) + updated_summary = { + **existing_summary, + "byPath": { + pname: summarize_path_results([t for t in trials if t.get("path") == pname]) + for pname in seen_paths + }, + "trials": trials, + } + summary_path.write_text(json.dumps(updated_summary, ensure_ascii=False, indent=2), encoding="utf-8") + return 0 + + +def command_archive(options: argparse.Namespace) -> int: + source_root = Path(options.source_root).expanduser().resolve() + output_dir = Path(options.output_dir).expanduser().resolve() + secrets_found: tuple[str, ...] = () + isolated_models = output_dir / "isolated-root" / ".opendirector" / "models.json" + if isolated_models.is_file(): + raw = json.loads(isolated_models.read_text(encoding="utf-8")) + found: list[str] = [] + for svc in (raw.get("services") or {}).values(): + if isinstance(svc, dict) and isinstance(svc.get("apiKey"), str) and svc["apiKey"]: + found.append(svc["apiKey"]) + for mdl in raw.get("models") or []: + if isinstance(mdl, dict) and isinstance(mdl.get("apiKey"), str) and mdl["apiKey"]: + found.append(mdl["apiKey"]) + secrets_found = tuple(found) + zip_out = build_sanitized_archive( + output_dir, + Path(options.zip_path).expanduser().resolve(), + secrets_to_scrub=secrets_found, + workspace_root=source_root, + ) + print(str(zip_out)) + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="bench_motion_paths.py") + sub = parser.add_subparsers(dest="subcommand", required=True) + + run_p = sub.add_parser("run") + run_p.add_argument("--output-dir", required=True) + run_p.add_argument("--source-root", default=".") + run_p.add_argument("--runs", type=int, default=3) + run_p.add_argument("--paths", default="motion_director,main_chat") + run_p.add_argument("--model", default="deepseek-flash") + run_p.add_argument("--thinking", choices=("auto", "low", "medium", "high"), default="low") + run_p.add_argument("--runtime", default="default") + run_p.add_argument("--prompt", default=DEFAULT_PROMPT) + run_p.add_argument("--base-url", default=None) + run_p.add_argument("--projects-root", default=None) + run_p.add_argument("--archive-path", default=None) + run_p.add_argument("--resume", action="store_true") + + arch_p = sub.add_parser("archive") + arch_p.add_argument("--output-dir", required=True) + arch_p.add_argument("--zip-path", required=True) + arch_p.add_argument("--source-root", default=".") + + re_p = sub.add_parser("reanalyze") + re_p.add_argument("--output-dir", required=True) + re_p.add_argument("--projects-root", default=None) + + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + options = parser.parse_args(argv) + if options.subcommand == "run": + return command_run(options) + if options.subcommand == "archive": + return command_archive(options) + if options.subcommand == "reanalyze": + return command_reanalyze(options) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_bench_motion_paths.py b/tests/test_bench_motion_paths.py new file mode 100644 index 000000000..4fab1cb40 --- /dev/null +++ b/tests/test_bench_motion_paths.py @@ -0,0 +1,710 @@ +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import zipfile + + +SCRIPT_PATH = Path(__file__).resolve().parents[1] / "scripts" / "bench_motion_paths.py" +SPEC = importlib.util.spec_from_file_location("bench_motion_paths", SCRIPT_PATH) +assert SPEC is not None and SPEC.loader is not None +bench = importlib.util.module_from_spec(SPEC) +sys.modules["bench_motion_paths"] = bench +SPEC.loader.exec_module(bench) + + +def test_classify_cli_command_distinguishes_help_probes_and_slide_copy(): + assert bench.classify_cli_command("opendirector motion render") == "renderAndPublish" + assert bench.classify_cli_command("opendirector motion inspect") == "inspectFrames" + assert bench.classify_cli_command("opendirector editor create") == "cliDiscoveryAndExec" + + assert ( + bench.classify_cli_command( + "bash", + "opendirector --project 123 motion render --publish-item-id 456", + ) + == "renderAndPublish" + ) + assert ( + bench.classify_cli_command( + "bash", + "opendirector motion render --help", + ) + == "cliDiscoveryAndExec" + ) + assert bench.is_help_probe("bash", "opendirector motion render --help") is True + assert bench.is_help_probe("bash", "opendirector editor create --help-field document") is True + assert bench.is_help_probe("bash", "opendirector motion render --publish-item-id 456") is False + + assert ( + bench.classify_cli_command( + "bash", + "python3 -c \"open('doc.json','w').write('feature: opendirector motion render')\"", + ) + == "cliDiscoveryAndExec" + ) + assert bench.classify_cli_command("read", "/tmp/work/frame_02.png") == "inspectFrames" + assert bench.classify_cli_command("read", "/tmp/work/SKILL.md") == "cliDiscoveryAndExec" + + +def test_partition_stage_intervals_prevents_nested_double_counting(): + result = bench.partition_stage_intervals( + 100.0, + 200.0, + { + "model": [(102.0, 122.0), (125.0, 132.0)], + "cliDiscoveryAndExec": [(122.0, 175.0)], + "inspectFrames": [(135.0, 140.0)], + "renderAndPublish": [(150.0, 174.0)], + }, + ) + stages = result["stages"] + assert result["endToEndSeconds"] == 100.0 + assert round(sum(stages.values()), 3) == 100.0 + assert stages["renderAndPublish"] == 24.0 + assert stages["inspectFrames"] == 5.0 + assert stages["cliDiscoveryAndExec"] == 24.0 + assert stages["model"] == 20.0 + assert stages["unattributed"] == 27.0 + + +def test_analyze_main_chat_traces_attributes_model_cli_inspect_and_render(): + model_records = [ + { + "event": "model.request", + "turnId": "t1", + "requestId": "r1", + "timestamp": 1001.0, + "payload": { + "model": "deepseek-flash", + "thinking": {"type": "disabled"}, + "max_tokens": 8192, + "tools": [{"type": "function"}], + "messages": [{"role": "user", "content": "prompt"}], + }, + }, + {"event": "model.response", "turnId": "t1", "requestId": "r1", "timestamp": 1002.0, "elapsedMs": 1000}, + { + "event": "model.completed", + "turnId": "t1", + "requestId": "r1", + "timestamp": 1011.0, + "elapsedMs": 10000, + "forwardedBytes": 4096, + }, + { + "event": "model.request", + "turnId": "t1", + "requestId": "r2", + "timestamp": 1011.5, + "payload": {"model": "deepseek-flash", "messages": [{"role": "user", "content": "title"}]}, + }, + { + "event": "model.completed", + "turnId": "t1", + "requestId": "r2", + "timestamp": 1013.5, + "elapsedMs": 2000, + "forwardedBytes": 256, + }, + ] + opencode_records = [ + { + "native": { + "type": "tool_use", + "part": { + "tool": "bash", + "state": { + "status": "completed", + "input": {"command": "opendirector --help"}, + "time": {"start": 1011500, "end": 1013000}, + }, + }, + } + }, + { + "native": { + "type": "tool_use", + "part": { + "tool": "bash", + "state": { + "status": "completed", + "input": {"command": "opendirector --project p1 editor create --file doc.json"}, + "time": {"start": 1014000, "end": 1016000}, + }, + }, + } + }, + { + "native": { + "type": "tool_use", + "part": { + "tool": "bash", + "state": { + "status": "completed", + "input": {"command": "opendirector --project p1 motion inspect --editor-id e1"}, + "time": {"start": 1017000, "end": 1020000}, + }, + }, + } + }, + { + "native": { + "type": "tool_use", + "part": { + "tool": "bash", + "state": { + "status": "completed", + "input": {"command": "opendirector --project p1 motion render --publish-item-id i1"}, + "time": {"start": 1021000, "end": 1045000}, + }, + }, + } + }, + ] + sse_records = [ + {"epoch": 1014.3, "event": {"type": "tool", "id": "c1", "name": "opendirector editor create", "status": "running"}}, + {"epoch": 1015.9, "event": {"type": "tool", "id": "c1", "name": "opendirector editor create", "status": "complete"}}, + {"epoch": 1017.2, "event": {"type": "tool", "id": "c2", "name": "opendirector motion inspect", "status": "running"}}, + {"epoch": 1019.9, "event": {"type": "tool", "id": "c2", "name": "opendirector motion inspect", "status": "complete"}}, + { + "epoch": 1021.3, + "event": { + "type": "tool", + "id": "c3", + "name": "opendirector motion render", + "status": "running", + "arguments": {"editorId": "e1", "publishItemId": "i1", "timeout": 300.0}, + }, + }, + { + "epoch": 1044.8, + "event": { + "type": "tool", + "id": "c3", + "name": "opendirector motion render", + "status": "complete", + "arguments": {"editorId": "e1", "publishItemId": "i1", "timeout": 300.0}, + }, + }, + { + "epoch": 1044.805, + "event": { + "type": "tool", + "id": "c4", + "name": "opendirector motion render", + "status": "complete", + "arguments": {"type": "object.get", "objectId": "obj-1", "revision": 1}, + }, + }, + {"epoch": 1046.0, "event": {"type": "end", "turnId": "t1", "error": None}}, + ] + timing_ledger = { + "calls": [ + {"id": "c1", "name": "opendirector editor create", "spawn": 0.2, "work": 1.4}, + {"id": "c2", "name": "opendirector motion inspect", "spawn": 0.2, "work": 2.5}, + {"id": "c3", "name": "opendirector motion render", "spawn": 0.2, "work": 23.3}, + {"id": "c4", "name": "opendirector motion render", "spawn": 0.0, "work": 0.005}, + ] + } + report = bench.analyze_main_chat_traces( + wall_started_at=1000.0, + wall_ended_at=1046.0, + sse_records=sse_records, + opencode_records=opencode_records, + model_records=model_records, + timing_ledger=timing_ledger, + ) + assert report["endToEndSeconds"] == 46.0 + assert round(sum(report["stages"].values()), 3) == 46.0 + assert report["stages"]["renderAndPublish"] == 24.0 + assert report["stages"]["inspectFrames"] == 3.0 + assert report["stages"]["cliDiscoveryAndExec"] == 3.5 + assert report["stages"]["model"] == 10.5 + assert report["ttfaSeconds"] == 15.9 + assert report["ttcSeconds"] == 44.8 + assert report["counts"]["cliTransportCalls"] == 4 + assert report["counts"]["helpProbes"] == 1 + assert report["counts"]["inspectCalls"] == 1 + assert report["counts"]["renderCalls"] == 1 + assert report["modelMeta"]["effectiveWireConfig"]["maxTokens"] == 8192 + + +def test_analyze_motion_director_traces_keeps_streaming_tool_deltas_in_model_stage(): + sse_records = [ + {"epoch": 2001.0, "event": {"type": "tool_start", "id": "call-1", "name": "replace_composition", "arguments": {}}}, + {"epoch": 2008.0, "event": {"type": "tool_progress", "id": "call-1", "name": "replace_composition", "summary": "9.8 KB"}}, + { + "epoch": 2021.0, + "event": { + "type": "tool_progress", + "id": "call-1", + "name": "replace_composition", + "arguments": {"duration": 30, "htmlChars": 6200}, + }, + }, + {"epoch": 2021.1, "event": {"type": "tool_end", "id": "call-1", "name": "replace_composition", "status": "complete"}}, + {"epoch": 2021.12, "event": {"type": "web_update", "duration": 30, "web": {"html": "
"}}}, + {"epoch": 2022.0, "event": {"type": "tool_start", "id": "call-2", "name": "inspect_frames", "arguments": {}}}, + { + "epoch": 2023.0, + "event": {"type": "tool_progress", "id": "call-2", "name": "inspect_frames", "arguments": {"times": [1, 8, 16, 26]}}, + }, + {"epoch": 2024.6, "event": {"type": "tool_end", "id": "call-2", "name": "inspect_frames", "status": "complete"}}, + {"epoch": 2026.0, "event": {"type": "delta", "text": "Done"}}, + {"epoch": 2027.0, "event": {"type": "done", "toolCount": 2, "webUpdated": True}}, + ] + report = bench.analyze_motion_director_traces( + wall_started_at=2000.0, + wall_ended_at=2048.0, + setup_span=(2000.0, 2000.4), + chat_started_at=2000.5, + chat_ended_at=2027.1, + sse_records=sse_records, + save_span=(2027.1, 2027.3), + publish_span=(2027.3, 2048.0), + ) + assert report["endToEndSeconds"] == 48.0 + assert round(sum(report["stages"].values()), 3) == 48.0 + assert report["stages"]["model"] == 24.78 + assert report["stages"]["inspectFrames"] == 1.6 + assert report["stages"]["renderAndPublish"] == 20.7 + assert report["stages"]["cliDiscoveryAndExec"] == 0.72 + assert report["ttfaSeconds"] == 27.3 + assert report["ttcSeconds"] == 48.0 + assert report["counts"]["modelRequests"] == 3 + assert report["counts"]["inspectCalls"] == 1 + + +def test_analyze_motion_director_traces_counts_one_model_step_per_multi_tool_batch(): + sse_records = [ + {"epoch": 3001.0, "event": {"type": "thinking"}}, + {"epoch": 3001.5, "event": {"type": "tool_start", "id": "s1", "name": "read_motion_skill", "arguments": {}}}, + {"epoch": 3001.6, "event": {"type": "tool_start", "id": "s2", "name": "read_motion_skill", "arguments": {}}}, + {"epoch": 3002.0, "event": {"type": "tool_progress", "id": "s1", "name": "read_motion_skill", "arguments": {"name": "a"}}}, + {"epoch": 3002.01, "event": {"type": "tool_progress", "id": "s2", "name": "read_motion_skill", "arguments": {"name": "b"}}}, + {"epoch": 3002.05, "event": {"type": "tool_end", "id": "s1", "name": "read_motion_skill", "status": "complete"}}, + {"epoch": 3002.06, "event": {"type": "tool_end", "id": "s2", "name": "read_motion_skill", "status": "complete"}}, + {"epoch": 3004.0, "event": {"type": "tool_start", "id": "m1", "name": "patch_css", "arguments": {}}}, + {"epoch": 3004.5, "event": {"type": "tool_start", "id": "m2", "name": "patch_script", "arguments": {}}}, + {"epoch": 3006.0, "event": {"type": "tool_progress", "id": "m1", "name": "patch_css", "arguments": {"cssChars": 200}}}, + {"epoch": 3006.1, "event": {"type": "tool_end", "id": "m1", "name": "patch_css", "status": "complete"}}, + {"epoch": 3006.12, "event": {"type": "web_update", "duration": 30, "web": {"html": "
"}}}, + {"epoch": 3006.3, "event": {"type": "tool_progress", "id": "m2", "name": "patch_script", "arguments": {"scriptChars": 120}}}, + {"epoch": 3006.4, "event": {"type": "tool_end", "id": "m2", "name": "patch_script", "status": "complete"}}, + {"epoch": 3006.42, "event": {"type": "web_update", "duration": 30, "web": {"html": "
"}}}, + {"epoch": 3007.5, "event": {"type": "delta", "text": "Finished"}}, + {"epoch": 3008.0, "event": {"type": "done", "toolCount": 4, "webUpdated": True}}, + ] + report = bench.analyze_motion_director_traces( + wall_started_at=3000.0, + wall_ended_at=3020.0, + setup_span=(3000.0, 3000.2), + chat_started_at=3000.2, + chat_ended_at=3008.0, + sse_records=sse_records, + save_span=(3008.0, 3008.1), + publish_span=(3008.1, 3020.0), + ) + assert report["counts"]["modelRequests"] == 3 + assert report["counts"]["nativeToolCalls"] == 4 + assert report["stages"]["model"] == 7.32 + assert report["stages"]["cliDiscoveryAndExec"] == 0.78 + assert report["stages"]["renderAndPublish"] == 11.9 + assert report["stages"]["unattributed"] == 0.0 + + +def test_verify_project_deliverables_checks_motion_document_and_published_video(tmp_path, monkeypatch): + project_dir = tmp_path / "p1" + assets_dir = project_dir / "assets" + assets_dir.mkdir(parents=True) + (project_dir / "project.json").write_text("{}", encoding="utf-8") + mp4_file = assets_dir / "out.mp4" + mp4_file.write_bytes(b"\x00\x00\x00\x18ftypmp42") + + monkeypatch.setattr( + bench, + "probe_video_file", + lambda path: { + "ok": True, + "probed": True, + "bytes": 12345, + "codec": "h264", + "width": 1920, + "height": 1080, + "fps": 30.0, + "durationSeconds": 30.0, + "hasAudio": False, + }, + ) + + valid_snapshot = { + "canvasItems": [ + { + "id": "item-motion", + "kind": "motion", + "visible": True, + "binding": {"role": "editor", "objectRef": {"id": "ed-motion", "kind": "motion"}}, + }, + { + "id": "item-video", + "kind": "video", + "visible": True, + "binding": {"role": "material", "objectRef": {"assetId": "asset-video", "kind": "video"}}, + }, + ], + "editorDocuments": [ + { + "id": "ed-motion", + "kind": "motion", + "revision": 2, + "data": { + "width": 1920, + "height": 1080, + "fps": 30, + "duration": 30.0, + "web": { + "html": '
OpenDirector
', + "css": "#stage {}", + "script": "", + }, + }, + } + ], + "assets": [ + { + "id": "asset-video", + "kind": "video", + "path": "assets/out.mp4", + "provenance": {"source": "rendered"}, + "metadata": {"durationSeconds": 30.0}, + } + ], + } + ok_res = bench.verify_project_deliverables(valid_snapshot, project_dir) + assert ok_res["passed"] is True + assert ok_res["motion"]["clipCount"] == 1 + assert ok_res["video"]["provenanceSource"] == "rendered" + + wrong_duration_snapshot = json.loads(json.dumps(valid_snapshot)) + wrong_duration_snapshot["editorDocuments"][0]["data"]["duration"] = 8.0 + bad_res = bench.verify_project_deliverables(wrong_duration_snapshot, project_dir) + assert bad_res["passed"] is False + assert any(reason.startswith("motion_duration_mismatch") for reason in bad_res["failures"]) + + monkeypatch.setattr( + bench, + "probe_video_file", + lambda path: { + "ok": True, + "probed": True, + "bytes": 12345, + "codec": "vp9", + "width": 1280, + "height": 720, + "fps": 24.0, + "durationSeconds": 30.0, + "hasAudio": False, + }, + ) + bad_spec = bench.verify_project_deliverables(valid_snapshot, project_dir) + assert bad_spec["passed"] is False + assert "video_codec_mismatch:vp9" in bad_spec["failures"] + assert "video_dimensions_mismatch:1280x720" in bad_spec["failures"] + assert "video_fps_mismatch:24.0" in bad_spec["failures"] + + +def test_probe_video_file_requires_ffprobe(tmp_path, monkeypatch): + mp4_file = tmp_path / "out.mp4" + mp4_file.write_bytes(b"\x00\x00\x00\x18ftypmp42") + monkeypatch.setattr(bench.shutil, "which", lambda name: None) + assert bench.probe_video_file(mp4_file) == {"ok": False, "reason": "ffprobe_not_found"} + + +def test_build_sanitized_archive_redacts_secrets_paths_and_raw_model_payloads(tmp_path, monkeypatch): + out_dir = tmp_path / "bench-out" + trial_dir = out_dir / "runs" / "main_chat-run-01" + trial_dir.mkdir(parents=True) + secret_key = "sk-live-super-secret-token-999999" + fake_home = tmp_path / "fake-home" + parent_repo = fake_home / "orca" / "OpenDirector" + (parent_repo / ".git" / "worktrees" / "pr").mkdir(parents=True) + workspace = fake_home / "orca" / "workspaces" / "OpenDirector" / "pr" + workspace.mkdir(parents=True) + (workspace / ".git").write_text(f"gitdir: {parent_repo / '.git' / 'worktrees' / 'pr'}\n", encoding="utf-8") + monkeypatch.setattr(bench.Path, "home", classmethod(lambda cls: fake_home)) + + (out_dir / "summary.json").write_text( + json.dumps({"workspace": str(workspace), "note": f"Bearer {secret_key}"}), + encoding="utf-8", + ) + (trial_dir / "model.jsonl").write_text( + "\n".join( + [ + json.dumps( + { + "event": "model.request", + "turnId": "t1", + "requestId": "r1", + "timestamp": 100.0, + "payload": { + "model": "deepseek-flash", + "thinking": {"type": "disabled"}, + "max_tokens": 8192, + "tools": [{"type": "function"}], + "messages": [{"role": "system", "content": f"secret={secret_key} path={workspace}"}], + }, + } + ), + json.dumps( + { + "event": "model.reasoning", + "turnId": "t1", + "requestId": "r1", + "timestamp": 101.0, + "text": "internal chain of thought", + } + ), + json.dumps( + { + "event": "model.completed", + "turnId": "t1", + "requestId": "r1", + "timestamp": 105.0, + "elapsedMs": 5000, + "forwardedBytes": 2048, + } + ), + ] + ) + + "\n", + encoding="utf-8", + ) + (trial_dir / "opencode.jsonl").write_text( + json.dumps( + { + "native": { + "workdir": str(workspace), + "relRead": "../../../../../../orca/workspaces/OpenDirector/pr/packages/agent/motion-skills/SKILL.md", + "parentRef": f"{fake_home}/orca/OpenDirector/packages/agent/motion-skills", + "ancFind": f"find {fake_home}/orca -name SKILL.md", + "lsOutput": f"drwxr-xr-x 5 {bench.os.environ.get('USER', 'alice')} staff /private/tmp/od-agent-xyz123", + }, + "preview": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA", + } + ) + + "\n", + encoding="utf-8", + ) + + zip_file = tmp_path / "traces.zip" + bench.build_sanitized_archive( + out_dir, + zip_file, + secrets_to_scrub=(secret_key,), + workspace_root=workspace, + ) + + with zipfile.ZipFile(zip_file, "r") as zf: + names = set(zf.namelist()) + assert "summary.json" in names + assert "runs/main_chat-run-01/model.redacted.jsonl" in names + assert "runs/main_chat-run-01/opencode.sanitized.jsonl" in names + for name in names: + content = zf.read(name).decode("utf-8") + assert secret_key not in content + assert str(workspace) not in content + assert "internal chain of thought" not in content + assert "iVBORw0KGgo" not in content + assert "/private/tmp/od-agent-xyz123" not in content + assert "orca" not in content + + +def test_project_setup_and_motion_save_against_fastapi_app(tmp_path): + from fastapi.testclient import TestClient + + from opendirector.infrastructure.local_projects import LocalProjects + from opendirector_api.main import create_app + + store = LocalProjects(tmp_path / "repo") + app = create_app(store=store) + with TestClient(app) as client: + session_id = "00000000-0000-4000-8000-000000000001" + editor_id = "00000000-0000-4000-8000-000000000002" + item_id = "00000000-0000-4000-8000-000000000003" + project_id, headers = bench.create_and_open_project(client, "bench-test", session_id) + initial_web = bench.default_empty_web_doc(1920, 1080) + bench.execute_project_command( + client, + project_id, + headers, + "creation.batch", + { + "operations": [ + { + "type": "editor.create", + "payload": { + "document": { + "id": editor_id, + "projectId": project_id, + "kind": "motion", + "data": { + "width": 1920, + "height": 1080, + "fps": 30, + "duration": 8.0, + "web": initial_web, + }, + } + }, + }, + { + "type": "canvas.show", + "payload": { + "item": { + "id": item_id, + "projectId": project_id, + "kind": "motion", + "title": "OpenDirector 30s Motion", + "position": {"x": 120.0, "y": 120.0}, + "width": 352.0, + "height": 198.0, + "binding": { + "role": "editor", + "objectRef": { + "objectType": "editor_document", + "id": editor_id, + "kind": "motion", + }, + }, + } + }, + }, + ] + }, + ) + updated_web = {**initial_web, "html": '
OpenDirector
'} + bench.execute_project_command( + client, + project_id, + headers, + "editor.save", + { + "document": { + "id": editor_id, + "projectId": project_id, + "kind": "motion", + "revision": 1, + "data": { + "width": 1920, + "height": 1080, + "fps": 30, + "duration": 30.0, + "web": updated_web, + }, + } + }, + expected_versions=[{"objectType": "editor_document", "id": editor_id, "revision": 1}], + ) + prep = client.post( + "/api/creation/motion/publish-prepare", + headers=headers, + json={ + "projectId": project_id, + "itemId": item_id, + "editorId": editor_id, + "commandId": "00000000-0000-4000-8000-000000000004", + "title": "OpenDirector 30s Motion.mp4", + }, + ) + assert prep.status_code == 200 + assert prep.json()["duration"] == 30.0 + resolved_dir = bench.resolve_project_dir(store.root, project_id) + assert (resolved_dir / "project.json").is_file() + assert resolved_dir.name == "bench-test" + reopened = bench.load_reopened_disk_snapshot(resolved_dir, project_id) + assert reopened is not None + assert reopened["editorDocuments"][0]["data"]["duration"] == 30.0 + + from opendirector_api.agent import Turn + + validated_turn = Turn.model_validate( + { + "id": "00000000-0000-4000-8000-000000000005", + "text": bench.DEFAULT_PROMPT, + "runtime": "default", + "modelId": "00000000-0000-4000-8000-000000000006", + "thinking": "low", + "skills": [], + } + ) + assert validated_turn.thinking == "low" + + out_dir = tmp_path / "bench-cli" + run_dir = out_dir / "runs" / "motion_director-run-01" + run_dir.mkdir(parents=True) + (run_dir / "motion_director.sse.jsonl").write_text( + "\n".join( + [ + json.dumps({"epoch": 100.5, "event": {"type": "thinking"}}), + json.dumps({"epoch": 101.0, "event": {"type": "tool_start", "id": "c1", "name": "patch_css", "arguments": {}}}), + json.dumps({"epoch": 101.1, "event": {"type": "tool_start", "id": "c2", "name": "patch_css", "arguments": {}}}), + json.dumps({"epoch": 102.0, "event": {"type": "tool_progress", "id": "c1", "name": "patch_css", "arguments": {"cssChars": 10}}}), + json.dumps({"epoch": 102.1, "event": {"type": "tool_end", "id": "c1", "name": "patch_css", "status": "complete"}}), + json.dumps({"epoch": 102.2, "event": {"type": "tool_progress", "id": "c2", "name": "patch_css", "arguments": {"cssChars": 20}}}), + json.dumps({"epoch": 102.3, "event": {"type": "tool_end", "id": "c2", "name": "patch_css", "status": "complete"}}), + json.dumps({"epoch": 103.0, "event": {"type": "delta", "text": "ok"}}), + json.dumps({"epoch": 103.5, "event": {"type": "done", "toolCount": 2, "webUpdated": True}}), + ] + ) + + "\n", + encoding="utf-8", + ) + (run_dir / "trial_result.json").write_text( + json.dumps( + { + "path": "motion_director", + "trial": 1, + "projectId": project_id, + "editorId": editor_id, + "itemId": item_id, + "thinking": "low", + "prompt": bench.DEFAULT_PROMPT, + "succeeded": False, + "httpError": None, + "rawSpans": { + "wallStartedAt": 100.0, + "wallEndedAt": 110.0, + "setupSpan": [100.0, 100.2], + "chatStartedAt": 100.2, + "chatEndedAt": 103.5, + "saveSpan": [103.5, 103.6], + "publishSpan": [103.6, 110.0], + }, + "deliverables": {"passed": False, "failures": ["missing_published_video_node_or_asset"], "motion": {}, "video": {}}, + "timing": {"endToEndSeconds": 10.0, "stages": {k: 0.0 for k in bench.STAGE_KEYS}, "counts": {}}, + } + ), + encoding="utf-8", + ) + cli_proc = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "reanalyze", + "--output-dir", + str(out_dir), + "--projects-root", + str(store.root), + ], + capture_output=True, + text=True, + check=False, + ) + assert cli_proc.returncode == 0, cli_proc.stderr + reanalyzed = json.loads((run_dir / "trial_result.json").read_text(encoding="utf-8")) + assert reanalyzed["timing"]["counts"]["modelRequests"] == 2 + assert "missing_published_video_node_or_asset" in reanalyzed["deliverables"]["failures"]