Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
125 changes: 125 additions & 0 deletions docs/development/motion-path-benchmark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# 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 on the PR branch)
- **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`
- **Shared completion & binding condition:** Reopening the project from disk via a fresh `CreationProjects` instance (without falling back to the HTTP snapshot) confirms an applied `canvas.publishMedia` commit matching the returned publish receipt (`commandId`, `sourceItemId`, `sourceEditorId`, frozen `executionDocumentId` + canonical `data` SHA-256 digest, `outputItemId`, and `assetId`), where the visible editable `motion` `editorDocument` (`30.0 ± 0.5s`, non-empty `web.html`) matches the frozen execution snapshot digest and the visible `video` `canvasItem` points to an on-disk MP4 matching both the recorded SHA-256 fingerprint and `ffprobe` (`1920x1080`, `30fps`, `h264`, `30.0 ± 0.5s`).

### Side-by-side path parameters & discovery version

| Dimension | `motion_director` | `main_chat` (`default` runtime) |
| --- | --- | --- |
| Harness & loop | Built-in `stream_motion_director_chat` (`MAX_AGENT_STEPS=12` + 1 synthesis wrap-up) | Bundled `opencode-ai` `1.19.5` (`NativeRuntime` + `ModelGateway` + `cli_transport`) |
| Wire reasoning (`thinking="low"`) | `thinking={"type": "enabled"}`, `reasoning_effort="low"` | `thinking={"type": "enabled"}`, `reasoning_effort="low"` |
| Default UI `thinking="auto"` mapping (reference) | `_motion_thinking` -> `"off"` (`thinking={"type": "disabled"}`) | `chat_payload` -> `thinking={"type": "enabled"}`, `reasoning_effort="high"` |
| Effective output `max_tokens` | `65536` at `low`/`medium` (`32768` at `off`/`auto`, `131072` at `high`), `reserve_reasoning=True` | `8192` (`CHAT_MAX_TOKENS`), `reserve_reasoning=False` |
| Tool & CLI discovery surface | In-process `MOTION_DIRECTOR_TOOLS` + `read_motion_skill` (`packages/agent/motion-skills/motion-director`) | `opendirector` CLI at `9f24de145389dab2186944d6fcc79acee5492dad` (`builtin_skills()` exposes `packages/agent/skills` only; `opendirector motion skills` hints at `.opendirector/motion-skills`; recorded prior to `#612`, `#662`, and `#664` CLI additions) |
| Frame inspection & MP4 render | Warm headless Chrome `inspect_frames`, then 1 post-chat `editor.save` + `publish-prepare` + `render-jobs` + `publish` | Subprocess `opendirector motion inspect` and `opendirector motion render` (`--publish-item-id` commits `canvas.publishMedia`) |
| Resume guard | Credential-free `experiment.json` SHA-256 fingerprint (`commitSha`, `prompt`, `thinking`, `runtime`, `model`, `canvas`) checked before server/provider dispatch | Same `experiment.json` SHA-256 fingerprint |

## 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 `<turn>.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 event handling, 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

Because `motion_director` and `main_chat` differ simultaneously across harness loop, effective output token budget (`65536` vs `8192`), skill/CLI discovery surface, and render cadence, the `2.53x` (`494.2s` vs `195.5s` mean) end-to-end difference reflects the combined multi-factor path delta rather than the isolated gain of any single mechanism. The traces locate where wall time accumulated and define candidate hypotheses to validate one factor at a time:

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) and exhausted all `8192` tokens inside `reasoning_content` (`output=0`) while planning the single-pass 30s `MotionDocument` write, hitting `finish_reason="length"` before emitting a tool call and exiting with zero deliverables (`main_chat` trial 3 also hit `finish_reason="length"` twice mid-output before recovering across later turns). 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: "<repo>/.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 <home> -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. **Unattributed wall-clock residual (`unattributed`: `56.6s` in trial 2, `11.8s` in trial 3, `4.5s` in failed trial 1 vs `0.000–0.001s` in `motion_director`):**
- `56.6s` and `11.8s` are unattributed wall-clock residuals outside `model`, `cliDiscoveryAndExec`, `inspectFrames`, and `renderAndPublish`; this bucket combines harness startup, inter-step scheduling, and client-side event handling without separate sub-timers (it does not isolate persistence time).
- In `main_chat` trial 2, the largest unattributed gap (`48.1s`) occurred between `ModelGateway` finishing request `f74f69d9bec41a58` (`7846` reasoning tokens across `7844` SSE chunks, `2.46 MB`) and the next child `bash` invocation. Whether OpenCode SSE/SQLite delta persistence or worktree snapshotting dominates that gap is an **unverified hypothesis** pending dedicated sub-stage timers or a controlled same-workload A/B test.

### 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.
4. Add sub-stage timers (or run a controlled same-workload A/B test) around OpenCode SSE ingestion, SQLite persistence, and worktree snapshot bookkeeping to quantify how much of `unattributed` comes from persistence versus harness startup and inter-step scheduling.

## 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)).
Loading
Loading