Nico-robot HF Staff commited on
Commit
2533701
·
verified ·
1 Parent(s): d34b061

Deploy d956c72 (part 2)

Browse files
docs/superpowers/specs/2026-09-03-microduck-arena-design.md CHANGED
@@ -224,7 +224,8 @@ quietly flatten that.
224
  2. Reset to the `STAND` keyframe. Apply the seed's perturbation (±0.01 rad per joint,
225
  ±2° yaw), drawn from a generator seeded by `(event_id, seed)` so it is reproducible.
226
  3. Settle for `settle_s` with the policy running and the clock stopped. Nobody is timed on
227
- standing up.
 
228
  4. Step the loop: build the 61-D observation, run the policy, apply 14 position targets,
229
  step physics 4 × 0.005 s. Command held at the manifest's pinned value throughout.
230
  5. Stop on one of:
@@ -238,7 +239,7 @@ quietly flatten that.
238
  been tipped for the full `fall_hold_s`, so a step where both fire is a robot that was
239
  collapsing and slid across the line — not a winner. A sprinter who falls *past* the tape is
240
  unaffected: it has no accumulated tipped time at the moment it crosses.
241
- 6. Return the outcome and the pose trace.
242
 
243
  The start line is `x = 0`, the duck's trunk x at the end of settling; the finish is
244
  `x = length_m`. The clock starts at the first stepped frame after settling.
@@ -272,6 +273,8 @@ which is the intended balance.
272
 
273
  Per run, the trace of the **median-finishing seed**: trunk position (3) + quaternion (4) +
274
  14 joint angles, float16 at 50 Hz. ~42 KB for a 20 s sprint (1000 frames × 21 × 2 bytes).
 
 
275
 
276
  Median, not best — a lane shows typical behaviour, and every entry's replay is selected the
277
  same way.
@@ -326,8 +329,9 @@ locking is needed.
326
 
327
  ```
328
  runs/<event_id>/<run_id>.json entry, per-seed times, score, provenance
329
- traces/<run_id>.npz median-seed replay, float16 (no event_id: run_id is
330
- globally unique, and the route is /api/runs/{run_id}/trace)
 
331
  models/<sha256>.onnx uploads only; content-addressed, so a re-submitted
332
  identical file costs nothing
333
  index/<event_id>.parquet nightly compaction, keeps boot fast
@@ -361,6 +365,7 @@ Physics only ever runs server-side.
361
  | `GET /api/events/{id}/leaderboard` | Ranked entries, one row per entrant |
362
  | `GET /api/runs/{run_id}` | One run: per-seed detail, provenance |
363
  | `GET /api/runs/{run_id}/trace` | Replay bytes |
 
364
  | `POST /api/events/{id}/submit` | Validate, run, return result |
365
  | `GET /api/me` | Signed-in user, or anonymous |
366
 
 
224
  2. Reset to the `STAND` keyframe. Apply the seed's perturbation (±0.01 rad per joint,
225
  ±2° yaw), drawn from a generator seeded by `(event_id, seed)` so it is reproducible.
226
  3. Settle for `settle_s` with the policy running and the clock stopped. Nobody is timed on
227
+ standing up. Its frames — the reset pose, then one per settle step — are kept beside the
228
+ trace, so a replay can start where the simulation did (the social clip does).
229
  4. Step the loop: build the 61-D observation, run the policy, apply 14 position targets,
230
  step physics 4 × 0.005 s. Command held at the manifest's pinned value throughout.
231
  5. Stop on one of:
 
239
  been tipped for the full `fall_hold_s`, so a step where both fire is a robot that was
240
  collapsing and slid across the line — not a winner. A sprinter who falls *past* the tape is
241
  unaffected: it has no accumulated tipped time at the moment it crosses.
242
+ 6. Return the outcome, the pose trace and the settle's frames.
243
 
244
  The start line is `x = 0`, the duck's trunk x at the end of settling; the finish is
245
  `x = length_m`. The clock starts at the first stepped frame after settling.
 
273
 
274
  Per run, the trace of the **median-finishing seed**: trunk position (3) + quaternion (4) +
275
  14 joint angles, float16 at 50 Hz. ~42 KB for a 20 s sprint (1000 frames × 21 × 2 bytes).
276
+ Beside it in the same file, that seed's settle in the same format (26 frames for 0.5 s);
277
+ traces stored before 2026-09-17 have none.
278
 
279
  Median, not best — a lane shows typical behaviour, and every entry's replay is selected the
280
  same way.
 
329
 
330
  ```
331
  runs/<event_id>/<run_id>.json entry, per-seed times, score, provenance
332
+ traces/<run_id>.npz median-seed replay and its settle, float16 (no event_id:
333
+ run_id is globally unique, and the routes are
334
+ /api/runs/{run_id}/trace and /settle)
335
  models/<sha256>.onnx uploads only; content-addressed, so a re-submitted
336
  identical file costs nothing
337
  index/<event_id>.parquet nightly compaction, keeps boot fast
 
365
  | `GET /api/events/{id}/leaderboard` | Ranked entries, one row per entrant |
366
  | `GET /api/runs/{run_id}` | One run: per-seed detail, provenance |
367
  | `GET /api/runs/{run_id}/trace` | Replay bytes |
368
+ | `GET /api/runs/{run_id}/settle` | The untimed settle before the replay, same format; empty for older runs |
369
  | `POST /api/events/{id}/submit` | Validate, run, return result |
370
  | `GET /api/me` | Signed-in user, or anonymous |
371
 
