feat(selection): put a floor under the clip count

Prod measurement, 3-ago-2026: 408 of 429 jobs (95%) delivered three clips or
fewer, the mode being ONE. Cross-referenced against retention on the cohort
that signed up 3-7 days ago (old enough to have returned, recent enough that
the 7-day purge has not deleted their user_videos rows):

    clips delivered   users   came back a 2nd day
    1-3                 251   0.4%
    4-9                  31   16.1%

Forty times the retention on the far side of a boundary that 95% of jobs never
crossed. That is the mechanism behind the 96.7% of users who only ever use the
product on a single day.

The shortlist was not the constraint — a 5-minute video already shortlists 5
windows. The detail prompt was: it asked to "prefer one great clip per
candidate window", and both the 2-second rule and STANDS ALONE end in "or skip
it" with no lower bound, as does DIVERSITY's "drop the other". Three rules
pushing down and nothing holding the count up collapses to one clip.

clip_count_targets() now derives a floor and a ceiling from the shortlist size
(3 windows -> 3-6, 5 -> 4-10, 10+ -> 6-12) and the prompt states it. Every
quality rule is untouched — they are validated at 82% against random windows
and this change does not spend that.

A/B on 8 real prod transcripts (3.5-18 min, all of which delivered 1-3 clips in
production), sharing the score pass between variants so only the detail prompt
differs:

    OLD  mean 2.75  median 2.5  <=3 clips: 6/8
    NEW  mean 4.00  median 4.0  <=3 clips: 3/8
    better on 7 of 8, worse on none, one tie (sign test p = 0.016)

The ceiling never bound: the most any video produced was 5 against a ceiling of
8-12, so the model is not padding to hit a number — the floor and the removal
of the one-per-window bias are doing the work. That is the outcome to want.

Read the limits honestly. Three of eight still land at three or fewer, and the
sample under-represents the sub-5-minute videos that are 54% of real jobs and
the hardest case here: both short videos in the set shortlisted only 2 windows
out of the 3-4 that existed, because the SCORE pass returned fewer usable
windows than it was given. That is the next thing to look at, and it caps this
change on exactly the videos that matter most.

CLIP_TARGET_MIN / CLIP_TARGET_MAX override both bounds for further A/B runs
without a deploy.
This commit is contained in:
juancarlos.cavero 2026-08-03 11:17:33 +02:00
parent db3e7849af
commit 18f2cf4dbd
4 changed files with 129 additions and 9 deletions

View file