docs/superpowers/specs/2026-09-16-social-clips-and-sharing-design.md ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Social clips and sharing — design
2
+
3
+ Date: 2026-09-16. Status: implemented on branch social-clips, awaiting the owner's browser check and the first Space render.
4
+
5
+ ## Goal
6
+
7
+ Every **published** run gets two short videos made for social networks — a
8
+ landscape 1920×1080 and a vertical 1080×1920 — rendered on the server in the
9
+ background the moment the publish completes. Each clip is the arena's own
10
+ stage: the author's duck racing the three ducks ranked just under it, every
11
+ duck wearing its `@name`, a stadium crowd that follows the race and reacts to
12
+ the verdict, a title over the waiting ducks while the camera travels to the
13
+ start, an air horn for the off, a crowd that builds to the line, the `VICTORY` or
14
+ `DNF` stamp slamming down on the author's duck with the time, the place and the points.
15
+
16
+ On the publication page (`#/r/<run_id>`), under the points, a row of stickers
17
+ shares the result: X and LinkedIn open with the post pre-filled; Instagram and
18
+ TikTok copy the post to the clipboard and download the vertical clip, or hand
19
+ both to the phone's share sheet; two more stickers download the clips. A server
20
+ route `/r/<run_id>` carries Open Graph tags so a pasted link unfurls with the
21
+ poster and the video.
22
+
23
+ The clips are made to be reused later by a live programme (Duck Jam's HLS
24
+ producer, out of scope here): they keep its container contract.
25
+
26
+ ## What Duck Jam has, and what is new
27
+
28
+ Duck Jam renders a clip per scored run in a Hugging Face Job: headless Chromium
29
+ photographs a three.js page frame by frame over the DevTools protocol, ffmpeg
30
+ encodes H.264 and mixes a crowd synthesised in the page with the sound kit's
31
+ cues (`dome/media/{record,clip,stage,audio}.mjs`, `design/sound/stadium*.mjs`).
32
+ Its results page has the share row (`dome/web/features/results/sharing.mjs`):
33
+ X and LinkedIn intents, Instagram and TikTok as copy-and-download buttons,
34
+ download stickers with `?download=true`, inline SVG logos, and the post text
35
+ composed from `design/strings.json`. Its gate serves `/r/<id>` with OG tags.
36
+
37
+ What is new here: the clip is rendered **inside the Space itself** by a
38
+ background worker rather than a Job; the recorder is **Python**, not Node; the
39
+ soundtrack is rendered **in one block** in the page rather than mixed by
40
+ ffmpeg; the stage is the **arena's viewer** with four named lanes rather than
41
+ Duck Jam's one-duck-and-ghost stage; the clip's framing, duration and sounds
42
+ are **configured per event** in its manifest; the post text is composed
43
+ **client-side** from the run detail rather than stored as `post.json`.
44
+
45
+ ## Decisions taken
46
+
47
+ | Decision | Why, and what it rules out |
48
+ | --- | --- |
49
+ | **Render in the Space, in a background worker** | One image, one deploy, no Jobs token or billing, and `arena serve` renders locally the same way. Rules out HF Jobs (a second image, a launcher token, a drain for lost jobs) and browser-side capture (H.264/AAC missing on Linux and Firefox, the author must stay on the page, and an uploaded file cannot be trusted by the live programme). Cost: Chromium and ffmpeg in the image (~600 MB), minutes of CPU per publish on cpu-basic, under `nice`. |
50
+ | **The recorder is Python** | The Chrome driver is 60 lines of DevTools JSON over a websocket and ffmpeg is a subprocess. One server language, no Node binary in the runtime image. Adds `websockets` to the dependencies. |
51
+ | **Both layouts render concurrently when cores allow** | One Chrome per run, one tab per layout, up to `ARENA_CLIP_PARALLEL` tabs at once (default `cpu_count // 2`): sequential on a 2-vCPU Space where SwiftShader already uses every core, both at once on a laptop. The soundtrack is rendered once per run and shared. |
52
+ | **The capture path is chosen by measurement, not guessed** | On Duck Jam a frame cost 0.5 s of which 8 ms was JavaScript; the split between SwiftShader rasterisation and PNG encoding is unknown. The plan's first task measures three paths on the arena's scene and applies a stated rule (see *Capture*). |
53
+ | **The soundtrack is one offline render** | Everything is known before the first frame — the trace, the tape end, the verdict — so the page computes the whole score and renders crowd and cues in a single `OfflineAudioContext` pass with a limiter. Rules out segment-by-segment crowd renders smoothed afterwards, and ffmpeg's `adelay`/`amix` graph: ffmpeg receives one PCM track and muxes it. |
54
+ | **The stage is the arena's viewer in a manual mode** | `viewer.js` gains `manual: true` (no animation loop, no controls) and `frame(seconds)`. The clip and the publication page share one drawing, so they cannot drift. Rules out a second stage module. |
55
+ | **Names are 3D nameplates over each duck** | Ported from Duck Jam's `plate.mjs`: a canvas-textured sprite in the lane's colour, hung above the trunk. Four ducks on one stage need names on the ducks, not in a corner. The publication page does not enable them yet. |
56
+ | **Per-event `[clip]` configuration** | Tape ceiling, camera and sounds live in the event manifest with defaults, so a jump or a hold can frame and score its clip differently without a code change. |
57
+ | **Clip state is three write-once files** | `pending.json`, then either `clip.json` with the media or `failed.json`. The store stays append-only: no file is rewritten. State is read by presence. |
58
+ | **Media files stay out of the Hub snapshot** | `HubStore` ignores `*.mp4` and `*.png` when it downloads the run log and fetches a clip file on demand, cached. Otherwise every boot would download the whole video library. |
59
+ | **Downloads stream through the Space** | The dataset is private, so there is no Hub URL to redirect to. Same-origin also means `<a download>` works without Duck Jam's `?download=true` trick; `?download=1` is still honoured so a link opened in a new tab saves rather than plays. |
60
+ | **The post is composed client-side** | The page already has the run detail; composing there means the place and the points are never stale. Rules out a stored `post.json` (Duck Jam's way, useful to a bot that does not exist here). |
61
+ | **`/r/<run_id>` unfurls** | Without OG tags a pasted link shows nothing. The route is server-side HTML with the tags and a redirect to `#/r/<id>`. It only helps once the Space is public — a deployment setting, not code. |
62
+ | **Historical runs are not rendered automatically** | Only runs marked `pending.json` at publish are drained at boot. `arena clip <run_id>` renders one by hand. Rules out a boot that renders 35 runs for hours. |
63
+ | **Tests stay at the minimum** | Store state, worker with a fake recorder, routes, post text, frame plan. The theatre is checked in a browser and the render in a player. |
64
+
65
+ ## The flow
66
+
67
+ 1. `POST /api/events/{id}/submit` evaluates and appends the run as today, then,
68
+ if the renderer is available, writes `clips/<run_id>/pending.json` and
69
+ enqueues the run.
70
+ 2. The browser lands on `#/r/<run_id>` and the reveal plays. The share row is
71
+ there from the first paint, veiled, and is unveiled with the rest at
72
+ `settle`. The page asks `GET /api/runs/{id}/clip` and, while `pending`,
73
+ asks again every 5 s.
74
+ 3. The worker takes the run, launches Chrome, opens `clip.html` once per
75
+ layout, renders the soundtrack once, captures the frames, encodes with
76
+ ffmpeg, and writes `clip.json`, `landscape.mp4`, `vertical.mp4` and
77
+ `poster.png` in one store write. On any failure it writes `failed.json`
78
+ with the reason.
79
+ 4. The clip stickers turn from `Clip · rendering…` into downloads. Instagram
80
+ and TikTok now download the vertical clip along with copying the post.
81
+
82
+ ## The rendering pipeline
83
+
84
+ ### The worker — `arena/clips.py`
85
+
86
+ ```python
87
+ class ClipRenderer:
88
+ available: bool # Chrome found, ffmpeg on PATH, clip.html in the bundle
89
+ def enqueue(self, run_id: str) -> None
90
+ def drain(self) -> None # enqueue store.pending_clips()
91
+ ```
92
+
93
+ One daemon thread and a `queue.Queue`, started by `create_app` and drained at
94
+ startup the way `recover` is. A job renders every layout of one run (see
95
+ *Parallelism*), then `store.put_clip(run_id, files)`; an exception or a
96
+ 15-minute timeout ends in `store.fail_clip(run_id, reason)` and a printed line.
97
+ Runs are processed one at a time; a redeploy that kills a job leaves its
98
+ `pending.json`, and the next boot drains it.
99
+
100
+ The renderer is constructed with the origin the page is served from
101
+ (`http://127.0.0.1:<port>`, from `arena serve`'s own arguments or
102
+ `ARENA_ORIGIN`), the frontend directory (for `clip.html` and `sound/`), and
103
+ `ARENA_CLIP_PARALLEL`.
104
+
105
+ Every subprocess — Chrome, ffmpeg — runs under `nice -n 10`, so a render never
106
+ starves an evaluation.
107
+
108
+ ### The recorder — `arena/recorder.py`
109
+
110
+ One layout of one run, in the order Duck Jam's `record.mjs` does it:
111
+
112
+ 1. Chrome is launched once per run with `--headless=new --hide-scrollbars
113
+ --no-first-run --use-angle=swiftshader --enable-unsafe-swiftshader
114
+ --no-sandbox --user-data-dir=<tmp> --remote-debugging-port=0`; the DevTools
115
+ endpoint is read from its stderr; the client is `websockets.sync`. The
116
+ binary is `$CHROME`, else the first of Chrome and Chromium at their usual
117
+ macOS and Linux paths.
118
+ 2. Per layout, a target is created, its viewport set to exactly the layout's
119
+ size with `deviceScaleFactor: 1`, and it navigates to
120
+ `<origin>/clip.html?run=<id>&layout=<landscape|vertical>&frame=0`.
121
+ 3. The recorder waits for `window.clip.ready` (60 s cap) and
122
+ `document.fonts.ready`, then reads `window.clip.plan` and
123
+ `window.clip.error`. An error is a failed render, never a blank video.
124
+ 4. The soundtrack is rendered in the page (`window.clip.soundtrack()`), once
125
+ per run, and transferred as base64 in chunks of at most 4 MB.
126
+ 5. Frames: for `i` in `0..plan.frames`, `window.clip.draw(i)` then one capture
127
+ (see *Capture*), piped into ffmpeg. The poster frame is also kept as PNG.
128
+ 6. ffmpeg: `-c:v libx264 -preset medium -crf 23 -pix_fmt yuv420p`, the PCM as
129
+ `-f f32le -ar 48000 -ac 2`, `-c:a aac -b:a 192k`, `-shortest`,
130
+ `-metadata crowdMixed=true -movflags +faststart+use_metadata_tags`.
131
+ 7. Chrome is closed with `Browser.close` raced against 2 s, then killed;
132
+ Chrome outlives a SIGTERM.
133
+ 8. A timing record is returned with the bytes: frames, seconds, draw and
134
+ capture milliseconds per frame, total wall time, and the machine's cores
135
+ and load. It goes into `clip.json` so the Space's real cost is on record.
136
+
137
+ ### Capture
138
+
139
+ Three paths are measured on the arena's scene — four ducks, 1080p, SwiftShader,
140
+ antialias on and off — and the fastest that works in the Debian `chromium`
141
+ build is the one implemented. Only one path ships.
142
+
143
+ | Path | What changes | What it imposes |
144
+ | --- | --- | --- |
145
+ | `Page.captureScreenshot` PNG | Duck Jam as is | nothing |
146
+ | `Page.captureScreenshot` JPEG q92 | image encoding two to three times cheaper | nothing: the overlay stays HTML/CSS |
147
+ | WebCodecs in the page | no round trip per frame: `new VideoFrame(canvas)` → `VideoEncoder` VP9 → an IVF container written in the page → one transfer; ffmpeg transcodes to H.264 | the overlay must be drawn into the canvas with Canvas2D, reading fonts and colours from computed styles as the nameplate does |
148
+
149
+ The rule: if rasterisation dominates the frame cost, JPEG screenshots take the
150
+ gain and the overlay stays in the design system. If capture dominates,
151
+ WebCodecs with a Canvas2D overlay. The prediction is that rasterisation
152
+ dominates. The poster is a PNG in both cases.
153
+
154
+ ### Parallelism
155
+
156
+ `ARENA_CLIP_PARALLEL` tabs render at once inside the one Chrome, each with its
157
+ own ffmpeg. With the default `max(1, cpu_count // 2)` the Space renders the
158
+ two layouts one after the other and a 10-core laptop renders both together.
159
+ The soundtrack is rendered by the first tab and reused.
160
+
161
+ ### Availability
162
+
163
+ `ClipRenderer.available` is true when a Chrome binary is found, `ffmpeg` is on
164
+ the PATH and `<frontend_dir>/clip.html` exists. When false, a publish writes no
165
+ `pending.json`, `GET …/clip` answers `none`, and the page shows the network
166
+ stickers with no downloads. Nothing is logged as an error: a developer machine
167
+ without Chromium is a supported configuration.
168
+
169
+ ### The CLI
170
+
171
+ `arena clip <run_id> --store DIR` starts the app on an ephemeral port in a
172
+ thread, renders the run, writes into the store, and exits. It is the test rig
173
+ and the way a historical run gets a clip.
174
+
175
+ ### The image
176
+
177
+ ```dockerfile
178
+ FROM python:3.13-slim
179
+ RUN apt-get update \
180
+ && apt-get install -y --no-install-recommends chromium ffmpeg fonts-liberation \
181
+ && rm -rf /var/lib/apt/lists/*
182
+ ENV CHROME=/usr/bin/chromium
183
+ RUN chromium --version && ffmpeg -version
184
+ RUN useradd -m -u 1000 user
185
+ USER user
186
+ ```
187
+
188
+ The comment that refuses `libgl1` is rewritten: the renderer needs Mesa now.
189
+ `fonts-liberation` is the fallback family for glyphs Anton and DM Sans lack.
190
+ The build tripwire fails an image whose apt layer is broken before it can boot
191
+ and render nothing.
192
+
193
+ ## The clip page — `app/clip.html`, `app/src/clip/`
194
+
195
+ A second Vite entry (`build.rollupOptions.input: { main, clip }`), served by
196
+ the static mount at `/clip.html`. It loads `/design/tokens.css`,
197
+ `/design/effects.css`, `/design/components.css` and a static `/clip.css` for
198
+ the frame's placement, exactly as Duck Jam's `clip.html` places its objects
199
+ without setting a colour or a face of its own.
200
+
201
+ ### Reading the run
202
+
203
+ `?run=<id>` → `getRun`, then `getTrace` for the four lanes `lanesFor` picks —
204
+ the run's row and the three under it, as on the publication page. `run.event`
205
+ carries the `[clip]` configuration (see below).
206
+
207
+ ### The viewer in manual mode
208
+
209
+ `createViewer(canvas, { rig, manual: true, camera })`:
210
+
211
+ - `manual` skips `requestAnimationFrame`, `OrbitControls` and the brightness
212
+ preference. `tick` is split into `advance(now)` and `draw()`, and
213
+ `frame(seconds)` is `player.seek(seconds)` then `draw()`.
214
+ - `camera` is a spec (below). Without one the viewer behaves exactly as today:
215
+ the chase camera at `(lead − 0.35, 0.34, sideOffset)` looking at
216
+ `(lead, 0.12, 0)`.
217
+ - Each `setLanes` entry may carry `name`; a nameplate sprite is hung above
218
+ that lane's trunk and moved with it in `draw`. `app/src/plate.js` is the
219
+ port of Duck Jam's `nameplate` only: the face read from `.mono-label`'s
220
+ computed style, three texture pixels per CSS pixel, `SRGBColorSpace`,
221
+ `depthWrite: false`, the lane's colour on deep ink. Height and lift are
222
+ constants tuned in the browser.
223
+ - The vertical layout backs the camera off by a constant factor; the same
224
+ spec serves both layouts.
225
+
226
+ ### The plan
227
+
228
+ 25 fps. The author's trace is 50 Hz, so one clip frame is two trace frames.
229
+
230
+ ```
231
+ settle = the lanes' settle frames # 26 for 0.5 s; 0 if none of them was stored with one
232
+ steps = settle + min(frameCount(author), tape_max_s / CTRL_DT)
233
+ intro = 75 # 3 s
234
+ travel = 60 # 2.4 s of it: the camera's travel to the chase
235
+ tape = ceil(steps / 2)
236
+ outro = 63 # 2.5 s
237
+ frames = intro + tape + outro
238
+ poster = intro + floor(tape × 0.6)
239
+ ```
240
+
241
+ Each lane plays `leadIn(settle, trace)`: its settle, then its trace, so the
242
+ tape starts where the simulation did — the ducks standing in the `STAND` pose
243
+ under the title, the settle from the horn — with a missing settle made up by
244
+ holding the trace's first frame, so older runs keep in step. The clock reads
245
+ `00:00.00` until the settle is over.
246
+
247
+ `draw(i)`: intro frames pose step 0 under the title, the camera
248
+ `travelPose(chase, min(1, i / travel))` of the way round from ahead of the line
249
+ to the chase, which it holds for the last 0.6 s; tape frames pose
250
+ step `(i − intro) × 2`; outro frames hold the last step under the stamp and
251
+ the figures. Rivals that finish first wait at the line; rivals still running
252
+ when the author's trace ends are cut with it, as the reveal does. A run longer
253
+ than `tape_max_s` — a timeout — is cut at the ceiling and stamped anyway: the
254
+ verdict is the record's, not the tape's.
255
+
256
+ `window.clip = { plan, score, layout, draw, soundtrack, chunk, ready, error }`.
257
+ The recorder reads and calls nothing else.
258
+
259
+ ### The frame
260
+
261
+ | Act | Picture | Sound |
262
+ | --- | --- | --- |
263
+ | Title | The waiting ducks on the stage, the author's in the foreground; over the sky, eyebrow `Microduck Arena`, the event title, `@user · policy` on a shade of ink. No OSD yet, and the vertical top band keeps its words for the horn | the crowd waiting; the air horn at the intro's end, as the title leaves |
264
+ | Tape | The stage full frame, four named ducks. OSD: `● REC · @user · policy` top-left, the clock `00:00.00` bottom-right, the event title bottom-left (landscape). Vertical: a top band with eyebrow, title and `@user · policy`, and the figures band at the bottom throughout | the crowd |
265
+ | Outro | The last frame frozen. The stamp `VICTORY` (lime) or `DNF` (magenta), `fx-tilt-2-5`, centred on the author's duck where the viewer's `spot` says it stands. The figures band: the time (`formatScore`), the place (`#rank`, or `—` off the board or withdrawn), the points (`+N`, or `—` at zero); under it the weights' address without its scheme when `policy_url` is set | `stamp.wav` at the tape end; `microduck-victory-echo.mp3` or `microduck-fall.wav` 160 ms later; the crowd turns to the verdict |
266
+
267
+ Landscape shows the figures band only in the outro, over the frozen frame.
268
+
269
+ ### The soundtrack in one block
270
+
271
+ Before any frame, the page builds the **score**:
272
+
273
+ - `crowdDirection = { start: intro / fps, end: (intro + tape) / fps, verdict,
274
+ progress }` where `verdict` is `pass` when `seeds_finished > 0`, else
275
+ `fail`, and `progress` samples the author's trunk `x / length_m`, clamped to
276
+ `[0, 1]`, every 0.5 s of tape. `stadiumDirection` turns it into a pure
277
+ function of time: play rises with the tape, encouragement follows progress,
278
+ the start horn raises a surge that never settles back — it builds with the
279
+ author's progress, joy creeping in with its square on a pass — and joy or
280
+ sadness is full 0.2 s before the line, as a real crowd sees it coming, and
281
+ holds over the outro.
282
+ - `cues`: `air-horn.mp3` at the tape start, `stamp.wav` at the tape end, the
283
+ verdict voice at tape end + 0.16 s — each `{ at, file, gain }`, only from
284
+ the sources the event lists. Every cue goes straight to the mix: the horn
285
+ and the victory carry the stadium echo Nicolas put in their files, and the
286
+ fall has none.
287
+
288
+ `soundtrack()` renders **one** `OfflineAudioContext` of `frames / fps`
289
+ seconds at 48 kHz stereo: `renderStadium`'s voices driven by the direction,
290
+ every cue decoded with `decodeAudioData` and scheduled as a `BufferSource` at
291
+ its instant, a `DynamicsCompressor` set as a limiter at the output so no
292
+ sample reaches ±1 — the live programme refuses a clip that clips. The
293
+ interleaved float32 buffer is the whole soundtrack; it is rendered once per
294
+ run and given to both layouts' ffmpeg as `-f f32le`. Gains are measured on a
295
+ real render: the stadium at half its own volume so its protection compressor
296
+ leaves the crowd room to build, made up by ×3 after it; horn 2, stamp 0.6,
297
+ victory 7, fall 0.45 (it plays over a crowd gone quiet). Chrome's limiter adds
298
+ make-up gain, so the sprint's joy and victory together peak at 0.95: pushing
299
+ either higher clips.
300
+
301
+ `app/src/clip/stadium.js` and `app/src/clip/direction.js` are Duck Jam's
302
+ `design/sound/stadium.mjs` and `stadium-direction.mjs`, ported with their
303
+ origin in a header comment; the direction's start surge, its build to the line
304
+ and its early verdict are this repository's.
305
+
306
+ ### Sound sources
307
+
308
+ A source is a function `(run, traces, plan) → cues[]`, registered by name.
309
+ Three exist: `crowd` (which contributes the direction rather than cues),
310
+ `horn`, `verdict`. An event's `sounds` list says which contribute; adding a
311
+ source — a `duck` foley track computed from the trace, a simulator's own
312
+ audio — is one function and one name, and is out of scope until such a sound
313
+ exists.
314
+
315
+ ### The horn
316
+
317
+ `air-horn.mp3`, made for the arena by Nicolas Rabault with its echo in the
318
+ file, the same for every event.
319
+
320
+ ### The live contract
321
+
322
+ Kept verbatim for the programme that will consume these clips: 25 fps, so the
323
+ duration is a whole multiple of 40 ms; `crowdMixed=true` as a container tag
324
+ and in `clip.json`; `crowdDirection { start, end, verdict }` in `clip.json`;
325
+ 1920×1080 and 1080×1920.
326
+
327
+ ## Per-event configuration — `[clip]` in the manifest
328
+
329
+ Optional. `manifest.py` validates it into a frozen `ClipConfig` with these
330
+ defaults, and `event_summary` exposes it as `clip`:
331
+
332
+ ```toml
333
+ [clip]
334
+ tape_max_s = 12.0 # the tape's ceiling in the clip
335
+ sounds = ["crowd", "horn", "verdict"]
336
+
337
+ [clip.camera]
338
+ kind = "chase" # the default: today's chase camera
339
+ back = 0.35 # behind the leader, along the lane
340
+ height = 0.34
341
+ side = "auto" # or a number; auto = cameraSideOffset
342
+ target_height = 0.12
343
+ fov = 42
344
+ ```
345
+
346
+ A fixed camera is `kind = "fixed"` with absolute `position = [x, y, z]`,
347
+ `target = [x, y, z]` and `fov`, for events where the picture is a jump or a
348
+ stand rather than a run. Unknown keys, unknown kinds and unknown source names
349
+ are `ManifestError`s, loudly, at load. Every existing event carries no
350
+ `[clip]` section and gets the defaults.
351
+
352
+ ## Store and API
353
+
354
+ ### Files
355
+
356
+ Under `clips/<run_id>/`, three write-once files and the media:
357
+
358
+ | File | Written by | Meaning |
359
+ | --- | --- | --- |
360
+ | `pending.json` `{run_id, user, event_id, queued_at}` | the submit route | a clip is owed |
361
+ | `clip.json` + `landscape.mp4` + `vertical.mp4` + `poster.png` | the worker, in one write | ready |
362
+ | `failed.json` `{run_id, failed_at, reason}` | the worker | given up |
363
+
364
+ State by presence: `ready` if `clip.json`, else `failed` if `failed.json`,
365
+ else `pending` if `pending.json`, else `none`.
366
+
367
+ ```json
368
+ {
369
+ "run_id": "01M2…", "version": 1, "rendered_at": "2026-09-16T18:00:00Z",
370
+ "poster": "poster.png",
371
+ "layouts": {
372
+ "landscape": { "file": "landscape.mp4", "width": 1920, "height": 1080, "fps": 25,
373
+ "frames": 213, "seconds": 8.52, "crowdMixed": true,
374
+ "crowdDirection": { "start": 1.0, "end": 6.0, "verdict": "pass" },
375
+ "timing": { "draw_ms_per_frame": 8, "capture_ms_per_frame": 190,
376
+ "total_wall_ms": 48000, "cores": 2, "load": [1.8, 1.2, 0.9] } },
377
+ "vertical": { "…": "…" }
378
+ }
379
+ }
380
+ ```
381
+
382
+ `version` is `CLIP_VERSION`, a constant. Bumping it does not re-render: an
383
+ older clip is still served.
384
+
385
+ ### The `Store` protocol grows
386
+
387
+ ```python
388
+ def mark_clip_pending(self, run_id: str, user: str, event_id: str, queued_at: str) -> None
389
+ def put_clip(self, run_id: str, files: dict[str, bytes]) -> None # clip.json and media, one write
390
+ def fail_clip(self, run_id: str, failed_at: str, reason: str) -> None
391
+ def clip_state(self, run_id: str) -> tuple[str, dict | None] # ("ready", manifest) or (state, None)
392
+ def clip_file(self, run_id: str, name: str) -> Path
393
+ def pending_clips(self) -> list[str] # pending, with neither clip nor failed
394
+ ```
395
+
396
+ `LocalStore` writes under its root. `HubStore` writes each as one
397
+ `create_commit`; its `snapshot()` passes `ignore_patterns=["*.mp4", "*.png"]`,
398
+ and `clip_file` is `hf_hub_download` of the one path, cached by the Hub cache.
399
+ `put_clip` and `fail_clip` drop the snapshot so the page sees the state at
400
+ once; `mark_clip_pending` is the extra commit a publish now pays.
401
+
402
+ ### Routes
403
+
404
+ - `GET /api/runs/{run_id}/clip` — `Cache-Control: no-store`.
405
+ `{"state": "ready", "poster": "/api/runs/<id>/clip/poster.png",
406
+ "layouts": {"landscape": {"url": "/api/runs/<id>/clip/landscape.mp4",
407
+ "width": 1920, "height": 1080, "seconds": 8.52}, "vertical": {…}}}`, or
408
+ `{"state": "pending"}`, `{"state": "failed"}`, `{"state": "none"}`.
409
+ - `GET /api/runs/{run_id}/clip/{name}` — `name` is one of `landscape.mp4`,
410
+ `vertical.mp4`, `poster.png`; anything else, or a clip not ready, is 404.
411
+ A `FileResponse` with the right media type and
412
+ `Cache-Control: public, max-age=31536000, immutable` — the bytes behind a
413
+ ready clip never change. `?download=1` adds
414
+ `Content-Disposition: attachment; filename="microduck-arena-<user>-<policy>-<layout>.mp4"`,
415
+ the stem sanitised by the rule `policy_filename` already applies.
416
+ - `POST /api/events/{id}/submit` — after `store.append`, when the renderer is
417
+ available: `mark_clip_pending` then `enqueue`. The response is unchanged.
418
+ - `GET /r/{run_id}` — see *Unfurl*.
419
+
420
+ ## The publication page
421
+
422
+ ### The share row
423
+
424
+ Under `#points`, a third child of `.run-score`:
425
+
426
+ ```html
427
+ <nav class="run-share" id="share" aria-label="Share this run">
428
+ <a class="sticker sticker-mark fx-tilt-2-5" href="<x intent>" target="_blank" rel="noopener" aria-label="X">…</a>
429
+ <a class="sticker sticker-mark fx-tilt-1-5" href="<linkedin intent>" …>…</a>
430
+ <button class="sticker sticker-mark fx-tilt-3-0" type="button" data-upload="instagram" aria-label="Instagram">…</button>
431
+ <button class="sticker sticker-mark fx-tilt-1-0" type="button" data-upload="tiktok" aria-label="TikTok">…</button>
432
+ <a class="sticker sticker-cyan fx-tilt-2-5" href="/api/runs/<id>/clip/landscape.mp4?download=1" download>Clip · landscape</a>
433
+ <a class="sticker sticker-cyan fx-tilt-1-5" href="/api/runs/<id>/clip/vertical.mp4?download=1" download>Clip · vertical</a>
434
+ </nav>
435
+ <p class="mono-label run-share-said" hidden></p>
436
+ ```
437
+
438
+ The row wears `.fx-tilt-alternate` so signs alternate. Logos are Duck Jam's
439
+ inline SVG paths, 22×22, `fill: currentColor`; the network's name is the
440
+ `aria-label` and `title`, never drawn. `.run-score` becomes
441
+ `grid-template-rows: auto auto auto`. The row is present from the first paint
442
+ and `veiled` during a reveal; `settle` unveils it — a beat unveils, it never
443
+ inserts. `.run-share`, `.sticker-mark`, `.sticker-logo` and `.run-share-said`
444
+ are added to `race.css`'s run section.
445
+
446
+ Clip stickers by state: `pending` → `Clip · rendering…`, no `href`,
447
+ `aria-disabled`, polled every 5 s; `ready` → the two downloads; `failed` or
448
+ `none` → the two stickers are absent.
449
+
450
+ ### Behaviour — `app/src/share.js`
451
+
452
+ Ported from `sharing.mjs`, with the page's own words:
453
+
454
+ - **X, LinkedIn**: plain links to `https://x.com/intent/post?text=` and
455
+ `https://www.linkedin.com/feed/?shareActive=true&text=`, the text
456
+ URL-encoded. These are the only two addresses that pre-fill a post;
457
+ `linkedin.com/sharing/share-offsite` takes a URL and no text.
458
+ - **Instagram, TikTok**: on a coarse-pointer device with `navigator.share`,
459
+ `share({ text })` — `text` only; a `url` beside it makes some targets drop
460
+ the text. Otherwise the post is copied to the clipboard, the vertical clip's
461
+ download URL is opened when the clip is ready, and the line says
462
+ `Text copied. Use the clip download to attach your video and publish in your app.`
463
+ or, while pending, `Text copied. The clip is still rendering — come back for the download.`
464
+ A refused clipboard says `Could not copy. Select the text and copy it yourself.`
465
+ - The functions take their browser hooks (`share`, `handheld`, `open`,
466
+ `clipboard`) as parameters so the tests need no browser.
467
+
468
+ ### The post — `postText(run, { origin, network })`, pure
469
+
470
+ ```
471
+ I coded a robot duck to walk. On 2 m Sprint it finished 5/5 seeds in 2.314 s, #3 on the board (+135 pts).
472
+ Beat it: https://<origin>/r/<run_id>
473
+ Weights: huggingface.co/<user>/microduck-<policy>
474
+ #MicroduckArena @pollenrobotics @huggingface
475
+ ```
476
+
477
+ - A DNF reads `it finished 0/5 seeds on its feet — it ate the floor` when a
478
+ seed fell, `it ran out of time` otherwise.
479
+ - `#rank on the board` is omitted off the board or when withdrawn; `(+N pts)`
480
+ is omitted at zero; the `Weights:` line is omitted without `policy_url`.
481
+ - The mentions `@pollenrobotics @huggingface` appear on X only; the hashtag
482
+ on every network.
483
+ - The link is the unfurl route, so a pasted post shows the poster.
484
+ - Every variant fits X's 280 with the link counted as 23.
485
+
486
+ ## Unfurl — `GET /r/{run_id}`
487
+
488
+ A router without the `/api` prefix, included before the static mount. It finds
489
+ the run (404 otherwise) and answers HTML:
490
+
491
+ ```html
492
+ <!doctype html><html lang="en"><head><meta charset="utf-8">
493
+ <title>@alice · walker · 2 m Sprint · Microduck Arena</title>
494
+ <meta property="og:type" content="video.other">
495
+ <meta property="og:title" content="@alice · walker · 2 m Sprint">
496
+ <meta property="og:description" content="@alice's duck finished 5/5 seeds in 2.314 s on 2 m Sprint, #3 on the board.">
497
+ <meta property="og:url" content="https://<host>/r/<id>">
498
+ <meta property="og:image" content="https://<host>/api/runs/<id>/clip/poster.png">
499
+ <meta property="og:image:width" content="1920"><meta property="og:image:height" content="1080">
500
+ <meta property="og:video" content="https://<host>/api/runs/<id>/clip/landscape.mp4">
501
+ <meta property="og:video:type" content="video/mp4">
502
+ <meta property="og:video:width" content="1920"><meta property="og:video:height" content="1080">
503
+ <meta name="twitter:card" content="summary_large_image">
504
+ <meta http-equiv="refresh" content="0; url=/#/r/<id>">
505
+ </head><body><script>location.replace("/#/r/<id>")</script>
506
+ <a href="/#/r/<id>">Open this run</a></body></html>
507
+ ```
508
+
509
+ Image and video tags appear only when the clip is `ready`. Every value is
510
+ HTML-escaped. The public origin is `https://$SPACE_HOST` when set, else the
511
+ request's base URL; `ArenaConfig.public_origin` holds it. `Cache-Control:
512
+ public, max-age=60`, so a crawler's re-fetch after the clip lands is soon.
513
+
514
+ ## Vendored assets and licences
515
+
516
+ Into `app/public/sound/`, with `PROVENANCE.md` extended one row each:
517
+ `microduck-fall.wav` (Apache-2.0, pollen-robotics/microduck's synthesiser,
518
+ "modified audio" per Duck Jam's `LICENSES.md`), with `MICRODUCK-LICENSE.txt`
519
+ beside them. Duck Jam's `LICENSES.md` also lists `microduck-victory.wav` as
520
+ Apache-2.0, "modified recipe"; the arena's `PROVENANCE.md` currently calls it
521
+ CC0-1.0, and that row is corrected in the same change.
522
+
523
+ Into `app/src/`: `plate.js` (nameplate only), `clip/stadium.js`,
524
+ `clip/direction.js`, each with a header naming the Duck Jam file and commit it
525
+ came from.
526
+
527
+ ## Configuration
528
+
529
+ | Variable | Default | Meaning |
530
+ | --- | --- | --- |
531
+ | `CHROME` | first found of the usual paths | the browser binary |
532
+ | `ARENA_CLIP_PARALLEL` | `max(1, cpu_count // 2)` | layouts rendered at once |
533
+ | `ARENA_ORIGIN` | `http://127.0.0.1:<port>` | where the recorder's Chrome loads `clip.html` |
534
+ | `SPACE_HOST` | unset | the public host for OG URLs; set by Spaces |
535
+
536
+ `websockets>=13` joins the dependencies. `uv.lock` is updated for it.
537
+
538
+ ## Testing
539
+
540
+ Python, `tests/test_clips.py`:
541
+
542
+ - store: the three files, state by presence, `pending_clips` excludes runs
543
+ with a `clip.json` or `failed.json`, `put_clip` writes the media and the
544
+ manifest together;
545
+ - worker: with a fake `render` that returns bytes, a publish enqueues and the
546
+ files land; a raising fake writes `failed.json`; `drain` enqueues exactly
547
+ the pending runs;
548
+ - routes: `/clip` in each state, the media route's 404s, media type,
549
+ `Content-Disposition` with `?download=1` and the sanitised name;
550
+ - unfurl: tags present when ready and absent when not, escaping, the redirect,
551
+ 404 for an unknown run.
552
+
553
+ Python, `tests/test_manifest.py`: `[clip]` defaults, a fixed camera, an
554
+ unknown source refused.
555
+
556
+ JavaScript: `share.test.js` — `postText` variants and the 280 rule, the two
557
+ intent URLs, the Instagram click on a laptop copies and opens the vertical
558
+ clip; `clip/plan.test.js` — the frame plan and the ceiling.
559
+
560
+ The render is checked by eye: `arena clip` on the developer's Mac, both mp4s
561
+ opened in a player, the crowd heard turning at the verdict; then on the Space
562
+ after deploy, the timing in `clip.json` read back for the real per-frame
563
+ cost. The share row is checked in the browser, as the theatre is.
564
+
565
+ ## Out of scope
566
+
567
+ The live programme and anything that consumes the clips; a bot that posts;
568
+ nameplates on the publication page; rendering historical runs other than by
569
+ hand; a `duck` or simulator sound source; attaching media to X or LinkedIn
570
+ intents (no intent accepts a file); OG tags for pages other than a run.
571
+
572
+ ## Risks
573
+
574
+ - **Render time on cpu-basic** is unmeasured until the plan's first task runs;
575
+ the expectation is one to three minutes per run after the capture choice.
576
+ The worker is background and serialised, so a slow render delays a clip,
577
+ never a publish.
578
+ - **Debian's `chromium`** may lack WebCodecs' VP9 encoder or behave
579
+ differently from Chrome; the spike runs against it in the image, not only
580
+ on the Mac.
581
+ - **The Space is private today.** No link unfurls and no outsider can open
582
+ one until it is made public; the code is ready either way.
583
+ - **Every push to `main` redeploys** and kills a render in flight; the drain
584
+ at boot is what makes that harmless.
pyproject.toml CHANGED
@@ -29,6 +29,7 @@ dependencies = [
29
  "uvicorn>=0.30",
30
  "python-multipart>=0.0.9",
31
  "httpx>=0.27,<1",
 
32
  ]
33
 
34
  [project.optional-dependencies]
 
29
  "uvicorn>=0.30",
30
  "python-multipart>=0.0.9",
31
  "httpx>=0.27,<1",
32
+ "websockets>=13", # The recorder's DevTools client (arena/recorder.py).
33
  ]
34
 
35
  [project.optional-dependencies]
scripts/probe_capture.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure what a clip frame costs, three ways, on the real clip page.
2
+
3
+ uv run --frozen python scripts/probe_capture.py --origin http://127.0.0.1:8001 \
4
+ --run <run_id> --layout landscape --frames 40
5
+
6
+ Prints milliseconds per frame for: the page's own draw (JavaScript only), a
7
+ PNG screenshot, a JPEG q92 screenshot, an in-page JPEG readback (raster +
8
+ encode, no protocol), a VideoFrame readback and a VP9 WebCodecs encode. The
9
+ spec's rule: if rasterisation dominates, JPEG screenshots; if the capture
10
+ does, WebCodecs.
11
+
12
+ This script stays in the tree, not as leftover scaffolding: cpu-basic prices
13
+ frames differently from a developer laptop, so re-run it there, against the
14
+ Space's own origin, whenever the choice of screenshot format is worth
15
+ re-checking.
16
+ """
17
+
18
+ import argparse
19
+ import statistics
20
+ import time
21
+
22
+ from arena.recorder import Chrome, find_chrome
23
+
24
+ SIZES = {"landscape": (1920, 1080), "vertical": (1080, 1920)}
25
+
26
+ WEBCODECS = """
27
+ (async () => {
28
+ const canvas = document.getElementById("stage");
29
+ const support = await VideoEncoder.isConfigSupported({ codec: "vp09.00.10.08", width: canvas.width, height: canvas.height, bitrate: 12_000_000, framerate: 25 });
30
+ if (!support.supported) return { supported: false };
31
+ let chunks = 0;
32
+ const encoder = new VideoEncoder({ output: () => chunks++, error: (e) => { throw e; } });
33
+ encoder.configure(support.config);
34
+ const t0 = performance.now();
35
+ for (let i = 0; i < %(frames)d; i++) {
36
+ window.clip.draw(%(first)d + i);
37
+ const frame = new VideoFrame(canvas, { timestamp: i * 40000 });
38
+ encoder.encode(frame, { keyFrame: i === 0 });
39
+ frame.close();
40
+ }
41
+ await encoder.flush();
42
+ return { supported: true, ms: (performance.now() - t0) / %(frames)d, chunks };
43
+ })()
44
+ """
45
+
46
+
47
+ def timed(fn, n):
48
+ samples = []
49
+ for _ in range(n):
50
+ start = time.perf_counter()
51
+ fn()
52
+ samples.append((time.perf_counter() - start) * 1000)
53
+ return statistics.median(samples)
54
+
55
+
56
+ def main() -> None:
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument("--origin", required=True)
59
+ parser.add_argument("--run", required=True)
60
+ parser.add_argument("--layout", default="landscape", choices=SIZES)
61
+ parser.add_argument("--frames", type=int, default=40)
62
+ args = parser.parse_args()
63
+ width, height = SIZES[args.layout]
64
+ with Chrome(find_chrome()) as chrome:
65
+ tab = chrome.tab(width, height)
66
+ tab.navigate(f"{args.origin}/clip.html?run={args.run}&layout={args.layout}&frame=0")
67
+ tab.wait_ready()
68
+ plan = tab.evaluate("window.clip.plan")
69
+ first = plan["intro"] + 5
70
+ i = [first]
71
+
72
+ def draw():
73
+ tab.evaluate(f"window.clip.draw({i[0]})")
74
+ i[0] += 1
75
+
76
+ print(f"{args.layout} {width}x{height}, {plan['frames']} frames planned")
77
+ print(f"draw only {timed(draw, args.frames):7.1f} ms")
78
+ print(f"draw + png shot {timed(lambda: (draw(), tab.send('Page.captureScreenshot', {'format': 'png', 'optimizeForSpeed': True})), args.frames):7.1f} ms")
79
+ print(f"draw + jpeg shot {timed(lambda: (draw(), tab.send('Page.captureScreenshot', {'format': 'jpeg', 'quality': 92})), args.frames):7.1f} ms")
80
+ print(f"draw + jpeg in page {timed(lambda: (draw(), tab.evaluate('document.getElementById(\"stage\").toDataURL(\"image/jpeg\", 0.92).length')), args.frames):7.1f} ms")
81
+ print(f"draw + VideoFrame {timed(lambda: (draw(), tab.evaluate('(() => { const f = new VideoFrame(document.getElementById(\"stage\"), { timestamp: 0 }); f.close(); return 1 })()')), args.frames):7.1f} ms")
82
+ vp9 = tab.evaluate(WEBCODECS % {"frames": args.frames, "first": i[0]}, await_promise=True)
83
+ print(f"draw + vp9 encode {vp9['ms']:7.1f} ms ({vp9['chunks']} chunks)" if vp9["supported"] else "vp9 encode unsupported")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
tests/test_clips.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clips: three write-once files per run, and a worker that owes one per publish."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pytest
8
+ from fastapi.testclient import TestClient
9
+
10
+ from arena.clips import CLIP_VERSION, ClipRenderer, clip_manifest
11
+ from arena.recorder import RenderedLayout, RenderedRun, ffmpeg_args
12
+ from arena.store import LocalStore, Withdrawal
13
+ from arena.trace import encode as encode_trace
14
+ from arena.web.app import create_app
15
+ from arena.web.config import ArenaConfig
16
+ from tests.test_routes_submit import REFERENCE, submit
17
+ from tests.test_store import make_record
18
+
19
+
20
+ def test_clip_state_is_read_by_presence(tmp_path):
21
+ store = LocalStore(tmp_path)
22
+ assert store.clip_state("R1") == ("none", None)
23
+ assert store.pending_clips() == []
24
+
25
+ store.mark_clip_pending("R1", "alice", "sprint-2m", "2026-09-16T10:00:00Z")
26
+ # Written once: a re-queue after a crash must not re-date the clip.
27
+ store.mark_clip_pending("R1", "alice", "sprint-2m", "2026-09-16T11:00:00Z")
28
+ assert store.clip_state("R1") == ("pending", None)
29
+ assert store.pending_clips() == ["R1"]
30
+ pending = json.loads((tmp_path / "clips" / "R1" / "pending.json").read_text())
31
+ assert pending == {"run_id": "R1", "user": "alice", "event_id": "sprint-2m",
32
+ "queued_at": "2026-09-16T10:00:00Z"}
33
+
34
+ manifest = {"run_id": "R1", "version": 1, "layouts": {}}
35
+ store.put_clip("R1", {"clip.json": json.dumps(manifest).encode(),
36
+ "landscape.mp4": b"mp4", "poster.png": b"png"})
37
+ assert store.clip_state("R1") == ("ready", manifest)
38
+ assert store.clip_file("R1", "landscape.mp4").read_bytes() == b"mp4"
39
+ # Ready is final: the pending marker stays on disk and no longer counts.
40
+ assert store.pending_clips() == []
41
+
42
+
43
+ def test_a_failed_clip_is_its_own_file_and_leaves_the_queue(tmp_path):
44
+ store = LocalStore(tmp_path)
45
+ store.mark_clip_pending("R2", "bob", "sprint-2m", "2026-09-16T10:00:00Z")
46
+ store.fail_clip("R2", "2026-09-16T10:05:00Z", "ffmpeg exited 1")
47
+ # Written once: a second failure must not erase the first reason.
48
+ store.fail_clip("R2", "2026-09-16T10:06:00Z", "second")
49
+ assert store.clip_state("R2") == ("failed", None)
50
+ assert store.pending_clips() == []
51
+ failed = json.loads((tmp_path / "clips" / "R2" / "failed.json").read_text())
52
+ assert failed["reason"] == "ffmpeg exited 1"
53
+
54
+
55
+ def test_a_clip_is_never_written_twice(tmp_path):
56
+ store = LocalStore(tmp_path)
57
+ store.put_clip("R3", {"clip.json": b"{}"})
58
+ with pytest.raises(FileExistsError):
59
+ store.put_clip("R3", {"clip.json": b"{}"})
60
+
61
+
62
+ def test_the_encode_is_h264_with_the_pcm_muxed_and_the_live_tag_set():
63
+ args = ffmpeg_args(25, Path("/tmp/s.f32"), Path("/tmp/out.mp4"))
64
+ assert args[:2] == ["ffmpeg", "-y"]
65
+ assert ["-f", "image2pipe", "-framerate", "25", "-c:v", "mjpeg", "-i", "-"] == args[4:12]
66
+ assert ["-f", "f32le", "-ar", "48000", "-ac", "2", "-i", "/tmp/s.f32"] == args[12:20]
67
+ # Values are unique in the command; flags are not (`-c:v` names the input's
68
+ # mjpeg first), so each value is found and the flag before it is checked.
69
+ for flag, value in (("-c:v", "libx264"), ("-crf", "23"), ("-pix_fmt", "yuv420p"),
70
+ ("-c:a", "aac"), ("-b:a", "192k"), ("-metadata", "crowdMixed=true"),
71
+ ("-movflags", "+faststart+use_metadata_tags")):
72
+ assert args[args.index(value) - 1] == flag
73
+ assert "-shortest" in args
74
+ assert args[-1] == "/tmp/out.mp4"
75
+
76
+
77
+ def rendered(seconds=7.52):
78
+ layout = lambda w, h: RenderedLayout(
79
+ mp4=b"mp4", plan={"fps": 25, "frames": 188, "seconds": seconds},
80
+ crowd={"start": 1.0, "end": 5.0, "verdict": "pass"}, timing={"total_wall_ms": 1},
81
+ )
82
+ return RenderedRun(layouts={"landscape": layout(1920, 1080), "vertical": layout(1080, 1920)},
83
+ poster=b"png")
84
+
85
+
86
+ def test_the_manifest_carries_the_live_contract_per_layout():
87
+ manifest = clip_manifest("R1", rendered(), "2026-09-16T10:00:00Z")
88
+ assert manifest["version"] == CLIP_VERSION
89
+ assert manifest["poster"] == "poster.png"
90
+ land = manifest["layouts"]["landscape"]
91
+ assert land == {
92
+ "file": "landscape.mp4", "width": 1920, "height": 1080, "fps": 25, "frames": 188,
93
+ "seconds": 7.52, "crowdMixed": True,
94
+ "crowdDirection": {"start": 1.0, "end": 5.0, "verdict": "pass"},
95
+ "timing": {"total_wall_ms": 1},
96
+ }
97
+ assert manifest["layouts"]["vertical"]["width"] == 1080
98
+
99
+
100
+ def test_the_worker_renders_what_is_owed_and_records_a_failure(tmp_path):
101
+ store = LocalStore(tmp_path)
102
+ store.mark_clip_pending("R1", "alice", "sprint-2m", "2026-09-16T10:00:00Z")
103
+ store.mark_clip_pending("R2", "bob", "sprint-2m", "2026-09-16T10:01:00Z")
104
+
105
+ def render(origin, run_id, parallel, budget_s):
106
+ if run_id == "R2":
107
+ raise RuntimeError("ffmpeg exited 1")
108
+ return rendered()
109
+
110
+ said = []
111
+ worker = ClipRenderer(store, "http://127.0.0.1:1", tmp_path, render=render, log=said.append)
112
+ worker.drain()
113
+ assert [item[2] for item in sorted(worker.queue.queue)] == ["R1", "R2"]
114
+ while not worker.queue.empty():
115
+ worker.render_one(worker.queue.get()[2])
116
+ state, manifest = store.clip_state("R1")
117
+ assert state == "ready" and manifest["run_id"] == "R1"
118
+ assert store.clip_file("R1", "vertical.mp4").read_bytes() == b"mp4"
119
+ assert store.clip_state("R2") == ("failed", None)
120
+ assert any("RuntimeError: ffmpeg exited 1" in line for line in said)
121
+
122
+
123
+ def test_a_publish_owes_a_clip_only_where_a_renderer_exists(tmp_path, monkeypatch):
124
+ # An absent frontend_dir resolves to None regardless of what this machine
125
+ # has built, so `available` starts False whether or not app/dist exists.
126
+ config = ArenaConfig.from_env(
127
+ store_dir=tmp_path, dev_user="coralie", frontend_dir=tmp_path / "no-bundle",
128
+ clip_worker=False,
129
+ )
130
+ app = create_app(config)
131
+ api = TestClient(app)
132
+ run_id = submit(api, REFERENCE).json()["run_id"]
133
+ assert app.state.store.clip_state(run_id) == ("none", None)
134
+
135
+ monkeypatch.setattr(app.state.clips, "available", True)
136
+ run_id = submit(api, REFERENCE).json()["run_id"]
137
+ assert app.state.store.clip_state(run_id) == ("pending", None)
138
+ assert [item[2] for item in app.state.clips.queue.queue] == [run_id]
139
+
140
+
141
+ def test_a_backfill_owes_every_run_without_a_clip_behind_the_fresh_ones(tmp_path):
142
+ store = LocalStore(tmp_path)
143
+ old = make_record(user="alice", submitted_at="2026-09-10T10:00:00Z")
144
+ newer = make_record(user="bob", submitted_at="2026-09-12T10:00:00Z")
145
+ done = make_record(user="carol", submitted_at="2026-09-13T10:00:00Z")
146
+ gone = make_record(user="dave", submitted_at="2026-09-14T10:00:00Z")
147
+ for record in (old, newer, done, gone):
148
+ store.append(record, encode_trace(np.zeros((5, 21), dtype=np.float32)))
149
+ store.put_clip(done.run_id, {"clip.json": b"{}"})
150
+ store.withdraw(Withdrawal(run_id=gone.run_id, event_id="sprint-2m", user="dave",
151
+ withdrawn_at="2026-09-15T00:00:00Z"))
152
+ store.mark_clip_pending("R9", "erin", "sprint-2m", "2026-09-16T10:00:00Z")
153
+
154
+ worker = ClipRenderer(store, "http://127.0.0.1:1", tmp_path, backfill=True)
155
+ worker.drain()
156
+ # The fresh publish first, then the log newest first; the rendered and the
157
+ # withdrawn are not owed.
158
+ assert [item[2] for item in sorted(worker.queue.queue)] == ["R9", newer.run_id, old.run_id]
159
+
160
+ quiet = ClipRenderer(store, "http://127.0.0.1:1", tmp_path)
161
+ quiet.drain()
162
+ assert [item[2] for item in sorted(quiet.queue.queue)] == ["R9"]
163
+
164
+
165
+ def app_with_run(tmp_path):
166
+ config = ArenaConfig.from_env(store_dir=tmp_path, dev_user="alice", clip_worker=False)
167
+ app = create_app(config)
168
+ record = make_record(user="alice", policy_name="walker v2")
169
+ app.state.store.append(record, encode_trace(np.zeros((5, 21), dtype=np.float32)))
170
+ return TestClient(app), app, record
171
+
172
+
173
+ def test_the_clip_route_says_none_pending_then_ready_with_its_files(tmp_path):
174
+ api, app, record = app_with_run(tmp_path)
175
+ store = app.state.store
176
+ url = f"/api/runs/{record.run_id}/clip"
177
+ assert api.get(url).json() == {"state": "none"}
178
+ assert api.get(url).headers["cache-control"] == "no-store"
179
+ assert api.get(f"{url}/landscape.mp4").status_code == 404
180
+
181
+ store.mark_clip_pending(record.run_id, "alice", "sprint-2m", "2026-09-16T10:00:00Z")
182
+ assert api.get(url).json() == {"state": "pending"}
183
+
184
+ manifest = clip_manifest(record.run_id, rendered(), "2026-09-16T10:05:00Z")
185
+ store.put_clip(record.run_id, {"clip.json": json.dumps(manifest).encode(),
186
+ "landscape.mp4": b"L", "vertical.mp4": b"V", "poster.png": b"P"})
187
+ body = api.get(url).json()
188
+ assert body["state"] == "ready"
189
+ assert body["poster"] == f"{url}/poster.png"
190
+ assert body["layouts"]["vertical"] == {
191
+ "url": f"{url}/vertical.mp4", "width": 1080, "height": 1920, "seconds": 7.52
192
+ }
193
+
194
+ inline = api.get(f"{url}/landscape.mp4")
195
+ assert inline.status_code == 200 and inline.content == b"L"
196
+ assert inline.headers["content-type"] == "video/mp4"
197
+ assert "content-disposition" not in inline.headers
198
+ assert inline.headers["cache-control"] == "public, max-age=31536000, immutable"
199
+ saved = api.get(f"{url}/vertical.mp4?download=1")
200
+ assert saved.headers["content-disposition"] == (
201
+ 'attachment; filename="microduck-arena-alice-walker-v2-vertical.mp4"'
202
+ )
203
+ assert api.get(f"{url}/poster.png").headers["content-type"] == "image/png"
204
+ assert api.get(f"{url}/clip.json").status_code == 404
205
+ assert api.get("/api/runs/NOPE/clip").status_code == 404
206
+
207
+
208
+ def test_a_run_link_unfurls_with_the_poster_once_the_clip_is_ready(tmp_path, monkeypatch):
209
+ monkeypatch.setenv("SPACE_HOST", "arena.hf.space")
210
+ api, app, record = app_with_run(tmp_path)
211
+ page = api.get(f"/r/{record.run_id}", follow_redirects=False)
212
+ assert page.status_code == 200
213
+ assert page.headers["content-type"].startswith("text/html")
214
+ assert f'<meta property="og:url" content="https://arena.hf.space/r/{record.run_id}">' in page.text
215
+ assert '<meta property="og:title" content="@alice · walker v2 · 2 m Sprint">' in page.text
216
+ assert "og:image" not in page.text
217
+ assert f'url=/#/r/{record.run_id}' in page.text
218
+
219
+ manifest = clip_manifest(record.run_id, rendered(), "2026-09-16T10:05:00Z")
220
+ app.state.store.put_clip(record.run_id, {"clip.json": json.dumps(manifest).encode(),
221
+ "landscape.mp4": b"L", "vertical.mp4": b"V",
222
+ "poster.png": b"P"})
223
+ page = api.get(f"/r/{record.run_id}").text
224
+ assert (f'<meta property="og:image" content="https://arena.hf.space/api/runs/'
225
+ f'{record.run_id}/clip/poster.png">') in page
226
+ assert '<meta property="og:video:width" content="1920">' in page
227
+ assert '<meta name="twitter:card" content="summary_large_image">' in page
228
+ assert api.get("/r/NOPE").status_code == 404
229
+
230
+
231
+ def test_the_unfurl_escapes_what_a_submitter_typed_and_falls_back_to_the_request_host(tmp_path):
232
+ config = ArenaConfig.from_env(store_dir=tmp_path, dev_user="alice", clip_worker=False)
233
+ app = create_app(config)
234
+ record = make_record(user="alice", policy_name='x"><script>alert(1)</script>')
235
+ app.state.store.append(record, encode_trace(np.zeros((5, 21), dtype=np.float32)))
236
+ page = TestClient(app, base_url="http://testserver").get(f"/r/{record.run_id}").text
237
+ assert "<script>alert" not in page
238
+ assert "&lt;script&gt;" in page
239
+ assert f'content="http://testserver/r/{record.run_id}"' in page
tests/test_evaluate.py CHANGED
@@ -57,7 +57,7 @@ def test_trace_seed_falls_back_to_the_first_seed_when_nobody_finishes():
57
  assert pick_trace_seed(_results((7, None), (8, None))) == 7
58
 
59
 
60
- def test_evaluating_the_reference_policy_scores_and_carries_a_trace():
61
  manifest = load_event("sprint-2m")
62
  policy = load_policy(ASSET_ROOT / "policies" / "BEST_alpha_walking.onnx")
63
  result = evaluate(manifest, policy)
@@ -71,6 +71,11 @@ def test_evaluating_the_reference_policy_scores_and_carries_a_trace():
71
  assert result.score == pytest.approx(
72
  mean_finish_time(result.per_seed, manifest.time_limit_s)
73
  )
 
 
 
 
 
74
 
75
 
76
  def test_evaluate_is_deterministic():
 
57
  assert pick_trace_seed(_results((7, None), (8, None))) == 7
58
 
59
 
60
+ def test_evaluating_the_reference_policy_scores_and_carries_the_trace_seeds_replay():
61
  manifest = load_event("sprint-2m")
62
  policy = load_policy(ASSET_ROOT / "policies" / "BEST_alpha_walking.onnx")
63
  result = evaluate(manifest, policy)
 
71
  assert result.score == pytest.approx(
72
  mean_finish_time(result.per_seed, manifest.time_limit_s)
73
  )
74
+ replay = run_once(
75
+ manifest, policy, result.trace_seed, command=manifest.command_at(result.command_vx)
76
+ )
77
+ np.testing.assert_array_equal(result.trace, replay.trace)
78
+ np.testing.assert_array_equal(result.settle, replay.settle)
79
 
80
 
81
  def test_evaluate_is_deterministic():
tests/test_manifest.py CHANGED
@@ -14,6 +14,7 @@ GOOD = {
14
  '[start.perturbation]\njoint_rad=0.01\nyaw_deg=2.0\n',
15
  "termination": '[termination]\nfall_gravity_z=-0.5\nfall_hold_s=0.3\n',
16
  "sweep": '[sweep]\nlo=0.2\nhi=0.4\nstep=0.1\nfinalists=1\n',
 
17
  }
18
 
19
 
@@ -354,3 +355,47 @@ def test_every_shipped_events_metric_has_a_scoring_function():
354
 
355
  for m in all_events():
356
  assert m.metric in SCORERS, f"{m.id}: no evaluate.METRICS entry for {m.metric!r}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  '[start.perturbation]\njoint_rad=0.01\nyaw_deg=2.0\n',
15
  "termination": '[termination]\nfall_gravity_z=-0.5\nfall_hold_s=0.3\n',
16
  "sweep": '[sweep]\nlo=0.2\nhi=0.4\nstep=0.1\nfinalists=1\n',
17
+ "clip": "",
18
  }
19
 
20
 
 
355
 
356
  for m in all_events():
357
  assert m.metric in SCORERS, f"{m.id}: no evaluate.METRICS entry for {m.metric!r}"
358
+
359
+
360
+ def test_an_event_without_a_clip_section_gets_the_defaults():
361
+ clip = load_event("sprint-2m").clip
362
+ assert clip.tape_max_s == 12.0
363
+ assert clip.sounds == ("crowd", "horn", "verdict")
364
+ assert clip.camera.kind == "chase"
365
+ assert clip.camera.side is None
366
+ assert clip.to_dict() == {
367
+ "tape_max_s": 12.0,
368
+ "sounds": ["crowd", "horn", "verdict"],
369
+ "camera": {"kind": "chase", "back": 0.35, "height": 0.34, "side": None,
370
+ "target_height": 0.12, "fov": 42.0},
371
+ }
372
+
373
+
374
+ def test_a_clip_section_pins_the_tape_a_fixed_camera_and_the_sounds(tmp_path):
375
+ path = write_manifest(
376
+ tmp_path,
377
+ clip='[clip]\ntape_max_s=6.0\nsounds=["crowd"]\n'
378
+ '[clip.camera]\nkind="fixed"\nposition=[1.0,0.6,2.2]\ntarget=[1.0,0.1,0.0]\nfov=40\n',
379
+ )
380
+ clip = load_manifest(path).clip
381
+ assert clip.tape_max_s == 6.0
382
+ assert clip.sounds == ("crowd",)
383
+ assert clip.camera.to_dict() == {
384
+ "kind": "fixed", "position": [1.0, 0.6, 2.2], "target": [1.0, 0.1, 0.0], "fov": 40.0
385
+ }
386
+
387
+
388
+ @pytest.mark.parametrize(
389
+ "section, said",
390
+ [
391
+ ('[clip]\nsounds=["crowd","organ"]\n', "unknown sound source"),
392
+ ('[clip]\ntape_max_s=0\n', "tape_max_s must be positive"),
393
+ ('[clip]\nfoo=1\n', "unknown keys"),
394
+ ('[clip]\n[clip.camera]\nkind="drone"\n', "unknown camera kind"),
395
+ ('[clip]\n[clip.camera]\nkind="fixed"\nfov=40\n', "needs position and target"),
396
+ ('[clip]\n[clip.camera]\nkind="chase"\nposition=[0,0,0]\n', "unknown keys"),
397
+ ],
398
+ )
399
+ def test_a_malformed_clip_section_is_refused(tmp_path, section, said):
400
+ with pytest.raises(ManifestError, match=said):
401
+ load_manifest(write_manifest(tmp_path, clip=section))
tests/test_routes_submit.py CHANGED
@@ -78,6 +78,10 @@ def test_the_replay_of_a_fresh_submission_is_fetchable(api):
78
  trace = api.get(f"/api/runs/{run_id}/trace")
79
  assert trace.status_code == 200
80
  assert int(trace.headers["x-frame-count"]) > 100
 
 
 
 
81
 
82
 
83
  def test_a_garbage_file_is_rejected_with_its_reason(api, tmp_path):
 
78
  trace = api.get(f"/api/runs/{run_id}/trace")
79
  assert trace.status_code == 200
80
  assert int(trace.headers["x-frame-count"]) > 100
81
+ # And the settle that led into it: the sprint's 0.5 s from the reset pose.
82
+ settle = api.get(f"/api/runs/{run_id}/settle")
83
+ assert settle.status_code == 200
84
+ assert settle.headers["x-frame-count"] == "26"
85
 
86
 
87
  def test_a_garbage_file_is_rejected_with_its_reason(api, tmp_path):
tests/test_routes_trace.py CHANGED
@@ -88,6 +88,30 @@ def test_the_trace_round_trips_as_float32(client):
88
  np.testing.assert_allclose(restored, original, rtol=0, atol=1e-2)
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def test_the_trace_byte_length_matches_the_frame_count(client):
92
  api, app = client
93
  record = make_record()
@@ -106,7 +130,7 @@ def test_an_unknown_run_is_a_404(client):
106
  from a deleted one.
107
  """
108
  api, _ = client
109
- for path in ("/api/runs/01NOPE", "/api/runs/01NOPE/trace"):
110
  response = api.get(path)
111
  assert response.status_code == 404, path
112
  assert "no such run" in response.json()["detail"], path
 
88
  np.testing.assert_allclose(restored, original, rtol=0, atol=1e-2)
89
 
90
 
91
+ def test_the_settle_is_served_like_the_trace(client):
92
+ api, app = client
93
+ record = make_record()
94
+ settle = a_trace(frames=4)
95
+ app.state.store.append(record, encode(a_trace(frames=9), settle))
96
+
97
+ response = api.get(f"/api/runs/{record.run_id}/settle")
98
+ assert response.status_code == 200
99
+ assert response.headers["content-type"] == "application/octet-stream"
100
+ assert response.headers["x-frame-count"] == "4"
101
+ restored = np.frombuffer(response.content, dtype="<f4").reshape(-1, TRACE_WIDTH)
102
+ np.testing.assert_allclose(restored, settle, rtol=0, atol=1e-2)
103
+
104
+
105
+ def test_a_run_stored_before_settles_were_recorded_serves_an_empty_one(client):
106
+ api, app = client
107
+ record = make_record()
108
+ app.state.store.append(record, encode(a_trace(frames=9)))
109
+ response = api.get(f"/api/runs/{record.run_id}/settle")
110
+ assert response.status_code == 200
111
+ assert response.headers["x-frame-count"] == "0"
112
+ assert response.content == b""
113
+
114
+
115
  def test_the_trace_byte_length_matches_the_frame_count(client):
116
  api, app = client
117
  record = make_record()
 
130
  from a deleted one.
131
  """
132
  api, _ = client
133
+ for path in ("/api/runs/01NOPE", "/api/runs/01NOPE/trace", "/api/runs/01NOPE/settle"):
134
  response = api.get(path)
135
  assert response.status_code == 404, path
136
  assert "no such run" in response.json()["detail"], path
tests/test_runner.py CHANGED
@@ -113,6 +113,19 @@ def test_an_unreachable_finish_line_times_out(sprint, walker):
113
  assert outcome.trace.shape[0] == pytest.approx(3.0 / CTRL_DT, abs=1)
114
 
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  def test_the_clock_starts_on_the_start_line(sprint, walker):
117
  """The first clocked frame sits on the start line.
118
 
 
113
  assert outcome.trace.shape[0] == pytest.approx(3.0 / CTRL_DT, abs=1)
114
 
115
 
116
+ def test_the_settle_is_recorded_from_the_reset_pose(sprint, walker):
117
+ """The untimed settle has its own frames, so a replay can start where the
118
+ simulation did: frame 0 is the keyframe before any step, then one frame per
119
+ settle step, the last one control step before the first clocked frame."""
120
+ outcome = run_once(sprint, walker, seed=1)
121
+ steps = round(sprint.start.settle_s / CTRL_DT)
122
+ assert outcome.settle.shape == (steps + 1, TRACE_WIDTH)
123
+ assert outcome.settle.dtype == np.float32
124
+ key = compile_course(sprint).key(sprint.start.keyframe)
125
+ np.testing.assert_allclose(outcome.settle[0, 0:3], key.qpos[0:3], atol=1e-6)
126
+ assert np.linalg.norm(outcome.trace[0, 0:3] - outcome.settle[-1, 0:3]) < 0.02
127
+
128
+
129
  def test_the_clock_starts_on_the_start_line(sprint, walker):
130
  """The first clocked frame sits on the start line.
131
 
tests/test_trace.py CHANGED
@@ -44,3 +44,19 @@ def test_a_20_second_sprint_trace_stays_small():
44
  def test_empty_trace_round_trips():
45
  empty = np.zeros((0, TRACE_WIDTH), dtype=np.float32)
46
  assert codec.decode(codec.encode(empty)).shape == (0, TRACE_WIDTH)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def test_empty_trace_round_trips():
45
  empty = np.zeros((0, TRACE_WIDTH), dtype=np.float32)
46
  assert codec.decode(codec.encode(empty)).shape == (0, TRACE_WIDTH)
47
+
48
+
49
+ def test_the_settle_round_trips_beside_the_trace():
50
+ rng = np.random.default_rng(2)
51
+ trace = rng.uniform(-3, 3, (40, TRACE_WIDTH)).astype(np.float32)
52
+ settle = rng.uniform(-3, 3, (26, TRACE_WIDTH)).astype(np.float32)
53
+ blob = codec.encode(trace, settle)
54
+ np.testing.assert_allclose(codec.decode(blob), trace, atol=3e-3)
55
+ restored = codec.decode_settle(blob)
56
+ assert restored.dtype == np.float32
57
+ np.testing.assert_allclose(restored, settle, atol=3e-3)
58
+
59
+
60
+ def test_a_trace_stored_before_settles_were_recorded_has_none():
61
+ blob = codec.encode(np.zeros((5, TRACE_WIDTH), dtype=np.float32))
62
+ assert codec.decode_settle(blob).shape == (0, TRACE_WIDTH)
uv.lock CHANGED
@@ -247,6 +247,7 @@ dependencies = [
247
  { name = "onnxruntime" },
248
  { name = "python-multipart" },
249
  { name = "uvicorn" },
 
250
  ]
251
 
252
  [package.optional-dependencies]
@@ -271,6 +272,7 @@ requires-dist = [
271
  { name = "python-multipart", specifier = ">=0.0.9" },
272
  { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.6" },
273
  { name = "uvicorn", specifier = ">=0.30" },
 
274
  ]
275
  provides-extras = ["dev"]
276
 
@@ -587,6 +589,35 @@ wheels = [
587
  { url = "https://files.pythonhosted.org/packages/f1/79/4a20b54ab0491485ccd8c077db2d39187c7f12b3e15485d38a7be37c81b4/uvicorn-0.52.4-py3-none-any.whl", hash = "sha256:f86e41a149d7d05a9969337e3946a9c171c06a5d42680896daaba624aeac8da1", size = 79871, upload-time = "2026-08-19T06:27:40.36Z" },
588
  ]
589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  [[package]]
591
  name = "zipp"
592
  version = "4.1.0"
 
247
  { name = "onnxruntime" },
248
  { name = "python-multipart" },
249
  { name = "uvicorn" },
250
+ { name = "websockets" },
251
  ]
252
 
253
  [package.optional-dependencies]
 
272
  { name = "python-multipart", specifier = ">=0.0.9" },
273
  { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.6" },
274
  { name = "uvicorn", specifier = ">=0.30" },
275
+ { name = "websockets", specifier = ">=13" },
276
  ]
277
  provides-extras = ["dev"]
278
 
 
589
  { url = "https://files.pythonhosted.org/packages/f1/79/4a20b54ab0491485ccd8c077db2d39187c7f12b3e15485d38a7be37c81b4/uvicorn-0.52.4-py3-none-any.whl", hash = "sha256:f86e41a149d7d05a9969337e3946a9c171c06a5d42680896daaba624aeac8da1", size = 79871, upload-time = "2026-08-19T06:27:40.36Z" },
590
  ]
591
 
592
+ [[package]]
593
+ name = "websockets"
594
+ version = "17.1"
595
+ source = { registry = "https://pypi.org/simple" }
596
+ sdist = { url = "https://files.pythonhosted.org/packages/18/72/fba934cb3dff7a85d811820efffcd141ddd52b5a2a01637f64551373ff4d/websockets-17.1.tar.gz", hash = "sha256:acfea4c20bf54384883ea33b1240fc1db4f52e190823a4e2b334bc3e8bfca96a", size = 187520, upload-time = "2026-08-26T17:25:33.063Z" }
597
+ wheels = [
598
+ { url = "https://files.pythonhosted.org/packages/1d/31/5f6450a7879f4f063ef08897cc385ea3ce3f1fe17f08b11e3fd959abdf27/websockets-17.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2a0162a6372110a5601cb5c9fd826635cedf69f3e110c545dd19774e040b970e", size = 217006, upload-time = "2026-08-26T14:56:10.509Z" },
599
+ { url = "https://files.pythonhosted.org/packages/d0/2a/c1b006fc861695d2aa4e35327b842015ce1d98cf8f99241829b3d6460bfc/websockets-17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:829dba1bc049779de9b332088c1a6a9858e96bd67e50b6b644a95e02b67836bc", size = 214690, upload-time = "2026-08-26T14:56:11.681Z" },
600
+ { url = "https://files.pythonhosted.org/packages/46/69/66e5b7d01445e0eeb1d4ab419c30315f2c90cf7a8a8cd4ecc47f894dba54/websockets-17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fd8f47dbf2e8adb15c847215f83436de3fdb120b51fdae0fbbdf69fd97a3ad80", size = 214947, upload-time = "2026-08-26T14:56:12.923Z" },
601
+ { url = "https://files.pythonhosted.org/packages/07/ce/033cafe2d2538562efa876b9149a2c7a0f7787870a4b1bb6e28adc9ceb6b/websockets-17.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:9f4c0377a83e163a303514fdfab501dbe379bdc13e5b9312a91d112658b29dce", size = 224329, upload-time = "2026-08-26T14:56:14.212Z" },
602
+ { url = "https://files.pythonhosted.org/packages/34/c7/e1c2e8a67f6cc0aa43abe0046fb3b7a020980649e6a843751dc7ce9eb170/websockets-17.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:c3241d684a76eaaef8b2dc789afde4343cd3aad55ea81e4e8ab3605b529bae51", size = 224611, upload-time = "2026-08-26T14:56:15.702Z" },
603
+ { url = "https://files.pythonhosted.org/packages/be/de/07c6d48eb3d2069709410c851e7de10ab83d752c4bd09862899627c2729b/websockets-17.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e5f5c7a893507d0e83a80b88aefd6522f7e882cd53f9722c6f23f5a020c9557c", size = 225848, upload-time = "2026-08-26T14:56:16.962Z" },
604
+ { url = "https://files.pythonhosted.org/packages/f3/dd/3c68572d20509648cc2fb6f50ccf3deeb4b87270f2c8966e99476e278ea3/websockets-17.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:00bf34b64501e3477e81fc281532ff3cbf4da26633c10b63979d5085d46602d3", size = 227290, upload-time = "2026-08-26T14:56:18.204Z" },
605
+ { url = "https://files.pythonhosted.org/packages/0a/4a/8f6651c8a22093539c9215af0c5bbf217b87b382c99d2112039b92d593c2/websockets-17.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ce0305b702b20d1e1d60a9aaace6bc89970e1753565543f310d549eab22c2435", size = 226476, upload-time = "2026-08-26T14:56:19.459Z" },
606
+ { url = "https://files.pythonhosted.org/packages/f5/be/f6fc33cea86b1127fd1297b18c107e81580ab55a73a39f9a934441ef321f/websockets-17.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29176d8b429cfa0fa443c473878d37a5c06cfd0cb36b71ba4314accc71e05906", size = 225233, upload-time = "2026-08-26T14:56:20.939Z" },
607
+ { url = "https://files.pythonhosted.org/packages/cb/83/65edaf05f7c9b1dea82f4d252fdc37706a84571646f06119a27b0a16fe19/websockets-17.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:3709a1ab30b4b922027d22f68d2b61a0656a91680ac894a537624e6be7dd7f7c", size = 222488, upload-time = "2026-08-26T14:56:22.208Z" },
608
+ { url = "https://files.pythonhosted.org/packages/07/42/d1169c2f7f1f0032b0d4b0c00f0711a070cd7c735de37bfeb876bc0f9606/websockets-17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:43bd0c1ceb924d67f5c1a5254d8361dd9d94246e6331a726064dfa2917880780", size = 225295, upload-time = "2026-08-26T14:56:23.445Z" },
609
+ { url = "https://files.pythonhosted.org/packages/a6/f4/64e2a386c3899b917c2933225c9b47887874229d159797f3bf1a11c20d51/websockets-17.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:1fce0f43e0d41422e0b2cad6561e1970df22f212f4c7e884967df7cf591b031c", size = 223891, upload-time = "2026-08-26T14:56:24.647Z" },
610
+ { url = "https://files.pythonhosted.org/packages/26/b3/dfb5c482f7e310a3432fdbb045ddfe6d34114680e89a233d4ff900a32961/websockets-17.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:4031152769179ab8dcdeafc7b0e58052a49117560a28671700b47b2c7b717aad", size = 224661, upload-time = "2026-08-26T14:56:26.027Z" },
611
+ { url = "https://files.pythonhosted.org/packages/a4/cf/94865130a336029f46412adc127c4fbe380f46172b90ce251369e35c4302/websockets-17.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a06f3b5085176763182449559e20391d7ce616a8972a9f7a33deda87ea6d4f3c", size = 225766, upload-time = "2026-08-26T14:56:27.455Z" },
612
+ { url = "https://files.pythonhosted.org/packages/96/34/eb8c658f86dfe562ed49a887a27424bfe9e618c26ea6f865b093d075d3a6/websockets-17.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:77b37cceca17291897c3c73bd30a7c7c7909593554b5da574ec852af83c1742a", size = 223323, upload-time = "2026-08-26T14:56:28.807Z" },
613
+ { url = "https://files.pythonhosted.org/packages/1b/7e/2629609652ece5ca0c7ac235927dd4511b08131e3a5d53439b798fddf002/websockets-17.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d8e83333385cac6030a5167fd18bf96cc6c58b914c308e683f05b0cf94bc8dd0", size = 224276, upload-time = "2026-08-26T14:56:29.991Z" },
614
+ { url = "https://files.pythonhosted.org/packages/a1/6b/8525737fe840b38e5f40956c198fb586a4fac1e07144d41a5b949b989cf8/websockets-17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:073c5c3f7e127041fa9d34a9e29ceefee8c3cafbd267ed2927318f425144380d", size = 224558, upload-time = "2026-08-26T14:56:31.184Z" },
615
+ { url = "https://files.pythonhosted.org/packages/74/ab/3a958c6cbcf74b118f601c20a80ac8bd5e8dfec0bcf7345116feaeefb121/websockets-17.1-cp313-cp313-win32.whl", hash = "sha256:2afb58c7ba48b329d56769f8dfd89f394efe587b65ef806bae810a484d6d3608", size = 217475, upload-time = "2026-08-26T14:56:32.431Z" },
616
+ { url = "https://files.pythonhosted.org/packages/22/36/fb521f0f2994c25509651f169efe5582dddd8713d57a0757ba87859372ef/websockets-17.1-cp313-cp313-win_amd64.whl", hash = "sha256:0340bbef6bfbe16da888b3983d666a4db4954ac3253c38f13bc7aba0c7db5a2f", size = 217784, upload-time = "2026-08-26T14:56:33.608Z" },
617
+ { url = "https://files.pythonhosted.org/packages/68/92/9b8419584681a12a7534b746dfb2737c466efe2455483e2fbf8b941a04ec/websockets-17.1-cp313-cp313-win_arm64.whl", hash = "sha256:7a72efa3bf4fa3a6669a54420a472ad056da3973d827f10e3a536da463f926c2", size = 217715, upload-time = "2026-08-26T14:56:34.865Z" },
618
+ { url = "https://files.pythonhosted.org/packages/41/63/23572870e01836a98346075b9e17a8bc24a6ddd9800a3204ceee58677f3c/websockets-17.1-py3-none-any.whl", hash = "sha256:f221081107b8c48184d99f7019604486376e7ef826037e70aad6b02540732c23", size = 211134, upload-time = "2026-08-26T17:25:31.397Z" },
619
+ ]
620
+
621
  [[package]]
622
  name = "zipp"
623
  version = "4.1.0"