@ -26,6 +26,47 @@ def lookup_model_prices(model_name):
return MODEL_PRICES[best_key] if best_key else None
def clip_count_targets(n_windows):
"""How many clips to ask the detail pass for, given the shortlist size.
Measured on prod 3-ago-2026: 408 of 429 jobs (95%) delivered 3 clips or
fewer, the mode being ONE, while the prompt was free to return one per
shortlisted window. Users who received 1-3 clips came back a second day
0.4% of the time; those who received 4-9 came back 16.1% — so the clip
count, not the clip quality, is what the retention curve hangs on.
The old prompt biased hard the other way ("prefer one great clip per
candidate window") and handed the model two unbounded licences to drop
clips (the 2-second rule and STANDS ALONE both end in "or skip it"), with
no floor to stop it collapsing to a single clip. This puts a floor and a
realistic ceiling on it instead.
``CLIP_TARGET_MIN`` / ``CLIP_TARGET_MAX`` override both for A/B runs
without a deploy (the reframe-testing harness drives them).
"""
import os
n = max(1, int(n_windows or 1))
# Floor grows with the material: 3 windows -> 3, 5 -> 4, 10+ -> 6.
low = max(2, min(6, n // 2 + 2))
# Ceiling allows a rich window to yield more than one without inviting padding.
high = min(12, max(4, n * 2))
low = min(low, high)
def _override(name, current):
raw = os.environ.get(name)
if not raw:
return current
try:
return max(1, int(raw))
except ValueError:
return current
low = _override("CLIP_TARGET_MIN", low)
high = _override("CLIP_TARGET_MAX", high)
return low, max(low, high)
def compact_words(words, precision=2):
"""Round word timestamps for prompts — full float precision wastes tokens."""
return [

View file

@ -9,7 +9,7 @@ from google import genai
from google.genai import types as genai_types
from pydantic import BaseModel
from clip_selection import lookup_model_prices
from clip_selection import clip_count_targets, lookup_model_prices
load_dotenv()
@ -254,10 +254,17 @@ CLIP RULES:
A brilliant moment that needs the previous five minutes is not a clip.
Fix this by moving the START earlier, never by cutting the ending short: a
clip that loses its payoff to gain context has traded down.
- Prefer one great clip per candidate window. Maximum 2 clips per window only if clearly justified.
- HOW MANY: return {min_clips} to {max_clips} clips. Work through EVERY candidate
window — they were already scored as the best moments in the video, so a window
that yields nothing should be the exception, not the norm. Two or three clips
from one window are fine when they are genuinely different moments. The rules
above let you skip a weak clip; they are not a licence to return one clip and
stop. Only fall short of {min_clips} when the material truly does not hold
them, and never pad with a clip you would not publish yourself.
- DIVERSITY: never return two clips that make the same point, tell the same
story, or land the same joke — even across different windows. Pick the
stronger one and drop the other.
stronger one and drop the other. Two clips on the same broad topic are fine
as long as each lands its own moment.
HOOK PLAYBOOK — pick the strongest fitting pattern for `viral_hook_text` (max 10 words):
- Open question: "Why does everyone get this wrong?"
@ -498,11 +505,17 @@ def main() -> int:
language = str(payload.get("language") or "unknown")
template = SCORE_PROMPT_TEMPLATE if args.mode == "score" else DETAIL_PROMPT_TEMPLATE
prompt = template.format(
video_duration=payload["video_duration"],
language=language,
windows_json=json.dumps(payload["windows"], ensure_ascii=False),
)
fmt = {
"video_duration": payload["video_duration"],
"language": language,
"windows_json": json.dumps(payload["windows"], ensure_ascii=False),
}
if args.mode != "score":
# Score mode receives every window, not a shortlist, so a count target
# derived from it would be meaningless — and the score template has no
# placeholder for one anyway.
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
prompt = template.format(**fmt)
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
response = client.models.generate_content(

View file

@ -23,7 +23,7 @@ from google.genai import types as genai_types
import gemini_worker
import layout_picker
from clip_selection import build_transcript_windows, snap_clip_to_words
from clip_selection import build_transcript_windows, clip_count_targets, snap_clip_to_words
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
@ -1274,8 +1274,10 @@ def get_viral_clips(transcript_result, video_duration):
# --- Pass 2: detailed clip extraction on the shortlist ---
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist]
min_clips, max_clips = clip_count_targets(len(shortlist))
prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
video_duration=video_duration, language=language,
min_clips=min_clips, max_clips=max_clips,
windows_json=json.dumps(payload, ensure_ascii=False))
detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse)
if cost:

View file

@ -1,6 +1,11 @@
"""Tests for the pure clip-selection helpers (windows, snapping, pricing)."""
import re
import pytest
from clip_selection import (
build_transcript_windows,
clip_count_targets,
snap_clip_to_words,
compact_words,
lookup_model_prices,
@ -98,3 +103,62 @@ class TestCompactWords:
def test_rounds_timestamps(self):
words = [{"w": " hi", "s": 17.240000000000002, "e": 17.899999999999999}]
assert compact_words(words) == [{"w": " hi", "s": 17.24, "e": 17.9}]
class TestClipCountTargets:
"""The floor is the whole point: prod was delivering a single clip on the
mode, and users who got 1-3 came back 0.4% of the time against 16% for 4-9.
"""
def test_floor_clears_the_dead_zone_once_there_is_material(self):
# 4+ shortlisted windows must not be allowed to return the 1-3 band.
for n in (4, 5, 6, 8, 10):
low, high = clip_count_targets(n)
assert low >= 4, f"{n} windows asked for only {low}"
assert high >= low
def test_tiny_shortlists_stay_modest(self):
assert clip_count_targets(1)[0] <= 2
assert clip_count_targets(2)[0] <= 3
def test_ceiling_is_capped_so_long_videos_do_not_explode(self):
assert clip_count_targets(40) == clip_count_targets(12)
assert clip_count_targets(40)[1] <= 12
def test_low_never_exceeds_high(self):
for n in range(1, 40):
low, high = clip_count_targets(n)
assert low <= high
def test_degenerate_input_does_not_crash(self):
assert clip_count_targets(0)[0] >= 1
assert clip_count_targets(None)[0] >= 1
def test_env_overrides_for_ab_runs(self, monkeypatch):
monkeypatch.setenv("CLIP_TARGET_MIN", "1")
monkeypatch.setenv("CLIP_TARGET_MAX", "2")
assert clip_count_targets(5) == (1, 2)
def test_garbage_env_falls_back_to_computed(self, monkeypatch):
baseline = clip_count_targets(5)
monkeypatch.setenv("CLIP_TARGET_MIN", "not-a-number")
assert clip_count_targets(5) == baseline
def test_override_min_above_max_still_orders(self, monkeypatch):
monkeypatch.setenv("CLIP_TARGET_MIN", "9")
monkeypatch.setenv("CLIP_TARGET_MAX", "3")
low, high = clip_count_targets(5)
assert low <= high
class TestDetailPromptCarriesTheCount:
def test_template_formats_with_the_targets(self):
gw = pytest.importorskip("gemini_worker")
low, high = clip_count_targets(5)
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
video_duration=300, language="es", min_clips=low, max_clips=high,
windows_json="[]")
assert f"return {low} to {high} clips" in prompt
# The JSON schema example legitimately keeps braces (they are {{ }} in
# the template), so assert on unsubstituted placeholders specifically.
assert re.findall(r"\{[a-z_]+\}", prompt) == []